Subscribe

TechnologyArticle

Deploying FastAPI on AWS Lambda with Mangum

No servers to patch, nothing to pay for while idle. Package a FastAPI project as a Lambda function — code in one archive, dependencies in a reusable layer.

Published By Aviox Blogs Engineering · 3 min read

AWS Lambda runs code on demand and bills only while it executes. FastAPI is an ASGI application, and Lambda speaks in events — so we need an adapter between the two. That adapter is Mangum.

This guide deploys a project using two separate archives: the application code, and its dependencies packaged as a Lambda layer. Keeping them apart means code-only changes upload in seconds, and the layer can be shared between functions.

Before you start

You’ll need a FastAPI project and an AWS account with access to Lambda and S3. The examples use a project called sample-fastapi-project, an S3 bucket called sample-fastapi-s3, and a function called sample-fastapi-lambda.

Prepare the project

Isolate the project’s dependencies in a virtual environment and install them:

python3 -m venv venv
source venv/bin/activate        # Windows: .\venv\Scripts\activate
pip install -r requirements.txt

Add Mangum and record it in your requirements:

pip install mangum
pip freeze > requirements.txt

Then wrap the application. The handler object is what Lambda will invoke:

from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()


@app.get("/health")
def health():
    return {"status": "ok"}


handler = Mangum(app)
main.py

Keep reading — it’s free

The remaining 2 min of this story is for Dispatch subscribers. Subscribing takes one field, and the whole story opens right here.

Originally published at Aviox Blogs engineering handbook.

Written by Aviox Blogs Engineering

Field notes, deployment guides and research from the engineers who build web, cloud and mobile products at Aviox Blogs.