Cheat sheets
FastAPI cheat sheet
Quick reference for FastAPI: defining routes, validating data with Pydantic, and auto-documenting the API.
Basic routes
@app.get("/items/{id}")- GET route decorator with a typed path parameter.
def read(id: int): ...- The parameter's type is validated automatically.
@app.post("/items")- POST route decorator.
def create(item: Item): ...- Receives and validates the request body as a model.
def list_items(skip: int = 0, limit: int = 10): ...- Query parameters with default values.
Validation with Pydantic
class Item(BaseModel): name: str; price: float- Data model with automatic validation.
name: str = Field(min_length=1)- Validation constraint on a field.
class ItemOut(Item): id: int- Output model kept separate from the input model.
Errors and responses
raise HTTPException(status_code=404, detail="Not found")- Returns an HTTP error with detail.
@app.get("/items", response_model=list[ItemOut])- Declares the response schema.
@app.get("/items", status_code=201)- Sets the route's default status code.
Automatic documentation
/docs- Interactive Swagger UI, generated automatically.
/openapi.json- The API's OpenAPI schema in JSON.