FastAPI Cheatsheet
Path Operations
Use this FastAPI reference while you build software engineering projects, review code, or refresh the syntax you reach for most.
HTTP Method Decorators
from fastapi import FastAPI app = FastAPI() @app.get("/items") def get_items(): ... @app.post("/items") def create_item(): ... @app.put("/items/{id}") def replace_item(id: int): ... @app.patch("/items/{id}") def update_item(id: int): ... @app.delete("/items/{id}") def delete_item(id: int): ... @app.head("/items") def head_items(): ... @app.options("/items") def options_items(): ...
Decorator Parameters
@app.get( "/items/{id}", summary="Get a single item", # shows in docs description="Longer description here", # Markdown supported response_description="The item", # docs label for 200 response tags=["items"], # grouping in Swagger UI status_code=200, # default response code response_model=ItemOut, # shape the response response_model_exclude_unset=True, # omit fields not explicitly set response_model_exclude_none=True, # omit None fields response_model_include={"id", "name"}, response_model_exclude={"password"}, deprecated=True, # mark in docs include_in_schema=False, # hide from OpenAPI entirely operation_id="getItem", # custom OpenAPI operationId responses={ 404: {"description": "Not found"}, 422: {"description": "Validation error"}, }, ) def get_item(id: int): ...
Path Parameters
@app.get("/users/{user_id}/posts/{post_id}") def get_post(user_id: int, post_id: int): return {"user": user_id, "post": post_id}
Path parameter names must match the
{name}in the path string.
Response Model
from pydantic import BaseModel class ItemIn(BaseModel): name: str price: float secret: str class ItemOut(BaseModel): name: str price: float # secret is NOT here — filtered automatically @app.post("/items", response_model=ItemOut) def create_item(item: ItemIn): return item # FastAPI filters to ItemOut shape
Return Types (Python 3.10+)
# Use return type annotation instead of response_model: @app.get("/items/{id}") def get_item(id: int) -> ItemOut: ...
Multiple Response Models / Union
from typing import Union @app.get("/things/{id}", response_model=Union[Cat, Dog]) def get_thing(id: int): ...
List Responses
from typing import List @app.get("/items", response_model=List[ItemOut]) def list_items() -> list[ItemOut]: return db.query_all()
Route Order Matters
# CORRECT — fixed path before parameterized: @app.get("/users/me") def get_me(): ... @app.get("/users/{user_id}") def get_user(user_id: int): ... # WRONG — /users/me would be swallowed by {user_id} above it
APIRouter: Grouping Routes
from fastapi import APIRouter router = APIRouter( prefix="/items", tags=["items"], responses={404: {"description": "Not found"}}, ) @router.get("/") def list_items(): ... @router.get("/{id}") def get_item(id: int): ... # main.py app.include_router(router)
Returning Raw Responses
from fastapi.responses import ( JSONResponse, HTMLResponse, PlainTextResponse, RedirectResponse, StreamingResponse, FileResponse, Response, ) @app.get("/redirect") def redirect(): return RedirectResponse(url="/new-url", status_code=302) @app.get("/html", response_class=HTMLResponse) def html_page(): return "<h1>Hello</h1>" @app.get("/file") def download(): return FileResponse("report.pdf", filename="report.pdf") @app.get("/stream") def stream(): def gen(): for i in range(10): yield f"chunk {i}\n" return StreamingResponse(gen(), media_type="text/plain")
Documenting with Docstrings
@app.get("/items/{id}") def get_item(id: int): """ Retrieve a single item by its **ID**. - **id**: the unique integer identifier """ ...
FastAPI renders the docstring as the route's description in Swagger UI (Markdown supported).