Install
openclaw skills install fastapi-frameworkFastAPI - 高性能 Python Web API 框架
openclaw skills install fastapi-framework本技能帮助开发者使用 FastAPI 构建现代化、高性能的 Web API,支持以下场景:
技术基础: FastAPI 构建于 Starlette(Web 框架层)和 Pydantic(数据验证层)之上,性能接近 NodeJS 和 Go。
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 会:
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}
# 启动开发服务器
fastapi dev main.py
# 或使用 uvicorn
uvicorn main:app --reload
访问 http://127.0.0.1:8000/docs 查看自动生成的交互式 API 文档。
startup/shutdown 生命周期钩子JSONResponse、HTMLResponse、FileResponse 等MIT License