FastAPI – Calling endpoints from AWS Lambda handler with explicit arguments

  amazon-web-services, fastapi, lambda, python

I currently have my lambda handler set up using FastAPI middleware decorator and Mangum like the following:

from routers import router

app = FastAPI()

app.include_router(router)

# Handler for api calls
@app.middleware("http")
async def api_process(request: Request, call_next):
    try:
        if path in endpoints_list:
            # ... validation logics here ...

            response = await call_next(request) # calls the endpoints with corresponding path

            # ... process the response ...
  
   except Exception as ex:
        # ... process exception ...


handler = Mangum(app)

And I have several endpoints which gets called from the above lambda function, do their job and return the response accordingly like this:

@router.get("/index")
def sample_endpoint(request: Request):
   try:
       query_params= request.query_params
       body = request.body
       # ....
       return Response(
           status_code = 200,
           content=json.dumps(response_body)
       )
   except Exception as ex:
        # ... process exception ...

Instead of accepting generic Request object and extract query_params and body data myself, I would like to use more explicit parameters such as item_id: int, customer_name: str, and so on for each endpoints. Since I am using middleware decorator for the lambda function to forward the request to path provided, I am not sure how to do it other than passing in the whole Request object from lambda function. Any help would be greatly appreciated!

Source: Python Questions

LEAVE A COMMENT