One page

FastAPI cheat sheet

What to keep at hand. If a line is not clear, go back to the matching lesson in the course.

Open the course: FastAPI: a Python backend

Routes and models

WhatHow
Route@app.get("/books/{book_id}")
A 404 errorraise HTTPException(404, "Not found")
Bodydef create(user: UserIn)
Response@app.post(..., response_model=UserOut, status_code=201)

Dependencies

WhatHow
Databasedb: Session = Depends(get_db)
Useruser: User = Depends(get_current_user)
Runfastapi dev main.py

Structure and production

WhatHow
Routerrouter = APIRouter(prefix="/books", tags=["books"])
Includeapp.include_router(books.router)
Custom handler@app.exception_handler(BookNotFound)
After the responsebackground_tasks.add_task(send_welcome, email)
Startup and shutdownFastAPI(lifespan=lifespan)
Productionfastapi run main.py --workers 4

Other cheat sheets