Create and Deploy FastAPI app to Heroku

In this tutorial we will implement a simple REST API implemented using Python based FastAPI framework. We will deploy FastAPI app to Heroku account for free.

Create and Deploy FastAPI app to Heroku - TutLinks
Create and Deploy FastAPI app to Heroku – TutLinks

Table of Contents

Introduction to FastAPI

FastAPI is a Python based High Performance Web API Framework with automatic OpenAPI (Swagger) and ReDoc doc generation capabilities for all its endpoints. Highly suitable for quick development of REST APIs or MicroServices.

FastAPI is full compatibility with Starlette (Starlette is a lightweight ASGI framework/toolkit, which is ideal for building high performance asyncio services) and Pydantic (a runtime data validation and settings management using Python type annotations). By leveraging the power of Starlette, FastAPI get full support for WebSockets and GraphQL.

Prerequisites

Before we proceed, if you are interested in following along with this tutorial it is suggested that you meet the below prerequisites.

  • A free GitHub account
  • A free Heroku account
  • Visual Studio Code IDE (Or any Programming IDE you prefer that supports Python programming)
  • A PC with Python 3.6 or latest version installed

This tutorial assumes you are using Visual Studio Code (VS Code) and hence the steps will mention about VS Code during the walk through of this tutorial.

In addition, this FastAPI tutorial also aims at absolute beginners in programming. Hence I try to describe the steps as detailed as possible which help enable non-programmers as well to practice this tutorial.

Create a Simple FastAPI Application

We will create an ultra simple FastAPI application with one endpoint and then we deploy FastAPI app to Heroku platform.

The full source code of this article is hosted on GitHub here. Our endpoint will simply return a response in the JSON (JavaScript Object Notation) format. The response will comprise of a message as key and hello tutlinks.com as value.

Open the command prompt and navigate to the location where you want to create a new application. Create a directory named fastapi-demo and set the current directory to it by running the following commands.

mkdir fastapi-demo
cd fastapi-demo

Now launch the VS Code from the command prompt by typing code . and hit enter.

code .

With the above command, a new instance of VS Code will be launched with the active directory set to the fastapi-demo that we just created. Open the command prompt (cmd or terminal) built in VS Code by pressing the two keys Ctrl and ` at once. If this doesn’t launch, you may try by pressing the keys Ctrl + Shift` at once.

Check the Version of Python installed on the PC

Check the version of Python installed on your PC by running the following command in the terminal.

python -V

Ensure you have Python version 3.6 or later is installed. I have Python 3.8.0 installed on my PC.

Create a Virtual Environment

Before proceeding with the implementation, we will create a Python Virtual Environment to work on our project.

Command to create Python Virtual Environment Windows OS

From Windows OS, create a Virtual Environment named env or any name of your choice by typing the following command

python -m venv env

Command to create Python Virtual Environment Unix based OS

From Unix based OS, create a Virtual Environment named env from command terminal by typing the following command

python3 -m venv env

Activate the Virtual Environment

Type in the following command based on your operating system to activate the virtual environment.

Command to activate Python Virtual Environment for Windows OS

env\Scripts\activate

Command to activate Python Virtual Environment for Unix based OS

source ./env/bin/activate

After successful activation of the virtual environment you will see the name of the environment that got created will be prefixed to the command line terminal in rounded brackets. On Windows OS, this looks like (env) c:\fastapi-demo provided that your project’s directory is located in C: drive.

Upgrade pip

pip is a module installer in Python. Simply put, in our case pip will help us to install FastAPI module so that we can consume it in our application. pip in itself is a module that comes by default with Python installation. There are frequent upgrades to pip. Hence it is a best practice to upgrade the pip so that it will always get the latest dependencies for our project. Run the following command to upgrade pip.

python -m pip install --upgrade pip

Install FastAPI module

Run the following command to install only FastAPI and application specific dependencies to build a Restful API using FastAPI.

Approach 1: FastAPI On-Demand Installation

In this approach we install FastAPI and then Uvicorn separately.

pip install fastapi

In this case, you again have to install uvicorn separately with the following command. Uvicorn is an ASGI (Asynchronous Server Gateway Interface) server that provides the infrastructure to run your FastAPI application.

pip install uvicorn

This means, the application development framework of FastAPI has been completely decoupled with the server it runs. This facilitates the FastAPI to run on WSGI (Web Server Gateway Interface) server as well. This is the beauty of FastAPI.

Approach 2: FastAPI Full Installation

If you want to install the FastAPI along with Uvicorn, run the following command.

pip install fastapi[all]

