Create REST API using FastAPI in Python
This tutorial will guide you in creating REST APIs from scratch using FastAPI in Python.
FastAPI is a modern Python 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 complete this tutorial:
STEP 1 - Setting Up Environment
- Before you start, make sure you have Python, pip and virtual environment installed on your system. You can check your Python version by running python --version in your terminal.
- Create a new project folder, and then navigate to that folder via a terminal or command prompt:
- Next, inside the folder, create a virtual environment using the command given below:
- Activate the virtual environment using the following command:
mkdir example-app cd example-app
Windows:
py -m venv env
Unix/macOS:
python3 -m venv env
Windows:
.\env\Scripts\activate
Unix/macOS:
source env/bin/activate
STEP 2 - Installing Dependencies
- Install FastAPI dependency:
- Install uvicorn. Uvicorn is an implementation of ASGI server for fast performance. To install uvicorn, use this command:
pip install fastapi
pip install "uvicorn[standard]"
STEP 3 - Create FastAPI Endpoints
Create a Python file (for example: main.py) inside the project folder to define your FastAPI application. Import FastAPI and create an instance of it. Next, you can define your API endpoints. Create Python functions that correspond to the HTTP methods you want to support (e.g., GET, POST, PUT, DELETE). Use FastAPI decorators to define routes and request parameters:
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")
STEP 4 - Run and Test your FastAPI Application
When you run your application, make sure your virtual environment is activated. Execute your Python file (main.py):
python main.py
Once your application starts, you can see tha documentation of your APIs at http://127.0.0.1:8005/docs.