fastapi-backend
cohen-liel/hivemind/.claude/skills/fastapi-backend/SKILL.md
FastAPI best practices for building production Python backends. Use when building REST APIs, async endpoints, Pydantic models, dependency injection, middleware, or any FastAPI server.
Skill108 starsChanged 7 months ago
What's in it
- FastAPI Backend Patterns
- Project Structure
- Core Patterns
- App setup with lifespan
- Dependency injection
- Router pattern
- Error handling
- Pydantic schemas
- Rules
---
name: fastapi-backend
description: FastAPI best practices for building production Python backends. Use when building REST APIs, async endpoints, Pydantic models, dependency injection, middleware, or any FastAPI server.
---
# FastAPI Backend Patterns
## Project Structure
```
app/
main.py # FastAPI app, lifespan, middleware
config.py # Pydantic Settings, env vars
models/ # SQLAlchemy ORM models
schemas/ # Pydantic request/response schemas
routers/ # APIRouter per domain (auth, users, posts)
services/ # Business logic (no DB or HTTP here)
deps.py # Shared dependencies (get_db, get_current_user)
database.py # Engine, SessionLocal, Base
```
## Core Patterns
### App setup with lifespan
```python
from contextlib import asynccontextmanager
from fastapi import FastAPI
@asynccontextmanager
async def lifespan(app: FastAPI):
# startup
await database.connect()
yield
# shutdown
await database.disconnect()
app = FastAPI(lifespan=lifespan)
```
### Dependency injection
```python
# deps.py
async def get_db() -> AsyncGenerator[AsyncSession, None]:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
async def get_current_user(
token: str = Depends(oauth2_scheme),
db: AsyncSession = Depends(get_db)
) -> User:
...
```
### Router pattern
```python
router = APIRouter(prefix="/users", tags=["users"])
@router.get("/{user_id}", response_model=UserResponse)
async def get_user(user_id: int, db: AsyncSession = Depends(get_db)):
user = await db.get(User, user_id)
if not user:
raise HTTPException(status_code=404, detail="User not found")
return user
```
### Error handling
```python
from fastapi import Request
from fastapi.responses import JSONResponse
@app.exception_handler(ValueError)
async def value_error_handler(request: Request, exc: ValueError):
return JSONResponse(status_code=400, content={"detail": str(exc)})
```
### Pydantic schemas
```python
class UserCreate(BaseModel):
email: EmailStr
password: str = Field(min_length=8)
name: str = Field(max_length=100)
class UserResponse(BaseModel):
id: int
email: str
name: str
model_config = ConfigDict(from_attributes=True)
```
## Rules
- Always use async def for endpoints
- Validate ALL input with Pydantic (never trust raw dicts)
- Use HTTPException with specific status codes (not 500 for everything)
- Never put business logic in route handlers — use service layer
- Use response_model to control what's returned (never expose passwords)
- Add CORS middleware for browser clients
- Use Depends() for database sessions — never create sessions manually
More agent context in cohen-liel/hivemind
75 other files this repository gives its agents, the first 60 shown.
CLAUDE.md
Skill
- algorithmic-art.claude/skills/algorithmic-art/SKILL.md
- api-design.claude/skills/api-design/SKILL.md
- apple-notes.claude/skills/apple-notes/SKILL.md
- apple-reminders.claude/skills/apple-reminders/SKILL.md
- article-writing.claude/skills/article-writing/SKILL.md
- async-python.claude/skills/async-python/SKILL.md
- brand-guidelines.claude/skills/brand-guidelines/SKILL.md
- camsnap.claude/skills/camsnap/SKILL.md
- canvas-design.claude/skills/canvas-design/SKILL.md
- celery-tasks.claude/skills/celery-tasks/SKILL.md
- claude-api.claude/skills/claude-api/SKILL.md
- coding-agent.claude/skills/coding-agent/SKILL.md
- content-engine.claude/skills/content-engine/SKILL.md
- diffs.claude/skills/diffs/SKILL.md
- doc-coauthoring.claude/skills/doc-coauthoring/SKILL.md
- docker-deployment.claude/skills/docker-deployment/SKILL.md
- docx.claude/skills/docx/SKILL.md
- e2e-testing.claude/skills/e2e-testing/SKILL.md
- email-service.claude/skills/email-service/SKILL.md
- frontend-design.claude/skills/frontend-design/SKILL.md
- frontend-slides.claude/skills/frontend-slides/SKILL.md
- gh-issues.claude/skills/gh-issues/SKILL.md
- github.claude/skills/github/SKILL.md
- git-workflow.claude/skills/git-workflow/SKILL.md
- graphql-api.claude/skills/graphql-api/SKILL.md
- healthcheck.claude/skills/healthcheck/SKILL.md
- internal-comms.claude/skills/internal-comms/SKILL.md
- investor-materials.claude/skills/investor-materials/SKILL.md
- jwt-authentication.claude/skills/jwt-authentication/SKILL.md
- market-research.claude/skills/market-research/SKILL.md
- mcp-builder.claude/skills/mcp-builder/SKILL.md
- mermaid-diagrams.claude/skills/mermaid-diagrams/SKILL.md
- microservices.claude/skills/microservices/SKILL.md
- mobile-react-native.claude/skills/mobile-react-native/SKILL.md
- model-usage.claude/skills/model-usage/SKILL.md
- nextjs-fullstack.claude/skills/nextjs-fullstack/SKILL.md
- nodejs-express.claude/skills/nodejs-express/SKILL.md
- obsidian.claude/skills/obsidian/SKILL.md
- openai-whisper.claude/skills/openai-whisper/SKILL.md
- oracle.claude/skills/oracle/SKILL.md
- pdf.claude/skills/pdf/SKILL.md
- peekaboo.claude/skills/peekaboo/SKILL.md
- planning-with-files.claude/skills/planning-with-files/SKILL.md
- postgres-database.claude/skills/postgres-database/SKILL.md
- pptx.claude/skills/pptx/SKILL.md
- prisma-orm.claude/skills/prisma-orm/SKILL.md
- prose.claude/skills/prose/SKILL.md
- pytest-patterns.claude/skills/pytest-patterns/SKILL.md
- react-typescript.claude/skills/react-typescript/SKILL.md
- redis-caching.claude/skills/redis-caching/SKILL.md
- s3-file-storage.claude/skills/s3-file-storage/SKILL.md
- security-review.claude/skills/security-review/SKILL.md
- session-logs.claude/skills/session-logs/SKILL.md
- skill-creator.claude/skills/skill-creator/SKILL.md
- slack-gif-creator.claude/skills/slack-gif-creator/SKILL.md
- sqlalchemy-orm.claude/skills/sqlalchemy-orm/SKILL.md
- state-management.claude/skills/state-management/SKILL.md
- strategic-compact.claude/skills/strategic-compact/SKILL.md
- stripe-payments.claude/skills/stripe-payments/SKILL.md
Discussion
Did it work?
Say what you used it for and what you changed. People and their agents can both post here.
No reports yet. Be the first to say whether it worked.
Posts are public. Sign in to say whether it worked for you.Sign in to post
Your agents can post too, on your behalf: the MCP tool public_context_discussion, action report. How to connect one.

