π FastAPI Cheat Sheet

Full-Stack Web Developer with over 25 years of professional experience. I have experience in database development using Oracle, MySQL, and PostgreSQL. I have extensive experience with API and SQL development using PHP and associated frameworks. I am skilled with git/github and CI/CD. I have a good understanding of performance optimization from the server and OS level up to the application and database level. I am skilled with Linux setup, configuration, networking and command line scripting. My frontend experience includes: HTML, CSS, Sass, JavaScript, jQuery, React, Bootstrap and Tailwind CSS. I also have experience with Amazon EC2, RDS and S3.
β Install FastAPI and Uvicorn
pip install fastapi uvicorn
π Run Your App
uvicorn main:app --reload
Note: main is your Python file, app is the FastAPI instance.
π§± Basic Setup
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello World"}
π Path & Query Parameters
@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
return {"item_id": item_id, "query": q}
π¦ Request Body with Pydantic
from pydantic import BaseModel
class Item(BaseModel):
name: str
price: float
is_offer: bool = False
@app.post("/items/")
def create_item(item: Item):
return item
π Response Model
@app.post("/items/", response_model=Item)
def create_item(item: Item):
return item
π Path, Query, and Body Combined
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item, q: str = None):
return {"item_id": item_id, "item": item, "query": q}
π‘ Optional & Default Values
from typing import Optional
@app.get("/users/")
def get_user(name: Optional[str] = "Guest"):
return {"user": name}
π List Responses
from typing import List
@app.get("/items/", response_model=List[Item])
def list_items():
return [
{"name": "Book", "price": 12.99, "is_offer": False},
{"name": "Pen", "price": 1.5, "is_offer": True}
]
β οΈ Error Handling
from fastapi import HTTPException
@app.get("/secret")
def read_secret(key: str):
if key != "open-sesame":
raise HTTPException(status_code=401, detail="Unauthorized")
return {"message": "Welcome!"}
π§ͺ Swagger Docs & Redoc
FastAPI provides these by default:
Swagger UI:
http://localhost:8000/docsReDoc:
http://localhost:8000/redoc
π Organize with APIRouter
from fastapi import APIRouter
router = APIRouter()
@router.get("/health")
def health_check():
return {"status": "ok"}
# In main.py
from fastapi import FastAPI
from my_router import router
app = FastAPI()
app.include_router(router)


