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