FastApi With AWS Serverless powered by CDK Typescript

FastApi With AWS Serverless powered by CDK Typescript


3 min read


  • Deploy FastAPI in a Lambda function that is fronted by an HTTP API in API Gateway, you can enable the API key required for the API

Table Of Contents

๐Ÿš€ Solution overview

  • Use AWS APIGW to build a simple API server with lambda integration

  • APIGW route paths such as /api/v1/ and /chat_gpt/ require API key (with usage plan)

  • The lambda function contains FastApi code to serve API requests and responses.

  • Let's see the stack relationships

๐Ÿš€ Build FastAPI as a lambda funnction handler

  • Lambda handler source code

      โžœ  simple-serverless-fastapi tree src/lambda-handler
      โ”œโ”€โ”€ api
      โ”‚   โ””โ”€โ”€ api_v1
      โ”‚       โ”œโ”€โ”€
      โ”‚       โ””โ”€โ”€ endpoints
      โ”‚           โ””โ”€โ”€
      โ””โ”€โ”€ requirements.txt
      4 directories, 4 files
  • Direct route paths include / and chat_gpt

    ```plaintext @app.get("/") async def root(): return {"message": "FastAPI running in a Lambda function"}

@app.get("/chat_gpt/") async def read_chatgpt(question: str = None): return {"message": f"We got question: {question}"}

* Restructure FastAPI Routing for developing API and optimize source code by using `APIRouter`

    โ””โ”€โ”€ api_v1
        โ””โ”€โ”€ endpoints
    from api.api_v1.api import router as api_router
    app.include_router(api_router, prefix="/api/v1")
  • For the lambda function handler, we use Mangum python module which is an adapter for running ASGI applications in AWS Lambda to handle Function URL, API Gateway, ALB, and Lambda@Edge events.

  • For building API Docs, one must set the following parameters in FastApi() constructor to resolve /openapi.json correctly

    • For API URL using APIGW stage URL, set root_path equal to the API stage name, eg. root_path=/AppAPI

    • For API custom domain


๐Ÿš€ Deploy

  • For production, building CDK pipeline for this is the best practice.

  • For the demo, I run cdk deploy manually

      โžœ  simple-serverless-fastapi cdk deploy
       โœ…  SimpleFastApiServerless
      โœจ  Deployment time: 72.44s
  • The API GW and method request

  • Custom domain mapped to the API

๐Ÿš€ Test API

  • Open API Docs

  • Call /chat_gpt with API key and query question

      โžœ  simple-serverless-fastapi curl -X GET -H "Content-Type: application/json" -H 'x-api-key: 6sUnYj8PAw8MKu8O6FqSw1kf1clmC0Fx8ilQhVeO' -d 'question=how%20are%20you' -G
      {"message":"We got question: how are you"}

๐Ÿš€ Conclusion

  • We created a FastAPI application using AWS Serverless. The user must provide the API key to query request and the API key is associated with the usage plan where we can specify who can access the deployed API stages and methods, and optionally sets the target request rate to start throttling requests.