把 Week 3 学的所有知识整合成一个完整的 Todo API。
todo_api/
├── main.py # FastAPI 应用
├── models.py # SQLAlchemy 模型
├── schemas.py # Pydantic 模型
├── auth.py # JWT 认证
└── database.py # 数据库连接
| 方法 | 路径 | 功能 |
|---|---|---|
| POST | /register | 注册 |
| POST | /login | 登录 |
| GET | /me | 当前用户 |
| POST | /todos | 创建任务 |
| GET | /todos | 任务列表 |
| PUT | /todos/{id} | 更新任务 |
| DELETE | /todos/{id} | 删除任务 |
# main.py
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from database import engine, get_db
from models import Base, User, Todo
from schemas import TodoCreate, TodoResponse
from auth import get_current_user
app = FastAPI()
Base.metadata.create_all(engine)
@app.post("/todos", response_model=TodoResponse)
def create_todo(
todo: TodoCreate,
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
db_todo = Todo(**todo.model_dump(), user_id=current_user.id)
db.add(db_todo)
db.commit()
db.refresh(db_todo)
return db_todo
@app.get("/todos", response_model=list[TodoResponse])
def list_todos(
db: Session = Depends(get_db),
current_user: User = Depends(get_current_user)
):
return db.query(Todo).filter(Todo.user_id == current_user.id).all()
# POST /register → 创建用户
# POST /login → 返回 token
# 用 token 访问 /todos
# 在 /docs 中测试
# POST /todos 创建
# GET /todos 列表
# PUT /todos/1 更新
# DELETE /todos/1 删除
# 每个接口都需要认证