sam init --runtime python3.11 --name fastapi-lambda
Choose the Quick Start: Hello World Example template.
Delete the default app.py and create your FastAPI app
app.py:
from fastapi import FastAPI
from mangum import Mangum
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello from FastAPI on Lambda!"}
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "q": q}
# Mangum handler for Lambda
handler = Mangum(app)
pip install fastapi mangum
pip freeze > requirements.txt
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: FastAPI on AWS Lambda with SAM
Resources:
FastAPIFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: .
Handler: app.handler # Points to the Mangum handler
Runtime: python3.11
Timeout: 30 # Increase timeout if needed
MemorySize: 512
Events:
ApiEvent:
Type: Api
Properties:
Path: /{proxy+}
Method: ANY
RestApiId: !Ref FastAPIApi
FastAPIApi:
Type: AWS::Serverless::Api
Properties:
StageName: prod
Cors: # Optional: Enable CORS
AllowMethods: "'*'"
AllowHeaders: "'*'"
AllowOrigin: "'*'"
Outputs:
ApiUrl:
Description: API Gateway endpoint URL
Value: !Sub "https://${FastAPIApi}.execute-api.${AWS::Region}.amazonaws.com/prod/"
sam build
sam local start-api
Visit http://localhost:3000/ or http://localhost:3000/items/42?q=test to test.
sam deploy --guided
Follow prompts to name your stack and select AWS region.
sam build && sam deploy --no-confirm-changeset
Test the endpoints:
curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/
curl https://<api-id>.execute-api.<region>.amazonaws.com/prod/items/5?q=test
Key Notes
Cold Starts: Lambda may have cold starts. Use Provisioned Concurrency for critical APIs.
Dependencies: Ensure all dependencies (like fastapi, mangum) are in requirements.txt.
Layers: For large dependencies, use Lambda Layers.
Logs: Check CloudWatch Logs for debugging:
sam logs -n FastAPIFunction --stack-name <stack-name> --tail
fastapi-lambda/
├── app.py
├── requirements.txt
├── template.yaml
└── tests/
This setup allows you to deploy a scalable, serverless FastAPI app on AWS Lambda with minimal overhead