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.
- Create a project folder and navigate to it:
- Inside the project folder, create a virtual environment using the command:
- Activate the virtual environment using the command: On ubuntu/Linux/Mac
cd restapi-example-web
virtualenv env
source env/bin/activate
On Windows
env/Scripts/activate
Installing Dependencies
- Install FastAPI dependency using the command:
- Next, install uvicorn. Uvicorn is an implementation of ASGI server for fast performance. To install uvicorn, use the command:
pip install fastapi
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": "[email protected]"}
@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
Once the application is running, you can see tha documentation of your APIs at http://127.0.0.1:8005/docs.