100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace

Python FastAPI Cheat Sheet

Python FastAPI Cheat Sheet

Covers FastAPI route definitions, path and query parameters, Pydantic request/response models, and the dependency injection system.

2 PagesIntermediateApr 15, 2026

Minimal FastAPI App

Auto-generated docs come for free.

python
from fastapi import FastAPIapp = FastAPI()@app.get("/")def read_root():    return {"message": "Hello, FastAPI!"}# Run with: uvicorn main:app --reload# Interactive docs auto-generated at /docs (Swagger UI) and /redoc

Path & Query Parameters

Parameters are validated automatically from type hints.

python
from typing import Optional@app.get("/items/{item_id}")def read_item(item_id: int, q: Optional[str] = None):    # item_id is validated as int from the URL path    # q is an optional query string param: /items/5?q=foo    return {"item_id": item_id, "q": q}@app.get("/items/")def list_items(skip: int = 0, limit: int = 10):    return {"skip": skip, "limit": limit}

Request Bodies with Pydantic

Define and validate JSON payloads.

python
from pydantic import BaseModelclass Item(BaseModel):    name: str    price: float    is_offer: bool = False@app.post("/items/")def create_item(item: Item):    # FastAPI parses & validates the JSON body against Item    return {"name": item.name, "total": item.price}@app.put("/items/{item_id}")def update_item(item_id: int, item: Item) -> Item:    return item

Dependency Injection

Share reusable logic like auth checks and pagination across routes.

python
from fastapi import Depends, HTTPExceptiondef get_token_header(x_token: str):    if x_token != "secret":        raise HTTPException(status_code=400, detail="Invalid token")    return x_token@app.get("/secure-data/")def secure_data(token: str = Depends(get_token_header)):    return {"token": token}# Class-based dependency with shared stateclass Pagination:    def __init__(self, skip: int = 0, limit: int = 10):        self.skip = skip        self.limit = limit@app.get("/users/")def list_users(pagination: Pagination = Depends()):    return {"skip": pagination.skip, "limit": pagination.limit}

FastAPI Essentials

Frequently used decorators and parameters.

  • @app.get/post/put/delete- Decorators mapping a function to an HTTP method and path
  • response_model=- Declares the Pydantic model used to serialize and validate the response
  • status_code=201- Sets the default HTTP status code for a route
  • async def- Route handlers can be async for non-blocking I/O; sync def also works
  • HTTPException- Raise to short-circuit with an HTTP error status and detail message
  • APIRouter- Group related routes into a module, then include_router() them into the app
  • BackgroundTasks- Run a function after the response is returned (e.g. sending an email)
Pro Tip

FastAPI generates the OpenAPI schema directly from your type hints and Pydantic models, so keep response_model set on every route — it also filters the response down to only the fields you intended to expose.

Was this cheat sheet helpful?

Explore Topics

#PythonFastAPI#PythonFastAPICheatSheet#Programming#Intermediate#MinimalFastAPIApp#PathQueryParameters#RequestBodiesWithPydantic#DependencyInjection#Databases#CheatSheet#SkillVeris
Advertisement
Sri Hayavadhana Info-Tech

Professional Web Designing Services

  • Responsive Websites
  • E-commerce Solutions
  • SEO Friendly Design
  • Fast & Secure
  • Support & Maintenance
Get a Free Quote

Share this Cheat Sheet