vumdao / simple-serverless-fastapi

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

FastApi With AWS Serverless

FastApi With AWS Serverless

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 simple API server with lambda integration

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

  • Lambda function contains FastApi code to serves API requests and respose.

  • Let's see the stack relationships

πŸš€ Build FastAPI as 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
    
  • 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

    src/lambda-handler/api
    └── api_v1
        β”œβ”€β”€ api.py
        └── endpoints
            └── users.py
    
    from api.api_v1.api import router as api_router
    app.include_router(api_router, prefix="/api/v1")
    
  • For 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, must set 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',
      

πŸš€ Deploy

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

  • For 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' https://chatgpt.simflexcloud.com/chat_gpt/ -d 'question=how%20are%20you' -G
    {"message":"We got question: how are you"}
    

πŸš€ Conclusion

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

References:


About

License:Apache License 2.0


Languages

Language:TypeScript 94.7%Language:Python 5.3%