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 inside the folder.
  2. Example:
    
        mkdir restapi-example-web
        cd restapi-example-web
        
  3. Inside the project folder, create a virtual environment using the command as <python.version> -m virtualenv <name>.
  4. 
        python3.9 -m virtualenv env39
        
  5. Activate the virtual environment using the command:
  6. 
        source env39/bin/activate
        

Install Dependencies

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

Create REST APIs

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

main.py

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")


@app.get("/")
def read_root():
    return {"Hello": "World"}


@app.get("/users/{user_id}")
def read_user(user_id: int):
    return {"user_id": user_id, "full_name": "Danny Manny", "email": "danny.manny@gmail.com"}


@app.post("/users/add")
def add_user(user: User):
    return {"full_name": user.first_name+" "+user.last_name}


@app.put("/users/update")
def update_user(user: User):
    return {"user_id": user.user_id, "full_name": user.first_name+" "+user.last_name, "email": user.email}


@app.delete("/users/{user_id}/delete")
def delete_user(user_id: int):
    return {"user_id": user_id, "is_deleted": True}


if __name__ == '__main__':
    uvicorn.run(app, host='127.0.0.1', port=8005)
    print("running")

Run your Application

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

To run your application, call the main.py file:


python3.9 main.py    

To call APIs, you can use some HTTP requesting tool, such as POSTMAN.