FastAPI + Claude Code 是 Python 后端开发的黄金组合。Claude Code 熟悉 FastAPI 的设计模式,能快速生成类型安全、高性能的 API 代码。本文展示从零开始的完整流程。
项目初始化
bash
mkdir my-api && cd my-api
python -m venv .venv && source .venv/bin/activate
pip install fastapi uvicorn sqlalchemy aiosqlite pydantic-settings
claude工作流 1:设计项目结构
Design a FastAPI project structure for a task management API.
Features: users, tasks (with tags), authentication (JWT)
Create the directory structure and empty files:
my-api/
app/
main.py, config.py, database.py
models/ (SQLAlchemy models)
schemas/ (Pydantic schemas)
routers/ (API endpoints)
services/ (business logic)
dependencies.py (FastAPI Depends)
tests/
requirements.txt
.env.example
Dockerfile
工作流 2:Pydantic 模型 + SQLAlchemy ORM
Create database models and Pydantic schemas for a Task entity:
Fields: id, title, description, status (todo/in_progress/done),
priority (low/medium/high), due_date, tags, user_id, created_at
1. SQLAlchemy 2.0 async model: app/models/task.py
2. Pydantic schemas: app/schemas/task.py
- TaskBase, TaskCreate, TaskUpdate, TaskResponse
- TaskResponse should include nested user info (name only)
3. Many-to-many with Tag model
4. Use SQLAlchemy 2.0 mapped_column() syntax
工作流 3:CRUD 路由
Create CRUD API routes for Tasks: app/routers/tasks.py
Endpoints:
GET /tasks - list (with filters: status, priority, tag; pagination)
POST /tasks - create
GET /tasks/{id} - get by id
PUT /tasks/{id} - update (partial update supported)
DELETE /tasks/{id} - soft delete
POST /tasks/{id}/tags - add tags
Requirements:
- Require authentication (Depends(get_current_user))
- Users can only see/edit their own tasks
- Proper HTTP status codes
- Async SQLAlchemy queries
- Pagination with cursor-based (not offset)
工作流 4:JWT 认证
Implement JWT authentication:
Endpoints:
POST /auth/register - create user
POST /auth/login - return access_token + refresh_token
POST /auth/refresh - refresh access token
POST /auth/logout - invalidate refresh token
JWT config:
- Access token: 15 minutes
- Refresh token: 7 days (stored in DB)
- Algorithm: HS256
- Password: bcrypt hash
Create get_current_user dependency that validates the Bearer token.
Use python-jose and passlib[bcrypt].
工作流 5:后台任务
Add background tasks for:
1. Send email notification when task is assigned to a user
2. Daily digest email of overdue tasks (use APScheduler)
3. Cleanup old soft-deleted tasks (older than 30 days)
Use FastAPI BackgroundTasks for #1.
Use APScheduler for #2 and #3 (runs on startup).
Mock the email sender (just print to log for now).
工作流 6:测试
Write pytest tests for the task CRUD endpoints.
Setup:
- Use pytest-asyncio for async tests
- Use httpx.AsyncClient with ASGITransport
- In-memory SQLite test database
- Fixtures: test user, auth headers, sample tasks
Test cases:
- Create task (valid + invalid data)
- List with filters (by status, priority, tag)
- Update task (partial update)
- Cannot access other user's tasks (403)
- Pagination works correctly
工作流 7:Docker 部署
Create production-ready Docker setup:
1. Dockerfile:
- Multi-stage build
- Non-root user
- .dockerignore
- Health check
2. docker-compose.yml:
- api service (FastAPI)
- db service (PostgreSQL 15)
- redis service (for caching/sessions)
- Volumes for data persistence
- Environment from .env file
3. Add alembic for database migrations
4. Startup script that runs migrations before starting
CLAUDE.md 推荐配置(FastAPI 项目)
markdown
## Tech Stack
- FastAPI + Uvicorn
- SQLAlchemy 2.0 async
- Pydantic v2
- Alembic 数据库迁移
## 代码规范
- 所有 DB 操作必须 async
- Pydantic schema 和 SQLAlchemy model 严格分离
- 业务逻辑放 services/,路由只做参数解析
- 错误使用 HTTPException,不用裸 Exception
## 命令
- 启动:uvicorn app.main:app --reload
- 测试:pytest tests/ -v
- 迁移:alembic upgrade head
- 文档:http://localhost:8000/docs来源:Anthropic 官方文档 + FastAPI 官方文档