FastAPI is a high-performance web framework for building APIs with Python. It was created to make the process of developing web applications and APIs faster, simpler, and more efficient. It's a great option for creating strong and well-documented APIs.

If you are looking for other deployment tutorials checkout out one of these:

In this post:

Key benefits of FastAPI

The primary purpose of FastAPI is to enable developers to build APIs quickly and efficiently. Also, its focus on performance makes it a great choice for high-throughput apps and services.

Things to know about FastAPI:

  1. Fast: FastAPI is built on top of Starlette, a high-performance asynchronous web framework. This enables FastAPI to handle many concurrent connections.
  2. With help of type hints FastAPI validates incoming request data and helps avoid errors.
  3. FastAPI generates interactive API documentation based on the provided type hints. Uses It offers an interactive Swagger UI and ReDoc.

FastAPI vs Django

Django is a full-featured web framework that follows the "batteries-included" philosophy. While Django is excellent for building complete web applications, it might be overkill if you only need to create APIs. FastAPI, is specifically designed for API development and is more lightweight and faster.

FastAPI versus Flask

Flask is a micro web framework. It is minimalistic and gives developers the flexibility to choose extra libraries. Flask is fine for small to medium-sized projects and offers simplicity and ease of use. Yet, absence of async support can limit Flask's performance in certain scenarios.

If you are building a high-performance API FastAPI is an excellent option.

Create a FastAPI app

Here is the link to the demo repository: https://github.com/appliku/fastapi_demo

Setup the environment

  1. First create an app directory
mkdir fastapi_demo
cd fastapi_demo
  1. Create virtual environment and install packages, then save all dependencies to the requirements.txt file for deployment to work.
python3 -m venv env
source env/bin/activate
pip install fastapi uvicorn sqlalchemy psycopg2-binary
pip freeze > requirements.txt
  1. Create a file main.py with the following code:
# main.py
import os

import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
from sqlalchemy import Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from starlette.responses import HTMLResponse

app = FastAPI()

DATABASE_URL = os.environ['DATABASE_URL']
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()


class Message(Base):
    __tablename__ = "messages"
    id = Column(Integer, primary_key=True, index=True)
    name = Column(String, index=True)
    email = Column(String, index=True)
    message = Column(String, index=True)


# Create the table in the database
Base.metadata.create_all(bind=engine)


class MessageIn(BaseModel):
    name: str
    email: str
    message: str


@app.post("/messages/", response_model=MessageIn)
def create_message(message: MessageIn):
    db_message = Message(**message.model_dump())
    db = SessionLocal()
    db.add(db_message)
    db.commit()
    db.refresh(db_message)
    db.close()
    return db_message


@app.get("/", response_model=str)
def home():
    return "OK"


if __name__ == "__main__":
    try:
        port = os.environ.get("PORT", "5000")
        port = int(port)
    except ValueError:
        port = 5000
    uvicorn.run("main:app", host='0.0.0.0', port=port, log_level="info")

What this code does:

  • app = FastAPI() this creates an instance of FastAPI app
  • Set up database connection:
DATABASE_URL = os.environ['DATABASE_URL']
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()

This grabs the database connection string from the environment variable DATABASE_URL. It will throw an exception if environment variable is not set. Then creates SQLAlchemy engine with the provided DATABASE_URL and creates a database session.

  • Message class represents the table in the database
  • Base.metadata.create_all(bind=engine): This line creates the "messages" table in the database if it doesn't exist yet, based on the Message model.
  • MessageIn: A Pydantic model that will be used to validate the input data for creating messages.
  • Two endpoints create_message, which accepts POST requests and writes data to the database table Messages and the home endpoint that simply returns OK . It can be useful to make verify that app is running.
  • Finally, we launch our app using uvicorn. We do it in the code of the app itself, not in command line to make sure it respects the environment variable PORT. If it is not set, then the default port 5000 will be used.

Also create the .gitgnore file. Main thing to include in this file is python cache files, virtual env and your editor of choice dot directory. Extend the following list for your own setup.

env/
.idea/
__pycache__/
*.py[cod]
*$py.class
.vscode/
.DS_Store
.AppleDouble
.LSOverride

Now we need to initialize a git repository and commit it.

git init
git add .
git commit -m'Initial commit'

Create a GitHub or GitLab repository, add the remote and let's deploy it with Appliku.

Deploy FastAPI on AWS EC2 Instance

If you haven't already – create an account in Appliku (https://app.appliku.com)[https://app.appliku.com]

Appliku automates the server setup and application deployment. It also takes care of the database creation, managing environment variables and automatically builds and deploys your FastAPI app when you push new changes to the attached git repository.

In this post I will show you how to deploy the FastAPI app on an AWS EC2 instance.

In Appliku dashboard go to the Servers tab.

If you haven't set up AWS connection then follow instructions to generate required credentials and add them to your team.

When it is done you will be able to create an AWS EC2 Instance.

Select AWS provider.

image

Select the region, instance type and the disk size. To fit in AWS Free Tier make sure the disk size to be <30GB.

image

image

Click "Create EC2 Instance".

You will be taken to the server page where you will see the setup process. When it is finished, go to Applications tab and create a new app from GitHub (or GitLab if you hosted your repository there)

Give application a name, pick your repository and the branch, select the server you have just created.

image

After clicking on "Create Application" you will be taken to the application overview.

Go to databases Management to create a Postgres Database on your your server. image

image

Wait for it to finish deploying and go back to application overview by click on the app's name image

On the application overview page click Add Processes button. image

Add a "web" process with command python main.py and click Save and Deploy. image

When deployment is finished click on "Open App" and click on the domain name.

image

You will see that app responds with our "OK" string, which means deployment went fine.

image

Now go to terminal and run a CURL command to save a message.

curl --request POST \
  --url https://fastapidemo.applikuapp.com/messages/ \
  --header 'Content-Type: application/json' \
  --data '{
    "name" : "john Snow",
    "email": "123@example.com",
    "message": "hello"
}'

image

You can now go back to the database and copy the credentials.

To do that, from the application overview click on the database link. image

On the database page click "Show credentials" button.

image

The database URL will appear, which you can now copy and paste into postgres client of your choice. image

I will do it from terminal using psql: image

You can see that table is created and there is a record with our message.

Congratulations! You have deployed a fully functional FastAPI with a PostgreSQL database!