FastAPI 安装配置
本章介绍如何安装 FastAPI 并配置开发环境。
系统要求
- Python 3.10 或更高版本(FastAPI 最新版本要求)
- pip 包管理器
FastAPI 从 0.125.0 版本开始不再支持 Python 3.8,推荐使用 Python 3.10+ 以获得最佳的类型提示支持和性能。
安装 FastAPI
标准安装(推荐)
# 安装 FastAPI 及所有标准依赖
pip install "fastapi[standard]"
注意:确保将 "fastapi[standard]" 放在引号中,以确保在所有终端中正常工作。
这会安装以下组件:
- FastAPI:核心框架
- Uvicorn:ASGI 服务器(包含高性能依赖如 uvloop)
- Pydantic:数据验证
- email-validator:邮箱验证
- httpx:用于 TestClient
- jinja2:模板引擎支持
- python-multipart:表单解析支持
- fastapi-cloud-cli:部署到 FastAPI Cloud 的工具
标准安装(不含 Cloud CLI)
如果不需要 FastAPI Cloud 部署功能:
pip install "fastapi[standard-no-fastapi-cloud-cli]"
这会安装标准依赖,但不包含 fastapi-cloud-cli。
最小安装
如果只需要核心功能:
pip install fastapi uvicorn
使用虚拟环境(推荐)
# 创建虚拟环境
python -m venv .venv
# 激活虚拟环境
# Windows
.venv\Scripts\activate
# macOS/Linux
source .venv/bin/activate
# 安装 FastAPI
pip install "fastapi[standard]"
使用 Poetry
# 创建新项目
poetry new my-api
cd my-api
# 添加依赖
poetry add "fastapi[standard]"
# 激活环境
poetry shell
验证安装
# test_install.py
import fastapi
import uvicorn
import pydantic
print(f"FastAPI 版本: {fastapi.__version__}")
print(f"Uvicorn 版本: {uvicorn.__version__}")
print(f"Pydantic 版本: {pydantic.__version__}")
运行测试:
python test_install.py
FastAPI 最新特性
FastAPI 持续更新,以下是近期版本的重要特性:
版本 0.135.0+ - Server-Sent Events 支持
内置 SSE 支持,简化实时推送实现:
from fastapi import FastAPI
from fastapi.sse import EventSourceResponse
app = FastAPI()
@app.get("/stream", response_class=EventSourceResponse)
async def stream_data():
for i in range(10):
yield {"count": i}
版本 0.132.0+ - Strict Content-Type 检查
默认启用 JSON 请求的 Content-Type 验证,提升安全性:
# 如需禁用(兼容旧客户端)
@app.post("/items/", strict_content_type=False)
async def create_item(item: Item):
return item
版本 0.130.0+ - JSON 响应性能提升
使用 Pydantic 在 Rust 中序列化 JSON,性能提升 2 倍以上:
# 自动优化,无需额外配置
@app.get("/items/", response_model=list[Item])
async def get_items():
return items
版本 0.126.0+ - 仅支持 Pydantic v2
不再支持 Pydantic v1,最低要求 Pydantic 2.7.0+,带来更好的性能和类型支持。
FastAPI Cloud 部署(可选)
FastAPI Cloud 是由 FastAPI 作者团队构建的云服务平台,提供一键部署功能:
# 部署到 FastAPI Cloud
fastapi deploy
输出示例:
Deploying to FastAPI Cloud...
✅ Deployment successful!
🚀 Your app is ready at https://myapp.fastapicloud.dev
注意:FastAPI Cloud 是可选的付费服务,FastAPI 本身是开源的,可以部署到任何云服务商。
运行第一个应用
创建 main.py:
from fastapi import FastAPI
# 创建 FastAPI 实例
app = FastAPI()
# 定义路由
@app.get("/")
async def root():
return {"message": "Hello, FastAPI!"}
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
使用 FastAPI CLI(推荐)
# 开发模式(自动重载)
fastapi dev main.py
# 生产模式
fastapi run main.py
输出:
╭────────── FastAPI CLI - Development mode ───────────╮
│ │
│ Serving at: http://127.0.0.1:8000 │
│ │
│ API docs: http://127.0.0.1:8000/docs │
│ │
╰─────────────────────────────────────────────────────╯
使用 Uvicorn 直接运行
# 开发模式
uvicorn main:app --reload
# 指定端口和主机
uvicorn main:app --host 0.0.0.0 --port 8080
# 生产模式(多 worker)
uvicorn main:app --workers 4
项目结构
小型项目结构
my_api/
├── main.py # 主应用文件
├── requirements.txt # 依赖列表
└── .env # 环境变量(可选)
中型项目结构
my_api/
├── main.py # 应用入口
├── routers/ # 路由模块
│ ├── __init__.py
│ ├── users.py
│ └── items.py
├── models/ # 数据模型
│ ├── __init__.py
│ └── schemas.py
├── services/ # 业务逻辑
│ └── __init__.py
├── config.py # 配置管理
├── requirements.txt
└── .env
大型项目结构
my_api/
├── app/
│ ├── __init__.py
│ ├── main.py # 应用入口
│ ├── core/ # 核心配置
│ │ ├── __init__.py
│ │ ├── config.py # 配置
│ │ └── security.py # 安全相关
│ ├── api/ # API 路由
│ │ ├── __init__.py
│ │ ├── deps.py # 依赖
│ │ └── v1/ # API 版本
│ │ ├── __init__.py
│ │ └── endpoints/
│ │ ├── users.py
│ │ └── items.py
│ ├── models/ # 数据库模型
│ │ └── __init__.py
│ ├── schemas/ # Pydantic 模型
│ │ └── __init__.py
│ ├── services/ # 业务逻辑
│ │ └── __init__.py
│ └── utils/ # 工具函数
│ └── __init__.py
├── tests/ # 测试
│ └── test_main.py
├── alembic/ # 数据库迁移
├── pyproject.toml # 项目配置
└── README.md
配置管理
使用环境变量
# config.py
import os
from pydantic_settings import BaseSettings
class Settings(BaseSettings):
"""应用配置"""
app_name: str = "FastAPI Application"
debug: bool = False
database_url: str = "sqlite:///./app.db"
class Config:
env_file = ".env"
settings = Settings()
# main.py
from fastapi import FastAPI
from config import settings
app = FastAPI(
title=settings.app_name,
debug=settings.debug
)
@app.get("/info")
async def info():
return {"app_name": settings.app_name}
.env 文件
# .env
APP_NAME=我的API
DEBUG=true
DATABASE_URL=postgresql://user:pass@localhost/db
开发工具配置
VS Code 配置
.vscode/launch.json:
{
"version": "0.2.0",
"configurations": [
{
"name": "FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"args": [
"main:app",
"--reload"
],
"jinja": true
}
]
}
requirements.txt
fastapi[standard]>=0.109.0
python-dotenv>=1.0.0
pydantic-settings>=2.0.0
# 开发依赖
pytest>=7.0.0
httpx>=0.25.0
black>=23.0.0
ruff>=0.1.0
mypy>=1.0.0
pyproject.toml(Poetry)
[tool.poetry]
name = "my-api"
version = "0.1.0"
description = "My FastAPI Application"
[tool.poetry.dependencies]
python = "^3.10"
fastapi = {extras = ["standard"], version = "^0.109.0"}
pydantic-settings = "^2.0.0"
[tool.poetry.group.dev.dependencies]
pytest = "^7.0.0"
httpx = "^0.25.0"
black = "^23.0.0"
ruff = "^0.1.0"
[build-system]
requires = ["poetry-core"]
build-backend = "poetry.core.masonry.api"
常见问题
Strict Content-Type 错误
从 FastAPI 0.132.0 开始,默认要求 JSON 请求必须包含正确的 Content-Type 头:
# 正确请求
curl -X POST "http://localhost:8000/items/" \
-H "Content-Type: application/json" \
-d '{"name": "test"}'
# 错误请求(会返回 415 错误)
curl -X POST "http://localhost:8000/items/" \
-d '{"name": "test"}'
如需兼容旧客户端,可禁用此检查:
@app.post("/items/", strict_content_type=False)
async def create_item(item: Item):
return item
端口被占用
# 查找占用端口的进程
# Windows
netstat -ano | findstr :8000
taskkill /PID <pid> /F
# macOS/Linux
lsof -i :8000
kill -9 <pid>
# 或使用其他端口
uvicorn main:app --port 8001
模块找不到
确保在项目根目录运行,或将项目添加到 Python 路径:
import sys
from pathlib import Path
sys.path.append(str(Path(__file__).parent))
热重载不工作
检查文件是否在监控目录下:
uvicorn main:app --reload --reload-dir ./app
pyproject.toml 配置入口点
FastAPI CLI 支持从 pyproject.toml 读取配置,可以定义应用入口点:
[project]
name = "my-api"
version = "0.1.0"
[project.scripts]
# 定义 fastapi run 的默认入口
my-api = "my_api.main:app"
配置后可以直接运行:
fastapi run
# 等同于 fastapi run my_api/main.py
VS Code 扩展
FastAPI 提供了官方的 VS Code 扩展,包含以下功能:
- 路径操作浏览器:在侧边栏查看所有 API 路由
- 路径操作搜索:快速搜索和跳转到路由定义
- CodeLens 导航:从测试跳转到定义
- FastAPI Cloud 部署:直接从编辑器部署和查看日志
在 VS Code 扩展市场搜索 "FastAPI" 即可安装。
小结
本章我们学习了:
- 安装方式:标准安装包含所有常用依赖
- 运行方式:FastAPI CLI 和 Uvicorn 两种方式
- 项目结构:从小型到大型项目的组织方式
- 配置管理:使用 pydantic-settings 和环境变量
- 开发工具:VS Code 配置和项目配置文件
练习
- 创建一个 FastAPI 项目并成功运行
- 使用环境变量配置应用名称
- 访问自动生成的 API 文档页面(
/docs和/redoc) - 组织一个小型项目的文件结构