Deploying FastAPI Apps on AWS Lambda with Serverless Framework

Deploying FastAPI applications on AWS Lambda has become a popular choice for developers seeking scalable and serverless solutions. Combining FastAPI with the Serverless Framework simplifies deployment, management, and scaling of APIs in the cloud.

Understanding FastAPI and AWS Lambda

FastAPI is a modern, fast (high-performance) web framework for building APIs with Python 3.7+ based on standard Python type hints. AWS Lambda is a serverless compute service that runs your code in response to events and automatically manages the underlying resources.

Prerequisites for Deployment

  • Python 3.7 or higher installed locally
  • AWS account with appropriate permissions
  • Node.js and npm installed for Serverless Framework
  • Serverless Framework installed globally (`npm install -g serverless`)
  • Basic knowledge of FastAPI and AWS Lambda

Creating a FastAPI Application

Start by creating a simple FastAPI app. Save this as main.py.

Example:

from fastapi import FastAPI

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello from FastAPI on Lambda!"}

Packaging the Application for Lambda

Use a tool like Zappa or Serverless Framework to package and deploy. Here, we’ll focus on Serverless Framework with a Python plugin.

Install the Serverless Python Requirements plugin:

npm install -g serverless
npm install --save-dev serverless-python-requirements

Configure your serverless.yml file to specify the service, provider, functions, and packaging options.

service: fastapi-lambda

provider:
  name: aws
  runtime: python3.8
  region: us-east-1

plugins:
  - serverless-python-requirements

functions:
  app:
    handler: main.app
    events:
      - http:
          path: /
          method: get

custom:
  pythonRequirements:
    dockerizePip: true
    layer: true

Adapting FastAPI for Lambda

FastAPI needs an ASGI server like Mangum to run on AWS Lambda. Install Mangum:

pip install mangum

Modify main.py to include Mangum:

from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()
handler = Mangum(app)

@app.get("/")
async def read_root():
    return {"message": "Hello from FastAPI on Lambda!"}

Deploying the Application

Run the following commands to deploy:

serverless deploy

After deployment, note the API Gateway URL provided in the output. You can now access your FastAPI app via this URL.

Testing and Managing the Deployment

Test your API by visiting the endpoint URL in your browser or using tools like curl or Postman. The Serverless Framework also allows you to update, remove, or rollback deployments seamlessly.

Conclusion

Deploying FastAPI applications on AWS Lambda with Serverless Framework provides a scalable and cost-effective way to run modern APIs. By integrating Mangum, you bridge the gap between ASGI frameworks and serverless environments, enabling fast and reliable API services in the cloud.