Back to knowledge base

The Ultimate FastAPI Cheatsheet

10 min readCheatsheets

The Ultimate FastAPI Cheatsheet

FastAPI is one of the fastest and most popular Python web frameworks for building APIs. Thanks to its native support for async execution and automatic data validation via Pydantic, it makes backend development a breeze. Here is your reference guide to its core features.

Async API Basics

FastAPI is built to be asynchronous from the ground up, allowing your server to handle concurrent requests efficiently.

from fastapi import FastAPI
import asyncio
 
app = FastAPI()
 
# A standard synchronous endpoint
@app.get("/sync")
def sync_endpoint():
    return {"message": "I block the event loop if I do heavy work."}
 
# An asynchronous endpoint
@app.get("/async")
async def async_endpoint():
    await asyncio.sleep(1) # Simulating a non-blocking I/O operation
    return {"message": "I am fast and concurrent!"}

FastAPI Routes

Defining routes and handling path and query parameters.

# Path Parameters
@app.get("/users/{user_id}")
async def read_user(user_id: int):
    # user_id is automatically validated as an integer
    return {"user_id": user_id}
 
# Query Parameters
# If a parameter is not in the path, it is interpreted as a query parameter
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
    return {"skip": skip, "limit": limit}
 
# Multiple HTTP Methods
@app.post("/create")
async def create_data():
    return {"message": "Data created"}
 
@app.put("/update/{item_id}")
async def update_data(item_id: int):
    return {"message": f"Updated {item_id}"}

Pydantic Models

FastAPI uses Pydantic for data validation, serialization, and schema generation.

from pydantic import BaseModel, EmailStr, Field
 
class UserCreate(BaseModel):
    username: str = Field(..., min_length=3, max_length=50)
    email: EmailStr
    age: int | None = None  # Optional field
    is_active: bool = True
 
@app.post("/users/")
async def create_user(user: UserCreate):
    # The 'user' parameter is automatically parsed from JSON and validated!
    return {"username": user.username, "email": user.email}

Dependency Injection

A powerful feature to share logic (like database connections or authentication) across routes.

from fastapi import Depends, Header, HTTPException
 
# 1. Define a dependency function
async def verify_token(x_token: str = Header(...)):
    if x_token != "supersecrettoken":
        raise HTTPException(status_code=400, detail="X-Token header invalid")
    return x_token
 
# 2. Inject it into a route
@app.get("/secure-data/")
async def get_secure_data(token: str = Depends(verify_token)):
    return {"message": "You have access!", "token": token}

FastAPI CRUD API

A quick blueprint for a standard Create, Read, Update, Delete setup using an in-memory database.

from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
 
app = FastAPI()
 
class Item(BaseModel):
    name: str
    price: float
 
# In-memory "database"
db = {}
 
# CREATE
@app.post("/items/{item_id}")
async def create_item(item_id: int, item: Item):
    if item_id in db:
        raise HTTPException(status_code=400, detail="Item already exists")
    db[item_id] = item
    return item
 
# READ
@app.get("/items/{item_id}")
async def read_item(item_id: int):
    if item_id not in db:
        raise HTTPException(status_code=404, detail="Item not found")
    return db[item_id]
 
# UPDATE
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    if item_id not in db:
        raise HTTPException(status_code=404, detail="Item not found")
    db[item_id] = item
    return {"message": "Updated successfully", "item": item}
 
# DELETE
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
    if item_id not in db:
        raise HTTPException(status_code=404, detail="Item not found")
    del db[item_id]
    return {"message": "Deleted successfully"}

JWT Authentication

Securing your API using JSON Web Tokens (requires PyJWT and passlib).

from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
import jwt
from datetime import datetime, timedelta
 
app = FastAPI()
 
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
 
# This tells FastAPI where the client should send credentials to get a token
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
 
def create_jwt_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=30)
    to_encode.update({"exp": expire})
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
 
# 1. Login route to generate token
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
    # In a real app, verify username and password against a database here
    if form_data.username != "admin" or form_data.password != "password":
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    
    token = create_jwt_token({"sub": form_data.username})
    return {"access_token": token, "token_type": "bearer"}
 
# 2. Secure route protecting data
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        username = payload.get("sub")
        if username is None:
            raise HTTPException(status_code=401, detail="Invalid token")
    except jwt.PyJWTError:
        raise HTTPException(status_code=401, detail="Invalid token")
        
    return {"username": username, "status": "Authenticated"}

Read Next

Cheatsheets

The Ultimate AI & LangChain Cheatsheet

A comprehensive guide to AI development with LangChain and OpenAI. Master prompt engineering, RAG, agents, embeddings, and vector databases.

Cheatsheets

The Ultimate Deployment Cheatsheet

A comprehensive guide to deploying web apps. Master Vercel, VPS setup, Nginx, environment variables, domain configuration, and SSL certificates.