Skip to content
Tutorials Center
My learning

Topics

Lesson 50 of 50 ยท Practice, interviews and cheat sheet

FastAPI cheat sheet

A one-page FastAPI cheat sheet: route decorators, parameter types, status codes, response models, dependency patterns, error handling and test snippets.

This is the page to keep open while you work: a compact recap of the FastAPI patterns you will use every day, with a link to the lesson that explains each one. Everything here is short on purpose. If a line surprises you, follow the link; if you want to see it work, run the two examples that bring the main patterns together.

The mental model

Type hints Signature decides the source.
Pydantic Validates in and out.
Depends Reusable building blocks.
OpenAPI Docs come for free.
1 / 2

Create and run

Python
from fastapi import FastAPI

app = FastAPI(title="My API", version="1.0.0")
Terminal
fastapi dev app/main.py              # development, auto-reload
uvicorn app.main:app --port 8000     # plain uvicorn
# docs: /docs (Swagger UI), /redoc, schema: /openapi.json

See What FastAPI is and how to set it up and Deployment.

Route decorators

Decorator Typical use Success code
@app.get(path) read 200
@app.post(path, status_code=201) create 201
@app.put(path) replace 200
@app.patch(path) partial update 200
@app.delete(path, status_code=204) delete 204 (no body)

Useful decorator arguments: response_model=, status_code=, tags=[...], summary=, dependencies=[...], responses={404: {...}}, response_class=, deprecated=True, include_in_schema=False.

Where each parameter comes from

In the signature Source Example
name inside in the path path item_id: int
{path:path} path, may contain / file_path: str
simple type query string limit: int = 10
Annotated[list[str], Query()] repeated query key ?tag=a&tag=b
Pydantic model JSON body item: ItemIn
Annotated[int, Body()] single body value {"qty": 3}
Annotated[str, Header()] request header (x_token is X-Token)
Annotated[str, Cookie()] cookie
Annotated[str, Form()] form field needs python-multipart
UploadFile / File() uploaded file needs python-multipart
Request, Response, BackgroundTasks injected by type

Validation shortcuts: Query(min_length=2, max_length=20, pattern=r"^[a-z]+$"), Query(ge=1, le=100), Path(gt=0), Field(gt=0, description="..."). Details: Path parameters, Query parameters, Request bodies, Headers, cookies, forms and uploads.

Status codes

Code Meaning Use it for
200 OK successful read or update
201 Created successful POST that creates
204 No Content successful delete
400 Bad Request malformed input not covered by validation
401 Unauthorized missing or invalid credentials
403 Forbidden authenticated but not allowed
404 Not Found unknown resource
409 Conflict duplicate or state conflict
422 Unprocessable Content validation failed (automatic)
429 Too Many Requests rate limit
500 Internal Server Error unexpected bug
Python
from fastapi import HTTPException, status

raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")

More in Status codes and error handling.

Models

Python
from pydantic import BaseModel, Field, field_validator

class ItemIn(BaseModel):
    name: str = Field(min_length=2, max_length=50)
    price: float = Field(gt=0)
    tags: list[str] = Field(default_factory=list)

class ItemOut(ItemIn):
    id: int

item.model_dump()                       # to dict
item.model_dump(exclude_unset=True)     # only fields that were sent (PATCH)
ItemIn.model_validate({"name": "A1", "price": 1})

The pattern: In model for input, Out model (no secrets) for response_model, a Patch model with optional fields for updates. See Pydantic models for APIs, Field constraints and validators and Response models and nested data.

Dependency patterns

Python
from typing import Annotated
from fastapi import Depends

async def pagination(skip: int = 0, limit: int = 20):          # shared parameters
    return {"skip": skip, "limit": limit}

async def get_db():                                             # setup / cleanup
    db = connect()
    try:
        yield db
    finally:
        db.close()

Db = Annotated[Connection, Depends(get_db)]                     # reusable alias
Page = Annotated[dict, Depends(pagination)]

def require_role(role: str):                                    # dependency factory
    async def checker(user: Annotated[User, Depends(current_user)]):
        if user.role != role:
            raise HTTPException(403, "Forbidden")
        return user
    return checker

router = APIRouter(dependencies=[Depends(require_login)])       # guard a whole router
app.dependency_overrides[get_db] = fake_get_db                  # in tests

Dependencies are cached per request (use_cache=False to disable). See Dependencies, Class and yield dependencies and Router-level and global dependencies.

Structure, middleware and lifespan

Python
router = APIRouter(prefix="/items", tags=["items"])
app.include_router(router)

@app.middleware("http")
async def timing(request, call_next):
    response = await call_next(request)
    response.headers["X-Process-Time"] = "..."
    return response

app.add_middleware(CORSMiddleware, allow_origins=["https://example.com"])

@asynccontextmanager
async def lifespan(app):
    app.state.client = make_client()      # startup
    yield
    await app.state.client.aclose()       # shutdown

app = FastAPI(lifespan=lifespan)

See Routers and project layout, Middleware and CORS, Lifespan events and app state and Settings and configuration.

Auth in one glance

Live recap: the patterns together

Python Parameters, models, dependencies and errors in one app

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Test snippets

Live version: an in-process async client and plain asserts. Overrides are async def, because the in-browser runner has no threads.

Python Test helper, override and assertions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The same tests in a real project (read-only):

Python
from fastapi.testclient import TestClient

def test_greet():
    with TestClient(app) as client:            # "with" runs lifespan events
        response = client.get("/greet/ada")
    assert response.status_code == 200

# pytest -q          run all tests
# pytest -k greet    run tests whose name contains "greet"

For the full approach read Testing FastAPI apps.

Quick reminders

  • async def + blocking call = stalled server. Use async libraries or plain def.
  • Fixed routes before parameterized ones.
  • Always set response_model so secret fields never leak.
  • Optional[X] is not a default in Pydantic v2: write = None.
  • Depends(func), never Depends(func()); always await coroutines.
  • One database session per request; commit explicitly; map unique violations to 409.
  • Migrate schemas with Alembic: Migrations with Alembic.

Check your understanding

Quick check ยท 3 questions

of 3 answered You scored / 3 ยท perfect!

  1. 1. Which status code should a successful DELETE normally return, with no body?

    204 No Content tells the client the deletion worked and there is nothing to read.
  2. 2. How do you make FastAPI read a parameter from a request header?

    Annotated[str, Header()] selects the header as the source. Underscores in the name map to hyphens.
  3. 3. Which line applies an authentication guard to every route of a router without injecting a value?

    Router-level dependencies run for each route in the router. Overrides are for tests, and Depends takes the function itself, not a call.

Summary

  • Type hints decide where each parameter comes from; Pydantic validates input and output.
  • Keep In, Out and Patch models separate and set response_model.
  • Dependencies share logic, resources and guards, are cached per request and can be overridden in tests.
  • Use the right status codes: 201 create, 204 delete, 401/403 for auth, 409 conflict, 422 validation.
  • Test in-process with an async client or TestClient, with a fresh state per test.

You have reached the end of the course. Return to the Exercises with solutions any time to keep your skills sharp.