How to use middleware with routing in FastAPI - python-3.x

I am following the FastAPI documentation here and trying to implement routing with a middleware.
My main contains:
app = FastAPI()
app.include_router(
SomeService.router,
prefix="/services",
tags=["services"]
)
#app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
When sending a request, it is correctly executed and returns the right value but does not contain the value appended through the middleware.
I have tried defining the middleware inside the service route
and defining the middleware before app.include_router

The documentation about middleware mentions that if
(...) you want a client in a browser to be able to see [the custom headers], you need to add them to your CORS configurations, using the parameter expose_headers documented in Starlette's CORS docs.

Related

Adding new endpoint to FastAPI at runtime

I have a API Gateway service based on FastAPI and some specific services (like plugins) to connect with it. One of them - Auth service dealing with user accounts and access-tokens.
For example Auth service wants to tell AG about new functionality he provides and to register new endpoint in AG at runtime.
I see the following steps:
Auth creates new endpoint in AG, /new_endpoint for example;
All the traffic going to http://AG/new_endpoint will be redirected to http://Auth/...
I looked at the method FastAPI.add_api_route to add new endpoint. It works at runtime - I checked using curl.
There is no effect after refreshing http://AG/docs page because OpenAPI schema is cached.
I would like to re-generate OpenAPI schema and see /new_endpoint on the OpenAPI page.
I think I found the solution how to re-generate OpenAPI schema.
Drop cache app.openapi_schema = None
Re-generate schema app.setup()
from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from pydantic import BaseModel
app = FastAPI()
class NewEndpointResponse(BaseModel):
status: str
method: str
url_path: str
async def catch_all(request: Request) -> JSONResponse:
"""
Your new endpoint handler
"""
# some logic to interact with Auth-service
# like: requests.get("http://Auth/...")
res = NewEndpointResponse(status="OK", method=request.method, url_path=request.url.path)
return JSONResponse(res.dict(), status_code=200)
class EndpointRegisterDTO(BaseModel):
endpoint: str = "/new_endpoint"
method: str = "GET"
name: str = "Extra Functionality"
#app.post("/register/endpoint")
async def add_endpoint(request: EndpointRegisterDTO):
"""
Adds new endpoint at runtime
"""
app.add_api_route(
request.endpoint,
catch_all,
methods=[request.method],
name=request.name,
response_model=NewEndpointResponse)
app.openapi_schema = None
app.setup()
return {"status": "OK"}
Open http://AG/docs. Only one endpoint is available.
Press "Try it out" and do POST /register/endpoint with suggested parameters.
Refresh http://AG/docs - now you can see /new_endpoint.
Call GET /new_endpoint and check that response is correct.
The solution is ugly a bit, but it works!
I think it's bloody hard to debug it!

how to make fastapi use x-gitlab-token header for authentication

I used this documentation to secure some endpoints in my fastapi app.
It seemed to be working fine, and I was also able to run some tests (using pytest):
...
client = TestClient(app=app)
response = client.post(
"/my_end_point",
json={'data':'model'},
headers={"Authorization": f"Bearer {token}"},
)
...
My problem is, I want to connect my app to a Gitlab Webhook, and when doing that, Gitlab sends this header:
{'x-gitlab-token':'some-token-that-can-be-defined-when-setting-up-the-webhook'}
That means, even if I configure a valid token in the Gitlab Webhook configuration, it is not accepted by my FastAPI app, which returns 401 Not authorized error.
I guess my question is how to instruct FastApi to take the token from 'x-gitlab-token' key and not from 'Authorization' key
There's an example of how you can use Header in a dependency function in FastAPI's user guide.
A self-contained example:
import uvicorn
from fastapi import (
Depends,
FastAPI,
Header,
HTTPException,
)
def authenticate_gitlab(x_gitlab_token: str = Header(...)):
if x_gitlab_token != 'magic':
raise HTTPException(status_code=403)
return x_gitlab_token
app = FastAPI()
#app.get("/")
async def req(authenticated_with: str = Depends(authenticate_gitlab)):
return {'authenticated_with': authenticated_with}
if __name__ == "__main__":
uvicorn.run("foo:app", host="127.0.0.1", port=5000, log_level="info")
This accepts any request with X-Gitlab-Token set to magic, while refusing other keys:
λ curl http://localhost:5000 -H "X-GitLab-Token: foo"
{"detail":"Forbidden"}
λ curl http://localhost:5000 -H "X-GitLab-Token: magic"
{"authenticated_with":"magic"}
You can use the dependencies argument when creating an APIRouter to have the dependency run before every route in a given router (which you can composition together as you need from multiple routers):
authenticated_router = APIRouter(dependencies=[Depends(authenticate_gitlab)])

