本技能帮助开发者使用 FastAPI 构建现代化、高性能的 Web API,支持以下场景:
技术基础: FastAPI 构建于 Starlette(Web 框架层)和 Pydantic(数据验证层)之上,性能接近 NodeJS 和 Go。
text
FastAPI 应用架构
├── app/
│ ├── main.py # 应用入口,注册路由和中间件
│ ├── dependencies.py # 公共依赖(认证、数据库会话等)
│ ├── models/ # Pydantic 数据模型
│ │ ├── __init__.py
│ │ └── user.py
│ ├── routers/ # 路由模块(按业务划分)
│ │ ├── __init__.py
│ │ ├── users.py
│ │ └── items.py
│ ├── crud/ # 数据库操作层
│ │ ├── __init__.py
│ │ └── user.py
│ └── core/ # 核心配置
│ ├── config.py
│ └── security.py
概念说明路径操作使用 @app.get/post/put/delete 装饰器定义 API 端点路径参数URL 中的变量,如 /items/{item_id}查询参数URL 查询字符串,如 /items?skip=0&limit=10请求体通过 Pydantic 模型接收 JSON 数据依赖注入通过 Depends() 注入可复用的依赖函数中间件处理每个请求/响应的通用逻辑路由器APIRouter 将路由按模块组织,类似 Flask Blueprint
AI 助手将引导你完成以下步骤:
main.py当你向 AI 描述需求时,AI 会:
python
from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Item(BaseModel):
name: str
price: float
is_offer: bool | None = None
@app.get("/")
async def read_root():
return {"Hello": "World"}
@app.get("/items/{item_id}")
async def read_item(item_id: int, q: str | None = None):
return {"item_id": item_id, "q": q}
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_name": item.name, "item_id": item_id}
bash
# 启动开发服务器
fastapi dev main.py
# 或使用 uvicorn
uvicorn main:app --reload
访问 http://127.0.0.1:8000/docs 查看自动生成的交互式 API 文档。
startup/ shutdown 生命周期钩子JSONResponse、 HTMLResponse、 FileResponse 等MIT License