- Enhance README with project structure, examples, and development guide - Update plan with completion status and verification results - Add memory entries for project context and future reference Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2.9 KiB
2.9 KiB
FastAPI Example
一个最小化的 FastAPI REST API 示例项目,演示健康检查和 CRUD 操作。
项目结构
.
├── app/
│ ├── __init__.py
│ ├── main.py # FastAPI 应用入口和路由
│ └── models.py # Pydantic 数据模型
├── tests/
│ ├── __init__.py
│ └── test_api.py # API 测试用例
├── docs/
│ └── plans/ # 实现计划文档
├── memory/ # 工作记忆
├── requirements.txt # Python 依赖
├── run.sh # 启动脚本
└── README.md
快速开始
环境要求
- Python 3.11+
- pip
安装
# 创建虚拟环境
python3 -m venv .venv
source .venv/bin/activate
# 安装依赖
pip install -r requirements.txt
启动服务
# 方式一:使用启动脚本
./run.sh
# 方式二:直接运行
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
服务启动后访问:
- API: http://localhost:8000
- Swagger UI: http://localhost:8000/docs
- ReDoc: http://localhost:8000/redoc
API 端点
| 方法 | 路径 | 描述 | 请求体 |
|---|---|---|---|
| GET | /health | 健康检查 | - |
| GET | /items | 列出所有项目 | - |
| POST | /items | 创建新项目 | {"name": "string", "description": "string?"} |
| GET | /items/{id} | 获取单个项目 | - |
示例请求
# 健康检查
curl http://localhost:8000/health
# {"status": "ok"}
# 创建项目
curl -X POST http://localhost:8000/items \
-H "Content-Type: application/json" \
-d '{"name": "My Item", "description": "A test item"}'
# {"id": 1, "name": "My Item", "description": "A test item"}
# 列出所有项目
curl http://localhost:8000/items
# [{"id": 1, "name": "My Item", "description": "A test item"}]
# 获取单个项目
curl http://localhost:8000/items/1
# {"id": 1, "name": "My Item", "description": "A test item"}
# 获取不存在的项目
curl http://localhost:8000/items/999
# {"detail": "Item not found"}
测试
source .venv/bin/activate
pytest tests/ -v
测试覆盖:
test_health_check- 健康检查端点test_create_item- 创建项目test_list_items- 列出项目test_get_item- 获取单个项目test_get_item_not_found- 404 错误处理
开发指南
添加新端点
- 在
app/models.py添加数据模型 - 在
app/main.py添加路由函数 - 在
tests/test_api.py编写测试 - 运行测试验证
代码风格
- 使用类型注解
- 遵循 PEP 8
- 函数添加 docstring
技术栈
License
MIT