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 backendRoutes and models
| What | How |
|---|---|
| Route | @app.get("/books/{book_id}") |
| A 404 error | raise HTTPException(404, "Not found") |
| Body | def create(user: UserIn) |
| Response | @app.post(..., response_model=UserOut, status_code=201) |
Dependencies
| What | How |
|---|---|
| Database | db: Session = Depends(get_db) |
| User | user: User = Depends(get_current_user) |
| Run | fastapi dev main.py |
Structure and production
| What | How |
|---|---|
| Router | router = APIRouter(prefix="/books", tags=["books"]) |
| Include | app.include_router(books.router) |
| Custom handler | @app.exception_handler(BookNotFound) |
| After the response | background_tasks.add_task(send_welcome, email) |
| Startup and shutdown | FastAPI(lifespan=lifespan) |
| Production | fastapi run main.py --workers 4 |