FastAPI Helper
Build modern, high-performance Python APIs with FastAPI.
Quick Start
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
Run: uvicorn main:app --reload
Core Concepts
Route Decorators
| Decorator |
HTTP Method |
@app.get() |
GET |
@app.post() |
POST |
@app.put() |
PUT |
@app.delete() |
DELETE |
@app.patch() |
PATCH |
Parameter Functions
| Function |
Source |
Path() |
URL path /items/{id} |
Query() |
Query string ?q=foo |
Body() |
JSON body |
Header() |
HTTP headers |
Cookie() |
Cookies |
Form() |
Form data |
File() / UploadFile |
File uploads |
Dependency Injection
from fastapi import Depends
async def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
@app.get("/items/")
async def read_items(db: Session = Depends(get_db)):
return db.query(Item).all()
Common Imports
from fastapi import (
FastAPI, APIRouter, Depends, HTTPException, status,
Request, Response, BackgroundTasks, WebSocket,
Path, Query, Body, Header, Cookie, Form, File, UploadFile
)
from fastapi.responses import JSONResponse, HTMLResponse, FileResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field, EmailStr
Reference Documentation
Load these based on task:
| Task |
Reference File |
| Routes, APIRouter, decorators |
references/routing.md |
| Path, Query, Body, Form, File params |
references/parameters.md |
| Response types, status codes, headers |
references/responses.md |
| Depends, Security, OAuth2 |
references/dependencies.md |
| Middleware, CORS, lifespan, BackgroundTasks |
references/middleware-events.md |
| WebSocket connections |
references/websockets.md |
| HTTPException, error handlers |
references/exceptions.md |
| Pydantic models, validation |
references/pydantic-models.md |
| TestClient, pytest fixtures |
references/testing.md |
Common Patterns
CRUD Endpoint Structure
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.orm import Session
router = APIRouter(prefix="/items", tags=["items"])
@router.get("/", response_model=list[ItemOut])
async def list_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
return db.query(Item).offset(skip).limit(limit).all()
@router.get("/{item_id}", response_model=ItemOut)
async def get_item(item_id: int, db: Session = Depends(get_db)):
item = db.query(Item).filter(Item.id == item_id).first()
if not item:
raise HTTPException(status_code=404, detail="Item not found")
return item
@router.post("/", response_model=ItemOut, status_code=status.HTTP_201_CREATED)
async def create_item(item: ItemCreate, db: Session = Depends(get_db)):
db_item = Item(**item.model_dump())
db.add(db_item)
db.commit()
db.refresh(db_item)
return db_item
@router.put("/{item_id}", response_model=ItemOut)
async def update_item(item_id: int, item: ItemUpdate, db: Session = Depends(get_db)):
db_item = db.query(Item).filter(Item.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Item not found")
for key, value in item.model_dump(exclude_unset=True).items():
setattr(db_item, key, value)
db.commit()
return db_item
@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
async def delete_item(item_id: int, db: Session = Depends(get_db)):
db_item = db.query(Item).filter(Item.id == item_id).first()
if not db_item:
raise HTTPException(status_code=404, detail="Item not found")
db.delete(db_item)
db.commit()
CORS Setup
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
JWT Authentication Pattern
from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = decode_token(token)
if not user:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Invalid credentials",
headers={"WWW-Authenticate": "Bearer"},
)
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
1---2name: fastapi-helper3description: FastAPI development assistant for building modern Python web APIs. Provides guidance on routing, request/response handling, dependency injection, authentication, middleware, WebSockets, testing, and Pydantic models. Use when: (1) Creating FastAPI applications or endpoints, (2) Implementing CRUD operations, (3) Setting up authentication/authorization, (4) Working with request parameters (path, query, body, headers, cookies, forms, files), (5) Configuring middleware or CORS, (6) Implementing WebSocket connections, (7) Writing tests for FastAPI apps, (8) Defining Pydantic models for validation.4---5
6# FastAPI Helper
7
8Build modern, high-performance Python APIs with FastAPI.
9
10## Quick Start
11
12```python
13from fastapi import FastAPI
14
15app = FastAPI()
16
17@app.get("/")
18async def root():
19 return {"message": "Hello World"}
20```
21
22Run: `uvicorn main:app --reload`
23
24## Core Concepts
25
26### Route Decorators
27
28| Decorator | HTTP Method |
29|-----------|-------------|
30| `@app.get()` | GET |
31| `@app.post()` | POST |
32| `@app.put()` | PUT |
33| `@app.delete()` | DELETE |
34| `@app.patch()` | PATCH |
35
36### Parameter Functions
37
38| Function | Source |
39|----------|--------|
40| `Path()` | URL path `/items/{id}` |
41| `Query()` | Query string `?q=foo` |
42| `Body()` | JSON body |
43| `Header()` | HTTP headers |
44| `Cookie()` | Cookies |
45| `Form()` | Form data |
46| `File()` / `UploadFile` | File uploads |
47
48### Dependency Injection
49
50```python
51from fastapi import Depends
52
53async def get_db():
54 db = SessionLocal()
55 try:
56 yield db
57 finally:
58 db.close()
59
60@app.get("/items/")
61async def read_items(db: Session = Depends(get_db)):
62 return db.query(Item).all()
63```
64
65### Common Imports
66
67```python
68from fastapi import (
69 FastAPI, APIRouter, Depends, HTTPException, status,
70 Request, Response, BackgroundTasks, WebSocket,
71 Path, Query, Body, Header, Cookie, Form, File, UploadFile
72)
73from fastapi.responses import JSONResponse, HTMLResponse, FileResponse, RedirectResponse
74from fastapi.middleware.cors import CORSMiddleware
75from pydantic import BaseModel, Field, EmailStr
76```
77
78## Reference Documentation
79
80Load these based on task:
81
82| Task | Reference File |
83|------|----------------|
84| Routes, APIRouter, decorators | [references/routing.md](references/routing.md) |
85| Path, Query, Body, Form, File params | [references/parameters.md](references/parameters.md) |
86| Response types, status codes, headers | [references/responses.md](references/responses.md) |
87| Depends, Security, OAuth2 | [references/dependencies.md](references/dependencies.md) |
88| Middleware, CORS, lifespan, BackgroundTasks | [references/middleware-events.md](references/middleware-events.md) |
89| WebSocket connections | [references/websockets.md](references/websockets.md) |
90| HTTPException, error handlers | [references/exceptions.md](references/exceptions.md) |
91| Pydantic models, validation | [references/pydantic-models.md](references/pydantic-models.md) |
92| TestClient, pytest fixtures | [references/testing.md](references/testing.md) |
93
94## Common Patterns
95
96### CRUD Endpoint Structure
97
98```python
99from fastapi import APIRouter, Depends, HTTPException, status
100from sqlalchemy.orm import Session
101
102router = APIRouter(prefix="/items", tags=["items"])
103
104@router.get("/", response_model=list[ItemOut])
105async def list_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
106 return db.query(Item).offset(skip).limit(limit).all()
107
108@router.get("/{item_id}", response_model=ItemOut)
109async def get_item(item_id: int, db: Session = Depends(get_db)):
110 item = db.query(Item).filter(Item.id == item_id).first()
111 if not item:
112 raise HTTPException(status_code=404, detail="Item not found")
113 return item
114
115@router.post("/", response_model=ItemOut, status_code=status.HTTP_201_CREATED)
116async def create_item(item: ItemCreate, db: Session = Depends(get_db)):
117 db_item = Item(**item.model_dump())
118 db.add(db_item)
119 db.commit()
120 db.refresh(db_item)
121 return db_item
122
123@router.put("/{item_id}", response_model=ItemOut)
124async def update_item(item_id: int, item: ItemUpdate, db: Session = Depends(get_db)):
125 db_item = db.query(Item).filter(Item.id == item_id).first()
126 if not db_item:
127 raise HTTPException(status_code=404, detail="Item not found")
128 for key, value in item.model_dump(exclude_unset=True).items():
129 setattr(db_item, key, value)
130 db.commit()
131 return db_item
132
133@router.delete("/{item_id}", status_code=status.HTTP_204_NO_CONTENT)
134async def delete_item(item_id: int, db: Session = Depends(get_db)):
135 db_item = db.query(Item).filter(Item.id == item_id).first()
136 if not db_item:
137 raise HTTPException(status_code=404, detail="Item not found")
138 db.delete(db_item)
139 db.commit()
140```
141
142### CORS Setup
143
144```python
145from fastapi.middleware.cors import CORSMiddleware
146
147app.add_middleware(
148 CORSMiddleware,
149 allow_origins=["http://localhost:3000"],
150 allow_credentials=True,
151 allow_methods=["*"],
152 allow_headers=["*"],
153)
154```
155
156### JWT Authentication Pattern
157
158```python
159from fastapi import Depends, HTTPException, status
160from fastapi.security import OAuth2PasswordBearer
161
162oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
163
164async def get_current_user(token: str = Depends(oauth2_scheme)):
165 user = decode_token(token)
166 if not user:
167 raise HTTPException(
168 status_code=status.HTTP_401_UNAUTHORIZED,
169 detail="Invalid credentials",
170 headers={"WWW-Authenticate": "Bearer"},
171 )
172 return user
173
174@app.get("/users/me")
175async def read_users_me(current_user: User = Depends(get_current_user)):
176 return current_user
177```