This is the second part of a two-part series on creating Serverless FAST API.
If you haven't checked the first part, do take a look here
From our previous setup, we created a fast API application that does CRUD operation on Todos.
Now let us modify this a bit to support AWS serverless.
For this application, we will use AWS SAM.
I have already talked about serverless here for you to explore.
Updating the setup
We need to add a SAM template in order to let us deploy fast API to AWS Lambda. However, we also need an adapter that can translate AWS serverless events to be transferred to our Fast API server.
Enters Magnum!
We will use Magnum, an adapter for running ASGI applications in AWS Lambda to handle Function URL, API Gateway, ALB, and Lambda@Edge events.
This is how we configure the adapter
from mangum import Mangum
from app.main import app
handler = Mangum(app=app)
Now let's add the SAM Template
We will create a ProxyApi of type Serverless API.
The Runtime selected is python 3.8 and architecture is arm64
The proxy setup allows a pass-through of all API Calls to our fast API server using Magnum.
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: >
fast-api
Globals:
Function:
Timeout: 30
MemorySize: 128
Resources:
ProxyApi:
Type: AWS::Serverless::Api
Properties:
StageName: Prod
BinaryMediaTypes: [ '*/*' ]
HandlerFunction:
Type: AWS::Serverless::Function
Properties:
Handler: handler.handler
Runtime: python3.8
Architectures:
- arm64
Events:
FunctionProxy:
Type: Api
Properties:
RestApiId: !Ref ProxyApi
Path: "/{proxy+}"
Method: ANY
Outputs:
HandlerFunctionApi:
Description: "API Gateway endpoint URL for Prod stage"
Value: !Sub "https://${ProxyApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/"
HandlerFunction:
Description: "Lambda Function ARN"
Value: !GetAtt HandlerFunction.Arn
HandlerFunctionIamRole:
Description: "Implicit IAM Role created"
Value: !GetAtt HandlerFunction.Arn
Deployment
Now all you need to do is run the below commands
sam build
sam deploy --guided
Once the deployment completes we can check in cloud formation, it should have an entry like the one below -

Now let us try the endpoints using Postman or any other rest client
Creating Todo

Fetching Todos

Deleting Todo

That's it! This completes our serverless Fast API! Hope you like it 🍻