The challenges with full installation is that if you are on a Windows 10 PC and do not have installed Microsoft Visual C++ 14.0, then the pip will fail to install FastAPI. So in order for you to have successful installation you need to download the Microsoft Visual C++ 14.0 which is very huge software. It is not necessary to have this software installed. Hence it is recommended to go with the Approach 1 of On-demand installation of FastAPI.

Install Gunicorn

We use Gunicorn to serve our application on Heroku. Run the following command to install Gunicorn.

pip install gunicorn

Save all project dependencies to a file

So far, we are able to install all the dependencies. But it is also important to automate installation of required dependencies. This is because, if this repository is being used by other developers on a different PC or if we deploy to various other environments, they should not run into problems with improper versions of modules when they install on their own. So we will freeze the project related dependencies and store them in a file by running the following command in the cmd terminal from the root directory of the project.

pip freeze > requirements.txt

The above command will freeze and captures all the modules’ versions and writes them to a text file named requirements in the root directory of project. The name of the file is your choice but requirements.txt is most widely used by Python community.

In order to install dependencies mentioned in the requirements.txt file, all you have to do is to run the following command.

pip install -r requirements.txt

The above command will recursively reads line by line of the requirements.txt file and installs all the packages with specific versions mentioned in the file.

Create a Simple End Point in FastAPI

We will create a GET endpoint that returns a simple JSON. For that, create a file named main.py in the root directory of our project fastapi-demo.

Import and Initialize FastAPI module

In the main.py add the following line so that we can start building our endpoint with the help of class named FastAPI exposed by the modulefastapi.

from fastapi import FastAPI

In the next new line assign the instance of FastAPI to a variable named app so that we can leverage the get HTTP Verb exposed by the module.

from fastapi import FastAPI
app = FastAPI()

Now, we will create an endpoint to return a simple JSON object as below.

{
    "message": "Hello TutLinks.com"
}

Implement GET Endpoint

Add the following logic in the next new line to implement our basic GET endpoint and save the changes made to main.py file.

# main.py
from fastapi import FastAPI
app = FastAPI()

@app.get("/")
def hello():
    return {"message":"Hello TutLinks.com"}

In the above code we have defined a method named hello with the keyword def. All this method does is just return an object of type dictionary in Python.

The line #1 is where all the magic happens. @app.get("/") is the decorator for our method hello and it will turn this method into an endpoint that accepts requests for GET HTTP method. The instance of FastAPI in our case which is assigned to app will automatically converts the return value of type dictionary in to JSON format.

Run the FastAPI application on local PC

Type the following command in the command prompt where the Python environment we created is activated and hit enter.

uvicorn --port 5000 --host 127.0.0.1 main:app --reload
  • With the above command, we are invoking the call to the Uvicorn ASGI server with the following infrastructure settings.
  • host 127.0.0.1 means we are configuring uvicorn to run our application on the localhost of the PC. The other possible values for host parameter is 0.0.0.0 or localhost0.0.0.0 is recommended when deploying the FastAPI to production environments.
  • port 5000 is the port on which we want our application to run. If you have any other application or service already running on this port, the above command will fail to execute. In such situation, try to change it to any other four digit number of your choice that is found to be freely available for the application to consume.
  • reload It is recommended to set this flag for the development purposes only. Enabling this flag will automatically restart the uvicorn server with any changes you make to your code while in development. It is obvious that, in case there are any run time failures, you will quickly identify those changes from the error trace that caused the failure of uvicorn server to restart.
  • reload flag is not to be confused with hot-code-reloading feature that comes with modern JavaScript libraries. The main difference between uvicorn’s reload and hot code reload provided by React and Vue is that uvicorn’s reload just restarts the server and hot-code-reload restarts both server and reload the user interface.
  • main:app This follows a pattern as detailed below.
    • main is the module where the FastAPI is initialized. In our case, all we have is main.py at the root level. If you are initializing the FastAPI variable somewhere under the other directories, you need to add an __init__.py file and expose that module so that uvicorn can properly identify the configuration. In our case main becomes the module.
    • app is the name of the variable which is assigned with the instance of FastAPI. You are free to change these names but reflect the same syntax that follows module-name:fastapi-initialization-variable pattern.

Access and see the app by navigating to the below endpoint in a browser of your choice.

http://127.0.0.1:5000/

As you are implementing a Web API using FastAPI, it is recommended to send the request to this endpoint via any API development tool such as Postman or Postwoman. Postman is a software for API development and testing. It will allow you to customize the requests being sent to an API. Features such as sending custom HTTP Verbs in the request like GET, PUT, POST, DELETE to name a few and adding custom headers like authorization or content negotiation. But for our simple endpoint we are fine with sending a GET request via browser.

