FastAPI Deployment to AWS Lambda with Serverless Framework
Deploy FastAPI to AWS Lambda using Serverless Framework
Hello, I will share how to deploy your FastAPI Project to the AWS Lambda Function. Let's do it…
Table of Contents
- Create FastAPI Project or you can use the existing one
- Create AWS Execution Role for Lambda
- Serverless Framework Configurations
- Deploy the project
Create FastAPI Project
If you are using the existing FastAPI Project, just skip this.
Ops, dont forget to install mangum as the requirements
Start with creating the project directory anywhere do you want on your machine, then create the python virtual environment in it.
mkdir FastAPI-Lambda-Function
cd FastAPI-Lambda-Function
python3 -m venv venv
source venv/bin/activate
Then install the requirements that are FastAPI, and Mangum
- FastAPI (fastapi.tiangolo.com)
- Mangum (mangum.io)
pip install fastapi mangum uvicorn
- Uvicorn (uvicorn.org) we need this to test the project locally
then, create a file named main.py
# main.pyimport os
from fastapi import FastAPI
from mangum import Mangum
STAGE = os.environ.get('STAGE')
root_path = '/' if not STAGE else f'/{STAGE}'app = FastAPI(title="FastAPI x AWS Lambda", root_path=root_path)@app.get('/hello')
def hello_api(name: str = "World"):
return {"hello": name}# Mangum Handler, this is so important
handler = Mangum(app)
Let’s run the project,
uvicorn main:app --reload
Create AWS Execution Role for Lambda
Creating an execution role in the IAM console
By default, Lambda creates an execution role with minimal permissions when you create a function in the Lambda console. You can also create an execution role in the IAM console.
To create an execution role in the IAM console
- Open the Roles page in the IAM console.
- Choose Create role.
- Under Common use cases, choose Lambda.
- Choose Next: Permissions.
- Under Attach permissions policies, choose the AWS managed policies AWSLambdaBasicExecutionRole and AWSXRayDaemonWriteAccess.
- Choose Next: Tags.
- Choose Next: Review.
- For Role name, enter
lambda-execution-role
. - Choose Create role.
Open the role that you just created, then copy the Role ARN (will be used on the next step)
Serverless Framework Configurations
create Python Requirements file
pip freeze > requirements.txt
Install serverless framework if it's not installed before
npm i -g serverless
Install serverless-python-requirements plugin for serverless
sls plugin install -n serverless-python-requirements
then, create the serverless.yaml file
# serverless.yaml
service: FastAPI-Lambda-Function
package:
individually: true
provider:
name: aws
profile: ${opt:aws-profile, "default"}
region: ${opt:region}
stage: ${opt:stage, "dev"}
runtime: python3.8
memorySize: 128
timeout: 30
iam:
role: ${opt:iamrole}plugins:
- serverless-python-requirements
custom:
pythonRequirements:
dockerizePip: true
layer:
name: FastAPI-Lambda-Function
description: FastAPI-Lambda-Function API Layer
compatibleRuntimes:
- python3.8functions:
app:
package:
patterns:
- 'src/**'
- '!requirements.txt'
- '!package.json'
- '!package-lock.json'
- '!.serverless/**'
- '!venv/**'
- '!node_modules/**'
handler: main.handler
environment:
STAGE: ${self:provider.stage}
layers:
- { Ref: PythonRequirementsLambdaLayer }
events:
- http:
method: get
path: /
- http:
method: any
path: /{proxy+}
Deploy the project
Make sure you already configure the AWS CLI Before, because the deployment process will be using it.
serverless deploy --region 'ap-southeast-1' --stage 'dev' --aws-profile 'default' --iamrole 'paste-your-lambda-arn-role-here'
Change the opt value with your own
- region: the AWS region that you wanna used
- aws-profile: the AWS CLI Profile (default will be used if it's not provided)
- stage: the default is dev, but you could change it with do you want (ex: staging)
- iamrole: using the ARN Role that you are copied on the previous step
If the deployment process success, the output on the console will be like the following picture
Then open the docs URL on the browser
Done 🎉🎉🎉
Project Repo: https://github.com/dwisulfahnur/fastapi-mangum-lambda