Published on

Using FastAPI with AWS SAM the Easy Way!

Authors
    avatar

    John Partee

Using FastAPI with AWS SAM

FastAPI is a modern, fast (high-performance, badass), web framework for building APIs with Python 3.6+ based on standard Python type hints. It's built on top of Starlette for the web parts and Pydantic for the data parts.

AWS SAM (Serverless Application Model) is an open-source framework for building serverless applications. It provides shorthand syntax to express functions, APIs, and events in an AWS CloudFormation template. This allows you to build serverless applications faster and with less boilerplate code.

Mangum is the glue that holds those together - And it doesn't even take much work.

TL;DR - Try this template out

Github Repo

It should be enough to get you going. FastAPI, Mangum, and SAM can get you moving really fast. Just write it up like a regular fastapi app and try it.

Defining Your FastAPI App in AWS SAM

To use FastAPI with AWS SAM, you need to define your FastAPI app as an AWS Lambda function. This can be done by creating a new AWS Lambda function in your AWS SAM template and setting its Handler property to the name of the FastAPI app object. You can then use the AWS::Serverless::Function resource to define the function in your AWS SAM template.

Here's an example of how you might do this in your AWS SAM template:

yaml

Resources:
  MyFastAPI:
    Type: AWS::Serverless::Function
    Properties:
      CodeUri: path/to/my/code
      Handler: app.app
      Runtime: python3.8

Creating a Proxy Route in AWS SAM

Once you've defined your FastAPI app as an AWS Lambda function, you can use the Events property to define an AWS API Gateway endpoint for the function. This will allow you to access your FastAPI app via HTTP requests.

To create a proxy route in AWS SAM, you can use the AWS::Serverless::Function resource's Events property. This will create an AWS API Gateway endpoint that forwards requests to our FastAPI app routes!

yaml

Events:
  HelloWorld:
    Type: Api # More info about API Event Source: https://github.com/awslabs/serverless-application-model/blob/master/versions/2016-10-31.md#api
    Properties:
      Path: /{proxy+}
      Method: ANY

Using FastAPI's Automatic Validation and Serialization

FastAPI also provides automatic validation and serialization of request and response data based on your API's type hints. This means that you can define the expected input and output for each endpoint using Python's built-in type hinting, and FastAPI will automatically validate and serialize the request and response data for you.

Here's an example of how you might define an endpoint in FastAPI to accept a JSON request body and return a JSON response:

python

from fastapi import FastAPI, Request, Response
from pydantic import BaseModel

app = FastAPI()

class Item(BaseModel):
  name: str
  description: str

@app.post("/items/")
async def create_item(item: Item):
  # FastAPI will automatically validate the request body
  # against the Item model, and will return a 400 Bad Request
  # response if the request body is invalid.

  # You can then use the Item object to access the request data.
  return {"name": item.name, "description": item.description}

Using FastAPI's automatic validation and serialization can help you write cleaner and more concise code for your API, and can reduce the amount of boilerplate code you need to write.

Deploying Your FastAPI App to AWS

Once you've defined your FastAPI app and its associated AWS API Gateway proxy route in your AWS SAM template, you can use the sam build and sam deploy commands to build and deploy your application to AWS.

Here's an example of how you might use the sam build and sam deploy commands to deploy your FastAPI app to AWS:

bash

sam build
sam deploy --guided

The sam build command will build your application's artifacts, such as the AWS Lambda function code, and the sam deploy command will deploy your application to AWS. The --guided flag will cause the sam deploy command to prompt you for input, such as the AWS region and stack name to deploy to.

Once your application is deployed to AWS, you can start using your API. You can use the /docs and /redoc endpoints provided by FastAPI to view the API documentation and try out your API's different endpoints.

Conclusion

Using FastAPI with AWS SAM allows you to quickly and easily develop and deploy serverless APIs. FastAPI's modern design and automatic validation and serialization make it a great choice for building APIs, and AWS SAM's concise syntax makes it easy to define and deploy serverless applications. And by using a proxy route in your AWS SAM template, you can easily create an AWS API Gateway endpoint that forwards requests to your FastAPI app.

Want an email when we post?

Free, weekly at most. We hate spam too.