Deploying FastAPI Apps with AWS Lambda and API Gateway

Overview
FastAPI has emerged as a popular framework for building high-performance APIs in Python. Its focus on simplicity, speed, and automatic data validation makes it ideal for modern web applications. Leveraging serverless architectures with AWS Lambda and API Gateway can further enhance your FastAPI app by offering scalability, cost-efficiency, and a pay-per-use model.
This article will explain the seamless deployment process of a FastAPI application using AWS Lambda and API Gateway, empowering you to create robust and efficient APIs.
Understanding the Key Players
Each terminology is explained below:
· FastAPI: A high-performance web framework built upon Python’s ASGI (Asynchronous Server Gateway Interface) for building modern APIs with ease.
· AWS Lambda: A serverless computing service allowing you to run code without managing servers. Perfect for event-driven applications with pay-per-execution billing.
· AWS API Gateway: A fully managed service for creating, publishing, and maintaining APIs for your applications. It acts as the front door for your API, handling requests and routing them to the appropriate backend (in this case, your Lambda function).
Getting Started: Prerequisites
· AWS Account: Sign up for a free tier AWS account if you don’t have one already (https://aws.amazon.com/free/).
· Python Environment: Ensure you have Python 3.6 or later installed along with pip for package management.
· AWS CLI (Command Line Interface): Install and configure the AWS CLI to interact with AWS services from your terminal (https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html).
1. Building Your FastAPI App
· Create a Project Directory: Use your terminal to create a new directory for your project and navigate to it.
· Initialize Virtual Environment (Optional): It’s recommended to create a virtual environment to isolate project dependencies. Use python -m venv venv and activate it using source venv/bin/activate (Linux/macOS) or venv\Scripts\activate.bat (Windows).
· Install Dependencies: Install FastAPI using the following command:
pip install fastapi
You might also need additional dependencies specific to your API functionality.
Now, let’s create a simple FastAPI application to illustrate the deployment process. Create a file named app.py with the following code:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello from your FastAPI App!"}
This code defines a basic endpoint (/
) that returns a JSON response when accessed.
2. Packaging for Lambda: Optimizing for Serverless
Since Lambda functions have limitations on execution time and memory size, it’s crucial to optimize your FastAPI app for serverless deployment. Here’s how:
· Dependency Management: Utilize a tool like uvicorn or mangum to handle ASGI server creation and dependency management within the Lambda environment. Install mangum by using the following command:
pip install mangum
· Create a Handler Function: In app.py, create a function using mangum to wrap your FastAPI application. This function will be the entry point for your Lambda.
from fastapi import FastAPI
from mangum import Mangum
app = FastAPI()
handler = Mangum(app)
@app.get("/")
async def root():
return {"message": "Hello from your FastAPI App!"}
· Create a Requirements File: Use the following command to generate a file listing all your application’s dependencies. This file ensures Lambda has the necessary libraries to run your app.
pip freeze > requirements.txt
3. Deploying to AWS Lambda
In the AWS Management Console, navigate to the Lambda service and click “Create function”. Choose “Author from scratch” and provide a name for your function (e.g., “fastapi-app”). Select “Python 3.9” as the runtime and click “Create function”. To configure it:
· In the “Code source” section, choose “Upload from”.
· Zip your project directory by the following command (including app.py, requirements.txt, and any other relevant files) and upload it as a ZIP archive.
zip -r app.zip app.py requirements.txt
· Under “Handler”, enter the handler function name (e.g., “app.handler”). This tells Lambda the function to execute when invoked.
· Consider setting appropriate memory and timeout values for your Lambda function based on your application’s needs.
4. Create an IAM Role (Optional):
While not mandatory for our simple example, creating an IAM role for your Lambda function enhances security by granting it specific permissions to interact with other AWS services (like API Gateway) as needed. Here’s a basic outline:
· In the IAM service, navigate to “Roles” and click “Create role”.
· Choose “Lambda” under “Use case” and select “Lambda basic execution role”.
· Review the pre-configured policy for Lambda access and customize further permissions if required. Click “Next: Tags” and optionally add tags for organization.
· Click “Next: Review” and provide a name for your role (e.g., “fastapi-app-role”). Finally, click “Create role”.
· Back in your Lambda function configuration, under “Role”, choose “Use an existing role” and select the newly created IAM role.
· Then, click “Save” to create the Lambda function. You can then test its functionality by clicking “Test” and providing sample event data (if applicable).
5. Building and Deploy the API Gateway for Your FastAPI App
· Create a New API: In the AWS Management Console, navigate to API Gateway and click “Create API”. Choose “REST API” and click “Build”.
· Configure API: Enter a name for your API (e.g., “fastapi-api”). Under “Create a new resource”, leave the field blank (represents the root path). Click the green checkmark.
· Create a Method: Click on “Actions” next to your root resource and select “Create Method”. Choose “GET” as the HTTP method and click the green checkmark.
· Integrate with Lambda: Click on the newly created “GET” method and select “Integration type” as “AWS Lambda”. Choose your Lambda function (e.g., “fastapi-app”) from the dropdown and click “Save”.
· Enable CORS (Optional): If your API expects requests from different origins (front-end hosted elsewhere), configure CORS (Cross-Origin Resource Sharing) to allow access. Under “Method Request”, click on “Integration request” and then “Body”. Choose “Pass-through” for all options and click “Save”.
· Deploy Your API: Click on “Actions” next to your API and select “Deploy API”. Choose a new stage for deployment (e.g., “dev”) and click “Deploy”.
6. Accessing Your FastAPI App
Once deployment is complete, navigate to the “Invoke” tab in your Lambda function and click “Test”. You should see the response from your FastAPI app ({"message": "Hello from your FastAPI App!"}
) displayed in the invocation results.
Alternatively, retrieve the API Gateway endpoint URL from the deployment stage details. Use tools like Postman or curl to send a GET request to this URL. You’ll receive the same JSON response, confirming the successful deployment of your FastAPI app.
Conclusion
In this article, we’ve explored how to deploy a FastAPI application using AWS Lambda and API Gateway. Serverless architectures offer numerous benefits, including scalability, cost-effectiveness, and reduced operational overhead.
By leveraging AWS Lambda and API Gateway, you can deploy and scale your FastAPI applications with ease, allowing you to focus on building great APIs without worrying about infrastructure management. With the provided commands and configuration files, cloud engineers can efficiently deploy and manage their FastAPI applications on AWS Lambda and API Gateway.