主题
FastAPI 是现代、高性能的 Python Web 框架,自动生成 API 文档,开发体验极佳。
📋 前置要求
Python 3.11+ 已安装
pip 已安装
已下载生成的项目代码
📁 项目结构
backend
main.py // 入口文件
requirements.txt // 依赖列表
app
__init__.py
api // API 路由
__init__.py
routes
deps.py // 依赖注入
core // 核心配置
config.py
security.py
models // 数据模型
schemas // Pydantic 模型
crud // CRUD 操作
db // 数据库配置
alembic // 数据库迁移(可选)
🚀 运行步骤
第 1 步:进入项目目录
bash
$
cd backend
第 2 步:创建虚拟环境
bash
$
python3 -m venv venv
激活虚拟环境:
bash
$
source venv/bin/activate
第 3 步:安装依赖
bash
$
pip install -r requirements.txt
使用国内镜像加速:
bash
$
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
第 4 步:配置环境变量
复制环境变量文件:
bash
$
cp .env.example .env
编辑 .env 文件:
| 变量名 | 说明 | 必填 |
|---|---|---|
| DATABASE_URL | 数据库连接字符串 | 是 |
| SECRET_KEY | 应用密钥 | 是 |
| DEBUG 默认值: True | 调试模式 | 否 |
| CORS_ORIGINS 默认值: http://localhost:5173 | 允许的跨域来源 | 否 |
第 5 步:数据库迁移(如果使用 Alembic)
bash
$
alembic upgrade head
第 6 步:启动开发服务器
bash
$
uvicorn main:app --reload
或者指定端口:
bash
$
uvicorn main:app --reload --host 0.0.0.0 --port 8000
--reload 参数
`--reload` 参数启用热重载,代码修改后会自动重启服务器,开发时非常方便。
第 7 步:验证运行
服务启动后,FastAPI 会自动生成交互式 API 文档:
- API 根路径:http://localhost:8000
- Swagger UI:http://localhost:8000/docs ⭐
- ReDoc:http://localhost:8000/redoc
启动成功
如果看到 `Uvicorn running on http://127.0.0.1:8000` 的消息,说明服务启动成功!
访问 /docs 可以看到自动生成的 API 文档,这是 FastAPI 的特色功能。
🔧 常用命令
| 命令 | 说明 |
|---|---|
uvicorn main:app --reload | 开发模式启动 |
uvicorn main:app --workers 4 | 生产模式(多进程) |
alembic revision --autogenerate -m "msg" | 创建迁移 |
alembic upgrade head | 执行迁移 |
pytest | 运行测试 |
🎯 FastAPI 特色功能
自动 API 文档
FastAPI 会自动根据你的代码生成:
- Swagger UI (
/docs) - 可交互的 API 测试界面 - ReDoc (
/redoc) - 美观的 API 文档
类型提示验证
FastAPI 使用 Python 类型提示进行自动验证:
python
from pydantic import BaseModel
class User(BaseModel):
name: str
email: str
age: int
@app.post("/users")
def create_user(user: User):
# user 已经过验证
return user❓ 常见问题
uvicorn 命令找不到
确保虚拟环境已激活,或者使用:
bash
$
python -m uvicorn main:app --reload
导入错误
检查 Python 路径:
bash
$
export PYTHONPATH=$PWD
数据库连接失败
- 确保数据库服务已启动
- 检查
DATABASE_URL格式:- SQLite:
sqlite:///./app.db - PostgreSQL:
postgresql://user:pass@localhost/dbname - MySQL:
mysql://user:pass@localhost/dbname
- SQLite:
CORS 错误
确保在 .env 中配置了前端地址:
CORS_ORIGINS=http://localhost:5173,http://localhost:3000