DEV Community

Cover image for FastApi With AWS Serverless powered by CDK Typescript

FastApi With AWS Serverless powered by CDK Typescript

Abstract

  • Deploy FastAPI in a Lambda function that is fronted by an HTTP API in API Gateway, you can enable 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 serves 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
  src/lambda-handler
  β”œβ”€β”€ api
  β”‚   └── api_v1
  β”‚       β”œβ”€β”€ api.py
  β”‚       └── endpoints
  β”‚           └── users.py
  β”œβ”€β”€ main.py
  └── requirements.txt

  4 directories, 4 files


Enter fullscreen mode Exit fullscreen mode
  • Direct route paths include / and chat_gpt ```

@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`
Enter fullscreen mode Exit fullscreen mode

src/lambda-handler/api
└── api_v1
β”œβ”€β”€ api.py
└── endpoints
└── users.py


Enter fullscreen mode Exit fullscreen mode

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`](https://pypi.org/project/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
    ```


    docs_url='/docs',
    openapi_url='/openapi.json',


Enter fullscreen mode Exit fullscreen mode

πŸš€ 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

  <img src=https://raw.githubusercontent.com/vumdao/simple-serverless-fastapi/master/images/apigw.png width=1100>

  <img src=https://raw.githubusercontent.com/vumdao/simple-serverless-fastapi/master/images/chat_gpt.png width=1100>

- Custom domain mapped to the API

  <img src=https://raw.githubusercontent.com/vumdao/simple-serverless-fastapi/master/images/custom-domain.png width=1100>

## πŸš€ **Test API** <a name="Test-API"></a>
- Open API Docs

  <img src=https://raw.githubusercontent.com/vumdao/simple-serverless-fastapi/master/images/api_docs.png width=1100>

- Call `/chat_gpt` with API key and query `question`

Enter fullscreen mode Exit fullscreen mode

➜ simple-serverless-fastapi curl -X GET -H "Content-Type: application/json" -H 'x-api-key: 6sUnYj8PAw8MKu8O6FqSw1kf1clmC0Fx8ilQhVeO' https://chatgpt.simflexcloud.com/chat_gpt/ -d 'question=how%20are%20you' -G
{"message":"We got question: how are you"}


## πŸš€ **Conclusion** <a name="Conclusion"></a>
- 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.

---

References:
- [Simple Serverless FastAPI with AWS Lambda](https://www.deadbear.io/simple-serverless-fastapi-with-aws-lambda/)

---





Enter fullscreen mode Exit fullscreen mode

Top comments (6)

Collapse
 
uponthesky profile image
UponTheSky

Thanks for the article! I have had fairly hard times deploying my FastAPI app using SAM ... I wonder how you think about using CDK rather than SAM. I might consider redeploying using CDK in the future!

Collapse
 
vumdao profile image
πŸš€ Vu Dao πŸš€

I have no idea about SAM, just love CDK

Collapse
 
jesuscc29 profile image
JesΓΊs Cota

Thank for the article! Looks great, but i have one question. I was trying to do the same architecture, but when i raise a HTTPException from FastAPI, Lambda throws a 500 error. Have you ever encounter a situation like this?

Collapse
 
fonzai profile image
Timo Saloranta

Thanks! I like this approach a lot. Have you found example of how the respective CDK code would look like? It takes some time to build it from the scratch.

Collapse
 
vumdao profile image
πŸš€ Vu Dao πŸš€

I just have my code here github.com/vumdao/simple-serverles...

Collapse
 
fonzai profile image
Timo Saloranta

Thanks a lot! This looks very helpful.

I'll try to modify the CDK part to my needs and give it a shot later. So far I've been deploying lambdas individually through CDK but having one FastApi endpoint would sometimes make things much easier to work with.