fastapi
FastAPI Development Guide
Build REST APIs with FastAPI - from Hello World to production.
Quick Start
Minimal App
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def root():
return {"message": "Hello World"}
Run: fastapi dev main.py → Visit http://127.0.0.1:8000/docs
New Project Setup
Copy starter template from assets/starter-project/ or:
pip install "fastapi[standard]"
Core Concepts
| Concept | Description |
|---|---|
| Path params | @app.get("/users/{id}") → def get(id: int) |
| Query params | def list(skip: int = 0, limit: int = 10) |
| Request body | Use Pydantic models: def create(item: Item) |
| Dependencies | def route(db = Depends(get_db)) |
| Response model | @app.post("/", response_model=ItemOut) |
Reference Files
Load these based on the task at hand:
| Topic | File | When to Use |
|---|---|---|
| Basics | basics.md | Path/query params, request bodies, forms, files, status codes |
| Models | models.md | Pydantic schemas, validation, nested models, serialization |
| Dependencies | dependencies.md | DI patterns, class-based deps, global deps, Annotated |
| Auth | auth.md | JWT, OAuth2, API keys, RBAC, CORS, security headers |
| Database | database.md | SQLAlchemy sync/async, Alembic migrations, repository pattern |
| Testing | testing.md | TestClient, pytest, fixtures, mocking, coverage |
| Deployment | deployment.md | Docker, Gunicorn, Nginx, env config, health checks |
| Advanced | advanced.md | Lifespan, middleware, WebSockets, streaming, caching, GraphQL |
Project Structure (Professional)
project/
├── main.py # App entry point
├── app/
│ ├── __init__.py
│ ├── config.py # Settings (pydantic-settings)
│ ├── database.py # DB connection, session
│ ├── models/ # SQLAlchemy models
│ ├── schemas/ # Pydantic schemas
│ ├── api/
│ │ ├── v1/
│ │ │ ├── endpoints/
│ │ │ └── router.py
│ │ └── deps.py # Common dependencies
│ ├── services/ # Business logic
│ └── repositories/ # Data access layer
├── tests/
├── alembic/ # Migrations
├── Dockerfile
└── requirements.txt
Common Patterns
CRUD Endpoint
@router.post("/", response_model=ItemOut, status_code=201)
def create(item: ItemCreate, db: DBDep, user: UserDep):
return service.create_item(db, item, user.id)
@router.get("/{id}", response_model=ItemOut)
def read(id: int, db: DBDep):
item = service.get_item(db, id)
if not item:
raise HTTPException(404, "Not found")
return item
Typed Dependencies (Recommended)
from typing import Annotated
DBDep = Annotated[Session, Depends(get_db)]
UserDep = Annotated[User, Depends(get_current_user)]
SettingsDep = Annotated[Settings, Depends(get_settings)]
Error Handling
from fastapi import HTTPException, status
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Item not found"
)
Workflow
- Define schemas (Pydantic) → Input validation + docs
- Create endpoints → Route handlers with type hints
- Add dependencies → DB, auth, settings injection
- Write tests → TestClient + pytest
- Deploy → Docker + Gunicorn/Uvicorn
Best Practices
- Use
Annotatedfor reusable dependency types - Separate schemas:
Create,Update,Response,InDB - Use
response_modelto control output shape - Keep business logic in services, not routes
- Use async only when needed (DB, external APIs)
- Enable CORS early in development
- Add health check endpoint (
/health) - Use pydantic-settings for configuration
More from salmanferozkhan/cloud-and-fast-api
chainlit
Expert guidance for building conversational AI applications with Chainlit framework in Python. Use when (1) creating chat interfaces for LLM applications, (2) building apps with OpenAI, LangChain, LlamaIndex, or Mistral AI, (3) implementing streaming responses, (4) adding UI elements like images, files, charts, (5) handling user file uploads, (6) implementing authentication (OAuth, password), (7) creating multi-step workflows with visible steps, (8) building RAG applications with document upload, or (9) deploying chat apps to web, Slack, Discord, or Teams.
87sqlmodel
Expert guidance for SQLModel - the Python library combining SQLAlchemy and Pydantic for database models. Use when (1) creating database models that work as both SQLAlchemy ORM and Pydantic schemas, (2) building FastAPI apps with database integration, (3) defining model relationships (one-to-many, many-to-many), (4) performing CRUD operations with type safety, (5) setting up async database sessions, (6) integrating with Alembic migrations, (7) handling model inheritance and mixins, or (8) converting between database models and API schemas.
17microsoft-agent-framework
Expert guidance for building AI agents and multi-agent workflows using Microsoft Agent Framework for .NET. Use when (1) creating AI agents with OpenAI or Azure OpenAI, (2) implementing function tools and structured outputs, (3) building multi-turn conversations, (4) designing graph-based workflows with streaming/checkpointing, (5) implementing middleware pipelines, (6) orchestrating multi-agent systems with fan-out/fan-in patterns, (7) adding human-in-the-loop interactions, (8) integrating OpenTelemetry observability, or (9) exposing agents as MCP tools.
3docx
Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. When Claude needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks
3xlsx
Comprehensive spreadsheet creation, editing, and analysis with support for formulas, formatting, data analysis, and visualization. When Claude needs to work with spreadsheets (.xlsx, .xlsm, .csv, .tsv, etc) for: (1) Creating new spreadsheets with formulas and formatting, (2) Reading or analyzing data, (3) Modify existing spreadsheets while preserving formulas, (4) Data analysis and visualization in spreadsheets, or (5) Recalculating formulas
3skill-validator
|
3