Serverless API with AWS SAM & FastAPI

Vinay Kachare
6 min readAug 12, 2021

In my last article we discussed some of the core features of FastAPI and how we can leverage them in order to faster the API development. In this article we will discuss how to deploy the API on aws using AWS SAM

What is SAM ?

The AWS Serverless Application Model (SAM) is an open-source framework for building serverless applications. It provides shorthand syntax to define the application you want and model it using YAML.

Now you don’t have to create the resources manually required for the api using the aws console, SAM will take care of it with just few lines of code.

How it is different from cloud formation ?

SAM is just an abstraction over cloud formation, in fact during the deployment, SAM transforms and expands the SAM syntax into AWS CloudFormation syntax, enabling you to build serverless applications faster.

Why SAM ?

In addition to above, It also provides a Lambda-like execution environment locally to debug your code before deployment.It uses TOML file to specify the configuration for each environment (QA, Dev) depending on your requirement, so that we can use the same template across different environments.

Prerequisite

In order to get started with the SAM we need following things.

  1. AWS Account
  2. IAM User (with programmatic access)
  3. AWS CLI
  4. Docker
  5. Python

So Let’s build our first serverless API

Once your AWS account is active you can create IAM user by following below steps.

IAM User Creation

Go to Search type IAM and click on the first option which will navigate you to IAM console then on left side click Users > Add user > Enter Username (check Programmatic access & click Next) > Attach existing policies directly (check AdministratorAccess & click Next) > Next > Create User

Once the user is successfully created you will get table with User, Access key ID & Secret access key you can note down this details or download it using Download .csv option which will be used in next step to configure aws cli.

AWS CLI

Download aws cli using this link and install it in your machine. Now we have to configure it by using following command and enter the details we got in above steps.

you have to provide the value (we got during the IAM user creation) & press enter for the next field. You can specify your own region as in my case it was ap-south-1. Once it is configured, all the information entered in above step will be stored in credentials file (under the default profile) located in .aws folder, this path may vary depending on your operating system. you can also change this details

Now we have to test whether aws cli is properly configured or not using below command which will list all the buckets from the configured account (In my case there was no bucket hence the output is empty) .

Install Docker Desktop

Use this link to install docker desktop for your respective operating system.

Python & API Setup

Now we are almost done with the configuration, in the last step we need to install the python version same as our runtime for the lambda function.

I highly recommend using anaconda over normal python installation as we can create virtual environment by using different python version depending on runtime we use in our lambda function (e.g 3.7, 3.8 etc) instead of installing different python versions locally.

Create conda environment using below command.

— name:- env name, python:- python runtime version

Once the environment is create activate it using below command

Now on the left side you can see the env is now activated, now we have to install all the dependencies required for the api using requirements.txt.

clone this repo to get the entire code base for this application and use below commands to install the dependencies into the newly created env.

pip install -r requirements-dev.txt

Once all the dependencies are installed, you can run the FastAPI using below command

If you go to http://127.0.0.1:8000/hello you will get below message.

Once you got the above response which means api is working as expected locally. Now we can proceed with the deployment.

Deployment ! ! !

In final step we will deploy our api to the aws as a cloud formation stack with just couple of commands, where SAM will play major role. It will create the resources specified in template.yml.

The first command will build the source of your application. The second command will package and deploy your application to AWS

  1. sam build

The above command will build the source code artifacts under .aws-sam/build folder using docker, hence ensure your docker desktop is running before executing the above command.

2. sam deploy — config-env as qa

The above command will start the deployment process, initially it will upload the code artifcats to the bucket specified in the samconfig.toml file (please note that you must create the bucket specified in the toml file before deployment), here we are passing the config-env as qa this will pick up the deployment configuration from the samconfig.toml file for the QA environment. If you haven’t specified the config-env parameter then it will take the default configuration specified in the file for that respective command (for sam build command it took the default configuration). we can set the configuration for each sam command in the toml file for different environments or we can also pass those parameters and their value inline (like we did it for config-env) without specifying any configuration in toml file, here is the list of supported sam commands and their respective parameters.

Once you preview the changeset type y to confirm and press enter, then sam will create cloud formation stack with the resource specified in the template.yml file for you.

Once the deployment process is completed it will generate the output specified in the template.yml on console, in our case we have printed the api gateway url for our ref.

If you go to below url you will get below message.

https://f0ykh5tzol.execute-api.ap-south-1.amazonaws.com/qa/hello

We have successfully deployed our api using SAM & FastAPI. It’s difficult to cover entire functionality in one article so I highly recommend you to go through the following resources to get detailed understanding of SAM.

Reference

[1]: AWS SAM

[2]: Serverless Land

[3]: FastAPI Documentation

--

--