Create REST API using FastAPI in Python

In this tutorial, we will learn how to create REST APIs using FastAPI from scratch in Python:

FastAPI is a Python modern web framework for building fast, high performance APIs.

FastAPI is fast because it uses ASGI. ASGI stands for Asynchronous Server Gateway Interface. ASGI is a successor to the WSGI.

WSGI stands for Web Server Gateway Interface. WSGI is synchronous and therefore is slower than ASGI. Frameworks like Django, Flask, Falcon use WSGI.

Follow the steps below to create REST APIs using FastAPI:

Create a Python Project

To maintain dependencies in this example project, you must have virtualenv and pip installed on your computer. If you haven't done it yet then we recommended you to install them first. Here is a guide to install virtualenv and pip.

  1. Create a project folder and navigate to it:
  2. mkdir restapi-example-web
    cd restapi-example-web
  3. Inside the project folder, create a virtual environment using the command:
         virtualenv env
  5. Activate the virtual environment using the command:
  6. On ubuntu/Linux/Mac
        source env/bin/activate
    On Windows

Installing Dependencies

  1. Install FastAPI dependency using the command:
    pip install fastapi
  3. Next, install uvicorn. Uvicorn is an implementation of ASGI server for fast performance. To install uvicorn, use the command:
    pip install uvicorn

Create REST APIs

Create a file inside the project folder root directory and add the code as shown in the example below:

import uvicorn
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel, Field

app = FastAPI()

class User(BaseModel):
    user_id: Optional[int] = None
    first_name: str
    last_name: str
    email: str
    father_name: Optional[str] = Field(
        None, title="The father name of the user", max_length=300
    age: float = Field(..., gt=0,
                       description="The age must be greater than zero")

def read_root():
    return {"Hello": "World"}

def read_user(user_id: int):
    return {"user_id": user_id, "full_name": "Danny Manny", "email": "[email protected]"}"/users/add")
def add_user(user: User):
    return {"full_name": user.first_name+" "+user.last_name}

def update_user(user: User):
    return {"user_id": user.user_id, "full_name": user.first_name+" "+user.last_name, "email":}

def delete_user(user_id: int):
    return {"user_id": user_id, "is_deleted": True}

if __name__ == '__main__':, host='', port=8005)

Run your Application

When you run your application, make sure your virtual environment is activated.

To run your application, call the file:


Once the application is running, you can see tha documentation of your APIs at