Skip to main content

Command Palette

Search for a command to run...

πŸš€ FastAPI Cheat Sheet

Updated
β€’2 min read
πŸš€ FastAPI Cheat Sheet
D

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:

πŸ“ 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)