FastAPI - can't access path parameters from middleware

My typical path is something like
/user/{user_id}/resource/{resource_id}
I have a validation method, already written in async python, like this:
async def is_allowed(user_id: int, resource_id: int) -> bool
That returns a boolean: true if the user can access the resource, false otherwise.
I want to write a middleware that calls is_allowed extracting the variables from the path.
I fiddled around but I can't find how to get them: I was expecting to get this information from request.path_params.
A somehow more complete example (edited following #Marcelo Trylesinski answer):
import logging
from fastapi import FastAPI
from starlette.requests import Request
from starlette.responses import Response
app = FastAPI()
_logger = logging.getLogger()
_logger.setLevel(logging.DEBUG)
async def is_allowed(user_id, resource_id):
_logger.error(user_id)
_logger.error(resource_id)
return True
#app.middleware('http')
async def acl(request: Request, call_next):
user_id = request.path_params.get("user_id", None)
resource_id = request.path_params.get("resource_id", None)
allowed = await is_allowed(user_id, resource_id)
if not allowed:
return Response(status_code=403)
else:
return await call_next(request)
#app.get('/user/{user_id}/resource/{resource_id}')
async def my_handler(user_id: int, resource_id: int):
return {"what": f"Doing stuff with {user_id} on {resource_id}"}
The logged values are None.
You will not be able to achieve your goal with a Middleware, because Middlewares are executed before the routing.
Therefore FastAPI/Starlette doesn't know which path it will match to and cannot populate path_params.
You will have to use a different solution, such as passing these params on a cookie, header or query arg, or using a decorator/Dependency.
Reference:
https://github.com/encode/starlette/issues/230
https://fastapi.tiangolo.com/tutorial/middleware/#middleware

How to send a GraphQL query to AppSync from python?

How do we post a GraphQL request through AWS AppSync using boto?
Ultimately I'm trying to mimic a mobile app accessing our stackless/cloudformation stack on AWS, but with python. Not javascript or amplify.
The primary pain point is authentication; I've tried a dozen different ways already. This the current one, which generates a "401" response with "UnauthorizedException" and "Permission denied", which is actually pretty good considering some of the other messages I've had. I'm now using the 'aws_requests_auth' library to do the signing part. I assume it authenticates me using the stored /.aws/credentials from my local environment, or does it?
I'm a little confused as to where and how cognito identities and pools will come into it. eg: say I wanted to mimic the sign-up sequence?
Anyways the code looks pretty straightforward; I just don't grok the authentication.
from aws_requests_auth.boto_utils import BotoAWSRequestsAuth
APPSYNC_API_KEY = 'inAppsyncSettings'
APPSYNC_API_ENDPOINT_URL = 'https://aaaaaaaaaaaavzbke.appsync-api.ap-southeast-2.amazonaws.com/graphql'
headers = {
'Content-Type': "application/graphql",
'x-api-key': APPSYNC_API_KEY,
'cache-control': "no-cache",
}
query = """{
GetUserSettingsByEmail(email: "john#washere"){
items {name, identity_id, invite_code}
}
}"""
def test_stuff():
# Use the library to generate auth headers.
auth = BotoAWSRequestsAuth(
aws_host='aaaaaaaaaaaavzbke.appsync-api.ap-southeast-2.amazonaws.com',
aws_region='ap-southeast-2',
aws_service='appsync')
# Create an http graphql request.
response = requests.post(
APPSYNC_API_ENDPOINT_URL,
json={'query': query},
auth=auth,
headers=headers)
print(response)
# this didn't work:
# response = requests.post(APPSYNC_API_ENDPOINT_URL, data=json.dumps({'query': query}), auth=auth, headers=headers)
Yields
{
"errors" : [ {
"errorType" : "UnauthorizedException",
"message" : "Permission denied"
} ]
}
It's quite simple--once you know. There are some things I didn't appreciate:
I've assumed IAM authentication (OpenID appended way below)
There are a number of ways for appsync to handle authentication. We're using IAM so that's what I need to deal with, yours might be different.
Boto doesn't come into it.
We want to issue a request like any regular punter, they don't use boto, and neither do we. Trawling the AWS boto docs was a waste of time.
Use the AWS4Auth library
We are going to send a regular http request to aws, so whilst we can use python requests they need to be authenticated--by attaching headers.
And, of course, AWS auth headers are special and different from all others.
You can try to work out how to do it
yourself, or you can go looking for someone else who has already done it: Aws_requests_auth, the one I started with, probably works just fine, but I have ended up with AWS4Auth. There are many others of dubious value; none endorsed or provided by Amazon (that I could find).
Specify appsync as the "service"
What service are we calling? I didn't find any examples of anyone doing this anywhere. All the examples are trivial S3 or EC2 or even EB which left uncertainty. Should we be talking to api-gateway service? Whatsmore, you feed this detail into the AWS4Auth routine, or authentication data. Obviously, in hindsight, the request is hitting Appsync, so it will be authenticated by Appsync, so specify "appsync" as the service when putting together the auth headers.
It comes together as:
import requests
from requests_aws4auth import AWS4Auth
# Use AWS4Auth to sign a requests session
session = requests.Session()
session.auth = AWS4Auth(
# An AWS 'ACCESS KEY' associated with an IAM user.
'AKxxxxxxxxxxxxxxx2A',
# The 'secret' that goes with the above access key.
'kwWxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxgEm',
# The region you want to access.
'ap-southeast-2',
# The service you want to access.
'appsync'
)
# As found in AWS Appsync under Settings for your endpoint.
APPSYNC_API_ENDPOINT_URL = 'https://nqxxxxxxxxxxxxxxxxxxxke'
'.appsync-api.ap-southeast-2.amazonaws.com/graphql'
# Use JSON format string for the query. It does not need reformatting.
query = """
query foo {
GetUserSettings (
identity_id: "ap-southeast-2:8xxxxxxb-7xx4-4xx4-8xx0-exxxxxxx2"
){
user_name, email, whatever
}}"""
# Now we can simply post the request...
response = session.request(
url=APPSYNC_API_ENDPOINT_URL,
method='POST',
json={'query': query}
)
print(response.text)
Which yields
# Your answer comes as a JSON formatted string in the text attribute, under data.
{"data":{"GetUserSettings":{"user_name":"0xxxxxxx3-9102-42f0-9874-1xxxxx7dxxx5"}}}
Getting credentials
To get rid of the hardcoded key/secret you can consume the local AWS ~/.aws/config and ~/.aws/credentials, and it is done this way...
# Use AWS4Auth to sign a requests session
session = requests.Session()
credentials = boto3.session.Session().get_credentials()
session.auth = AWS4Auth(
credentials.access_key,
credentials.secret_key,
boto3.session.Session().region_name,
'appsync',
session_token=credentials.token
)
...<as above>
This does seem to respect the environment variable AWS_PROFILE for assuming different roles.
Note that STS.get_session_token is not the way to do it, as it may try to assume a role from a role, depending where it keyword matched the AWS_PROFILE value. Labels in the credentials file will work because the keys are right there, but names found in the config file do not work, as that assumes a role already.
OpenID
In this scenario, all the complexity is transferred to the conversation with the openid connect provider. The hard stuff is all the auth hoops you jump through to get an access token, and thence using the refresh token to keep it alive. That is where all the real work lies.
Once you finally have an access token, assuming you have configured the "OpenID Connect" Authorization Mode in appsync, then you can, very simply, drop the access token into the header:
response = requests.post(
url="https://nc3xxxxxxxxxx123456zwjka.appsync-api.ap-southeast-2.amazonaws.com/graphql",
headers={"Authorization": ACCESS_TOKEN},
json={'query': "query foo{GetStuff{cat, dog, tree}}"}
)
You can set up an API key on the AppSync end and use the code below. This works for my case.
import requests
# establish a session with requests session
session = requests.Session()
# As found in AWS Appsync under Settings for your endpoint.
APPSYNC_API_ENDPOINT_URL = 'https://vxxxxxxxxxxxxxxxxxxy.appsync-api.ap-southeast-2.amazonaws.com/graphql'
# setup the query string (optional)
query = """query listItemsQuery {listItemsQuery {items {correlation_id, id, etc}}}"""
# Now we can simply post the request...
response = session.request(
url=APPSYNC_API_ENDPOINT_URL,
method='POST',
headers={'x-api-key': '<APIKEYFOUNDINAPPSYNCSETTINGS>'},
json={'query': query}
)
print(response.json()['data'])
Building off Joseph Warda's answer you can use the class below to send AppSync commands.
# fileName: AppSyncLibrary
import requests
class AppSync():
def __init__(self,data):
endpoint = data["endpoint"]
self.APPSYNC_API_ENDPOINT_URL = endpoint
self.api_key = data["api_key"]
self.session = requests.Session()
def graphql_operation(self,query,input_params):
response = self.session.request(
url=self.APPSYNC_API_ENDPOINT_URL,
method='POST',
headers={'x-api-key': self.api_key},
json={'query': query,'variables':{"input":input_params}}
)
return response.json()
For example in another file within the same directory:
from AppSyncLibrary import AppSync
APPSYNC_API_ENDPOINT_URL = {YOUR_APPSYNC_API_ENDPOINT}
APPSYNC_API_KEY = {YOUR_API_KEY}
init_params = {"endpoint":APPSYNC_API_ENDPOINT_URL,"api_key":APPSYNC_API_KEY}
app_sync = AppSync(init_params)
mutation = """mutation CreatePost($input: CreatePostInput!) {
createPost(input: $input) {
id
content
}
}
"""
input_params = {
"content":"My first post"
}
response = app_sync.graphql_operation(mutation,input_params)
print(response)
Note: This requires you to activate API access for your AppSync API. Check this AWS post for more details.
graphql-python/gql supports AWS AppSync since version 3.0.0rc0.
It supports queries, mutation and even subscriptions on the realtime endpoint.
The documentation is available here
Here is an example of a mutation using the API Key authentication:
import asyncio
import os
import sys
from urllib.parse import urlparse
from gql import Client, gql
from gql.transport.aiohttp import AIOHTTPTransport
from gql.transport.appsync_auth import AppSyncApiKeyAuthentication
# Uncomment the following lines to enable debug output
# import logging
# logging.basicConfig(level=logging.DEBUG)
async def main():
# Should look like:
# https://XXXXXXXXXXXXXXXXXXXXXXXXXX.appsync-api.REGION.amazonaws.com/graphql
url = os.environ.get("AWS_GRAPHQL_API_ENDPOINT")
api_key = os.environ.get("AWS_GRAPHQL_API_KEY")
if url is None or api_key is None:
print("Missing environment variables")
sys.exit()
# Extract host from url
host = str(urlparse(url).netloc)
auth = AppSyncApiKeyAuthentication(host=host, api_key=api_key)
transport = AIOHTTPTransport(url=url, auth=auth)
async with Client(
transport=transport, fetch_schema_from_transport=False,
) as session:
query = gql(
"""
mutation createMessage($message: String!) {
createMessage(input: {message: $message}) {
id
message
createdAt
}
}"""
)
variable_values = {"message": "Hello world!"}
result = await session.execute(query, variable_values=variable_values)
print(result)
asyncio.run(main())
I am unable to add a comment due to low rep, but I just want to add that I tried the accepted answer and it didn't work. I was getting an error saying my session_token is invalid. Probably because I was using AWS Lambda.
I got it to work pretty much exactly, but by adding to the session token parameter of the aws4auth object. Here's the full piece:
import requests
import os
from requests_aws4auth import AWS4Auth
def AppsyncHandler(event, context):
# These are env vars that are always present in an AWS Lambda function
# If not using AWS Lambda, you'll need to add them manually to your env.
access_id = os.environ.get("AWS_ACCESS_KEY_ID")
secret_key = os.environ.get("AWS_SECRET_ACCESS_KEY")
session_token = os.environ.get("AWS_SESSION_TOKEN")
region = os.environ.get("AWS_REGION")
# Your AppSync Endpoint
api_endpoint = os.environ.get("AppsyncConnectionString")
resource = "appsync"
session = requests.Session()
session.auth = AWS4Auth(access_id,
secret_key,
region,
resource,
session_token=session_token)
The rest is the same.
Hope this Helps Everyone
import requests
import json
import os
from dotenv import load_dotenv
load_dotenv(".env")
class AppSync(object):
def __init__(self,data):
endpoint = data["endpoint"]
self.APPSYNC_API_ENDPOINT_URL = endpoint
self.api_key = data["api_key"]
self.session = requests.Session()
def graphql_operation(self,query,input_params):
response = self.session.request(
url=self.APPSYNC_API_ENDPOINT_URL,
method='POST',
headers={'x-api-key': self.api_key},
json={'query': query,'variables':{"input":input_params}}
)
return response.json()
def main():
APPSYNC_API_ENDPOINT_URL = os.getenv("APPSYNC_API_ENDPOINT_URL")
APPSYNC_API_KEY = os.getenv("APPSYNC_API_KEY")
init_params = {"endpoint":APPSYNC_API_ENDPOINT_URL,"api_key":APPSYNC_API_KEY}
app_sync = AppSync(init_params)
mutation = """
query MyQuery {
getAccountId(id: "5ca4bbc7a2dd94ee58162393") {
_id
account_id
limit
products
}
}
"""
input_params = {}
response = app_sync.graphql_operation(mutation,input_params)
print(json.dumps(response , indent=3))
main()

What's the Pythonic way to add a parameter to many of the function calls in my code?

I have a Python (3.6) web server using aiohttp with a lot of routes in it. The handler in my routes usually looks like this:
async def __call__(self, request):
response1 = await call_service_1('aaa')
response2 = await call_service_2('bbb')
response3 = await call_service_3('ccc')
return [response1, response2, response3]
And a service call looks like:
async def call_service1(self, arg):
url = 'http://localhost/' + arg
headers = {'Content-Type': 'application/json'}
async with self.client_session.get(url, headers=headers) as response:
return response
I have a new requirement in which I need to read a header value in the request, and pass that on as a header in my subsequent service requests. I have this requirement for all of my routes and all of my service calls. My initial attempt to fulfil this requirement would be to change the routes to this:
async def __call__(self, request):
my_header_value = request.headers['my_header_value'] # new header value
response1 = call_service_1('aaa', my_header_value)
response2 = call_service_2('bbb', my_header_value)
response3 = call_service_3('ccc', my_header_value)
And to change the service request to this:
async def call_service1(self, arg, my_header_value): # new parameter
url = 'http://localhost/' + arg
headers = {
'Content-Type': 'application/json',
'my_header_value': my_header_value # new header value
}
async with self.client_session.get(url, headers=headers) as response:
return response
I don't think this is the Pythonic way to make a change like this. I think it's a bad design to pass this parameter around like this, from endpoint to endpoint. I know that this is a cross-cutting concern, but I don't know the proper way to design something to handle this in Python. I'd ultimately be copying and pasting code all over the place. There's got to be a better way, but I don't know it and my Python isn't that strong.
For instance, is there some way I can decorate the service calls so that I don't have to add a new parameter all over the place? I don't think I have access to some session variables that I can set so that I don't have to add parameters at all. If I did however, I'd be worried about unit testing.
What do you recommend?

Resources