In the browser, you will see the JSON response with message Hello Tutlinks.com. Success, you mastered creating a simple Web API with sample response. It is always recommended to have an understanding of how to deploy this to production environments like Heroku that offer limited dynos with free accounts. This ability will help you show case your work to your friends, colleagues or share your work on professional networking sites such as LinkedIn to boast your technical skills.

Create a Deployment Configuration Procfile for Heroku

Procfile is a Heroku specific file and is read by the deployment configurations during an active deployment that take place on Heroku. Heroku automatically looks for the presence of Procfile and executes the commands located in it.

Command to Deploy FastAPI app to Heroku

Create a file with the name Procfile without any extensions. Place the following command to run your FastAPI app on Heroku in the Procfile.

web: gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
  • web: is specific to Procfile command convention that will help identify the Heroku deployment process to start a web application with the command next to it.
  • gunicorn is the WSGI server to which we are configuring our application to run on, with the following configuration.
  • -w 4 indicates that we need our application to run on gunicorn with 4 worker processes.
  • -k uvicorn.workers.UvicornWorker tells the gunicorn to run the application using uvicorn.workers.UvicornWorker worker class.
  • main:app is our module main where our FastAPI() app is initialized.

You can also specify the host and port. But Heroku will automatically figure them out and no extra configuration is needed for this demo.

Push your repository to GitHub

GitHub is an open platform to host your software related code files. You can configure your code to be publicly available or make it private as per your need. In case you are new to GitHub, go for it and register for free. Follow this detailed tutorial to add your existing project to GitHub.

Configure FastAPI Deployment on Heroku

Signup for a free Heroku account if you do not have already. Heroku is a platform as a service (PaaS) that enables developers to build, run, and operate applications entirely in the cloud. Once you signup with a verified email account, proceed with creating an app.

Create and Configure app in Heroku

Create App in Heroku

  • Login to your verified Heroku account with registered email.
  • In the dashboard click on Create new app button. If you already have apps, click on New and select Create new app.
  • Give an App name that is available. You must ensure that the App name must be unique across all other Heroku apps across all the users registered with it. Otherwise Heroku will not allow you to create the app.
  • Choose a region or leave it to default region selected as United States
  • Ignore the Add to pipeline option unless you want to configure a deployment pipeline.
  • Click on Create app button.

Connect to GitHub

  • Under the Deployment method select the option GitHub and connect to GitHub.
  • First time users need to link the GitHub account by signing into the account where the repository is pushed. Existing users will automatically see the option to search a repository.
  • Once connected, Search for a repository to connect to. Search for the repository by the name you gave while creating a new repository in GitHub.
  • In the search results look for and Connect to the repository where our FastAPI application is located.

Configure Automatic Deployment in Heroku from GitHub

Once you connect to the repository successfully, you will see option to Configure Automatic Deploys.
Leave the option to Choose a branch to deploy to master and click on Enable Automatic Deploys. This setting will automatically trigger the deployment that builds and publishes the latest changes every time you push the new code changes to the master branch.
From the Manual deploy section, Enter the name of the branch to deploy as master and click on Deploy Branch.
Wait for the deployment process to complete. Once done, you should see Your app was successfully deployed.
Click on View button to see your first Python based FastAPI app deployed to Heroku. 🎉

Video Tutorial

In case you are familiar with the basics of FastAPI, you might just want to understand how to deploy FastAPI app to Heroku. The following video tutorial will guide you to do that in just 6 minutes.

Deploy FastAPI on Heroku in just 6 minutes – TutLinks

Congratulations 🎉, you have mastered the basics of FastAPI Hello World app and understood how to deploy FastAPI app to Heroku.

Bookmark 🔖 (Ctrl + D) this page as a quick reference on how to deploy FastAPI app to Heroku.

Check these resources to deploy FastAPI on On Premises and other Cloud Platforms

Navule Pavan Kumar Rao

I am a Full Stack Software Engineer with the Product Development experience in Banking, Finance, Corporate Tax and Automobile domains. I use SOLID Programming Principles and Design Patterns and Architect Software Solutions that scale using C#, .NET, Python, PHP and TDD. I am an expert in deployment of the Software Applications to Cloud Platforms such as Azure, GCP and non cloud On-Premise Infrastructures using shell scripts that become a part of CI/CD. I pursued Executive M.Tech in Data Science from IIT, Hyderabad (Indian Institute of Technology, Hyderabad) and hold B.Tech in Electonics and Communications Engineering from Vaagdevi Institute of Technology & Science.

This Post Has 3 Comments

Leave a Reply