Skip to main content

Command Palette

Search for a command to run...

FastAPI as AWS Lambda Function

Deploy a FastAPI application to AWS Lambda

Updated
3 min read
FastAPI as AWS Lambda Function

As a fan of both FastAPI and AWS Lambda, I wanted to share a quick tutorial on how to combine these two awesome technologies. If you're not familiar with AWS Lambda, it's a serverless compute service that lets you run code without managing servers. And FastAPI? It's one of my favorite Python frameworks for building APIs!

In this article, I'll show you how to deploy a FastAPI application to AWS Lambda using Mangum. Let's dive in!

Prerequisites

Project Setup

First, let's create the directory for our project:

# Create project directory
mkdir fastapi-lambda-function 
cd fastapi-lambda-function

Create and activate virtual environment

python -m venv venv 
source venv/bin/activate  # On Windows: venv\Scripts\activate

Create two files in your project:

  • requirements.txt

  • main.py

In requirements.txt, add these dependencies:

fastapi==0.99.0  # Using this version due to current compatibility
mangum

Install the packages:

pip install -r requirements.txt

Creating Our FastAPI Application

In main.py, let's create a basic FastAPI app:

from fastapi import FastAPI
from mangum import Mangum

app = FastAPI()

@app.get("/")
async def read_root():
    return {"message": "Hello, this is my first FastAPI app running on AWS Lambda!"}

# Add another route for demonstration
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q}

# This is the key for Lambda!
handler = Mangum(app)

This basic FastAPI has two endpoints, a root and pretty basic /items endpoint. But as you can see the last line with handler being Mangum, that is how AWS will trigger this Lambda function.

Packaging for AWS Lambda

Now comes the fun part - packaging our application for Lambda! We need to create a ZIP file containing all our dependencies and code.

On Windows you can use PowerShell:

# Zip dependencies
Compress-Archive -Path "venv/Lib/site-packages/*" -DestinationPath "aws-lambda.zip"

# Add main.py to the zip
Compress-Archive -Path "main.py" -Update -DestinationPath "aws-lambda.zip"

On Unix/Linux:

cd venv/lib/python3.10/site-packages
zip -r ../../../../aws-lambda.zip .
cd ../../../../
zip -g aws-lambda.zip main.py

Deploying to AWS Lambda

  1. Go to AWS Console and search for Lambda

  2. Click "Create function"

  3. Choose "Author from scratch"

  4. Configure the basics:

    • Name: fastapi-lambda

    • Runtime: Python 3.10

    • Architecture: x86_64

    • Default execution role: Create new basic Lambda role

  5. Enable Function URL:

    • Click "Configuration" tab

    • Find "Function URL" and enable it

    • Auth type: NONE (for this demo)

    • Click "Save"

  6. Upload your code:

    • Go to "Code" tab

    • Click "Upload from" and choose ".zip file"

    • Upload your aws-lambda.zip

    • Click "Save"

  7. Configure the handler:

    • Go to "Runtime settings"

    • Click "Edit"

    • Change Handler to: main.handler

    • Click "Save"

Testing Your API

Once deployed, you'll get a Function URL. Try these endpoints:

  • <your-function-url>/ - Should return your welcome message

  • <your-function-url>/items/1 - Should return {"item_id": 1, "q": null}

  • <your-function-url>/items/100 - Should return {"item_id": 100, "q": null}

What's Next?

This is just a basic example of what you can do with FastAPI and AWS Lambda. In production, you might want to consider:

  • Setting up proper authentication

  • Using API Gateway for more control

  • Implementing proper error handling

  • Setting up CI/CD pipelines

If you found this helpful, don't forget to follow me for more cloud and DevOps content! Check out my YouTube channel where I have a detailed video walkthrough of this tutorial.

Common Issues

  • If you're getting errors with the latest FastAPI version, stick to version 0.99.0 as specified in the requirements.

  • Make sure your handler name matches exactly main.handler.

  • Check your Lambda execution role has proper permissions.

Happy coding!

P.S. All code from this tutorial is available in my GitHub repo.