How to Deploy FastAPI over AWS Lambda

This guide walks you through deploying a FastAPI application to AWS Lambda.

Prerequisites

Install the required packages:

pip install fastapi uvicorn mangum

Steps

1. Create requirements.txt

Generate the requirements file:

pip freeze > requirements.txt

2. Prepare main.py

Create your main.py file with FastAPI and Mangum handler:

from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()

# Your FastAPI routes here
@app.get("/")
def read_root():
    return {"message": "Hello World"}

handler = Mangum(app)

3. Install dependencies

Install all dependencies into a dependencies directory:

pip install -t dependencies -r requirements.txt

4. Create deployment package

Create a zip file containing all dependencies:

cd dependencies
zip ../aws_lambda_artifact.zip -r .
cd ..

on Windows:


Compress-Archive -Path * -DestinationPath ..\aws_lambda_artifact.zip -Force

Add your main.py to the zip file:

zip aws_lambda_artifact.zip -u main.py

5. Create Lambda function on AWS

  1. Create a new Lambda function on AWS with the correct runtime (Python 3.9, 3.10, or 3.11)
  2. Upload the aws_lambda_artifact.zip file

6. Configure Lambda function

  1. Enable Function URL:

    • Go to Configuration → Function URL
    • Create a function URL with authType set to None
  2. Update Runtime Settings:

    • Go to Configuration → Runtime settings
    • Edit and update the handler to: main.handler

Notes

  • Make sure your Lambda function has sufficient timeout and memory settings
  • The handler name (main.handler) corresponds to the handler variable exported from main.py
  • Function URL with authType: None allows public access (consider security implications)