在当今快速发展的互联网世界,开发者面临着快速交付高性能应用的挑战。在这个背景下,FastAPI作为一种现代化的Python Web框架,便以其简洁性、性能和易用性脱颖而出。假如你正在寻找一种能够快速构建API的解决方案,FastAPI无疑是理想之选。接下来,让我们深入探索FastAPI的非凡之处,揭示它为何能成为开发者的新宠。
FastAPI 是一个用于构建 API 的现代、快速(高性能)的 web 框架,使用 Python 3.6+ 并基于标准的 Python 类型提示。
本文将详细介绍如何从零开始创建你的第一个 FastAPI 应用,涵盖安装、基本路由、请求处理、数据验证等核心概念。
特性介绍
经过前面的介绍,我们已经知道FastApi拥有以下特性:
快速:可与 NodeJS 和 Go 比肩的极高性能(归功于 Starlette 和 Pydantic)。最快的 Python web 框架之一。 高效编码:提高功能开发速度约 200% 至 300%。* 更少 bug:减少约 40% 的人为(开发者)导致错误。* 智能:极佳的编辑器支持。处处皆可自动补全,减少调试时间。 简单:设计的易于使用和学习,阅读文档的时间更短。 简短:使代码重复最小化。通过不同的参数声明实现丰富功能。bug 更少。 健壮:生产可用级别的代码。还有自动生成的交互式文档。 标准化:基于(并完全兼容)API 的相关开放标准:OpenAPI (以前被称为 Swagger) 和 JSON Schema。
接着前面搭建的环境,以及第一个代码示例,接下来继续开始扩展这个的服务应用,来一一展现这些功能特性
第一个APP介绍
创建一个名为 main.py 的文件,并添加以下代码:
from fastapi import FastAPI # 这行代码从fastapi 模块中导入了 FastAPI 类。FastAPI 类是 FastAPI 框架的核心,用于创建 FastAPI 应用程序实例。
app = FastAPI() # 这行代码创建了一个 FastAPI 应用实例。与 Flask 不同,FastAPI 不需要传递 __name__ 参数,因为它默认使用当前模块。
@app.get("/") # 这是一个装饰器,用于告诉 FastAPI 哪个 URL 应该触发下面的函数,并且指定了 HTTP 方法为 GET。在这个例子中,它指定了根 URL(即网站的主页)。
def read_root(): # 这是定义了一个名为 read_root 的函数,它将被调用当用户使用 GET 方法访问根 URL 时。
return {"message": "Hello, World!"} # 这行代码是 read_root 函数的返回值。当用户使用 GET 方法访问根 URL 时,这个 JSON 对象将被发送回用户的浏览器或 API 客户端。
这个简单的应用程序:
- 导入 FastAPI 类
- 创建一个 FastAPI 实例(通常命名为
app) - 定义一个路径操作装饰器
@app.get("/") - 定义一个路径操作函数
read_root() - 返回一个字典,FastAPI 会自动将其转换为 JSON
3.1 运行应用程序
在命令行中使用 Uvicorn 运行你的应用程序,运行以下命令以启动应用:
uvicorn main:app --reload
参数说明:
main: 模块名称(main.py)app: FastAPI 实例名称(app = FastAPI())--reload: 开发时启用自动重载(生产环境不要使用)
3.2 测试应用程序
打开浏览器访问 http://127.0.0.1:8000,你应该会看到:
{"message": "Hello, World!"}
3.3 交互式 API 文档
FastAPI 自动生成交互式 API 文档:
- Swagger UI:
http://127.0.0.1:8000/docs - ReDoc:
http://127.0.0.1:8000/redoc
4. 添加更多路由
让我们扩展应用程序,以下的 FastAPI 应用,使用了多个路由操作,添加更多端点:
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"message": "Hello, World!"}
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
@app.get("/users/{username}")
def read_user(username: str):
return {"username": username}
这些新路由展示了:
- 路径参数(
item_id和username) - 类型提示(
item_id: int和username: str)
5. 路径参数和查询参数
5.1 路径参数
路径参数是 URL 的一部分,如 /items/42 中的 42:
@app.get("/items/{item_id}")
def read_item(item_id: int):
return {"item_id": item_id}
FastAPI 会自动将路径参数转换为指定的类型(这里是 int),如果类型不匹配会返回错误。
5.2 查询参数
查询参数是 URL 中 ? 后面的键值对,如 http://127.0.0.1:8000/items/?skip=0&limit=10:
from typing import Optional
@app.get("/items/")
def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
这里 skip 和 limit 是可选的查询参数,带有默认值。
6. 请求体和 Pydantic 模型
FastAPI 使用 Pydantic 模型来处理请求体和数据验证。
6.1 定义 Pydantic 模型
from pydantic import BaseModel
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
6.2 使用模型作为请求体
@app.post("/items/")
def create_item(item: Item):
return item
FastAPI 将:
- 读取请求体作为 JSON
- 转换为相应的类型
- 验证数据
- 提供自动文档
7. 响应模型
你可以指定响应模型以确保返回的数据符合特定格式:
@app.post("/items/", response_model=Item)
def create_item(item: Item):
return item
响应模型还可以用于过滤输出字段:
class UserIn(BaseModel):
username: str
password: str
email: str
class UserOut(BaseModel):
username: str
email: str
@app.post("/user/", response_model=UserOut)
def create_user(user: UserIn):
return user
8. 错误处理
FastAPI 提供了内置的错误处理:
from fastapi import HTTPException
@app.get("/items/{item_id}")
def read_item(item_id: int):
if item_id not in items_db:
raise HTTPException(status_code=404, detail="Item not found")
return {"item": items_db[item_id]}
你也可以创建自定义异常处理器。
9. 表单数据和文件上传
处理表单数据:
from fastapi import Form
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
文件上传:
from fastapi import UploadFile, File
@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
7.3 性能优化建议
-
启用 JIT 编译:
from fastapi import FastAPI
from fastapi.middleware.gzip import GZipMiddleware
app = FastAPI()
app.add_middleware(GZipMiddleware, minimum_size=1000)
使用 ORJSONResponse 提高 JSON 序列化速度:
pip install orjson
from fastapi import FastAPI
from fastapi.responses import ORJSONResponse
app = FastAPI(default_response_class=ORJSONResponse)
启用 HTTP/2:
uvicorn main:app --http h11 --http2
8. 测试与调试
8.1 单元测试配置
使用 pytest 进行测试:
-
创建
app/tests/conftest.py:
import pytest
from fastapi.testclient import TestClient
from app.main import app
@pytest.fixture
def client():
with TestClient(app) as client:
yield client
示例测试 (app/tests/test_main.py):
def test_read_main(client):
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello World"}
8.2 异步测试
对于异步代码,使用 pytest-asyncio:
-
安装:
pip install pytest-asyncio
异步测试示例:
import pytest
from httpx import AsyncClient
from app.main import app
@pytest.mark.asyncio
async def test_read_item():
async with AsyncClient(app=app, base_url="http://test") as ac:
response = await ac.get("/items/42")
assert response.status_code == 200
assert response.json() == {"item_id": 42}
8.3 调试技巧
-
使用 pdb:
import pdb; pdb.set_trace()
使用 FastAPI 的调试中间件:
from fastapi import FastAPI
from fastapi.middleware import Middleware
from fastapi.middleware.httpsredirect import HTTPSRedirectMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
app = FastAPI()
app.add_middleware(
TrustedHostMiddleware,
allowed_hosts=["example.com", "*.example.com"]
)
日志配置:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
10. 依赖注入
FastAPI 的依赖注入系统非常强大:
from fastapi import Depends
def common_parameters(q: Optional[str] = None, skip: int = 0, limit: int = 100):
return {"q": q, "skip": skip, "limit": limit}
@app.get("/items/")
async def read_items(commons: dict = Depends(common_parameters)):
return commons
11. 数据库集成
与数据库集成(以 SQLAlchemy 为例):
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db"
engine = create_engine(
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
# 定义模型
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String, unique=True, index=True)
hashed_password = Column(String)
# 创建表
Base.metadata.create_all(bind=engine)
# 依赖项
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# 在路由中使用
@app.post("/users/")
def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = User(email=user.email, hashed_password=user.password)
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
12. 认证和授权
实现基本的 JWT 认证:
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
def verify_password(plain_password, hashed_password):
return pwd_context.verify(plain_password, hashed_password)
def get_password_hash(password):
return pwd_context.hash(password)
def create_access_token(data: dict):
to_encode = data.copy()
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt
@app.post("/token")
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
user = authenticate_user(form_data.username, form_data.password)
if not user:
raise HTTPException(
status_code=400, detail="Incorrect username or password")
access_token = create_access_token(
data={"sub": user.username})
return {"access_token": access_token, "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(token: str = Depends(oauth2_scheme)):
credentials_exception = HTTPException(
status_code=401,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except JWTError:
raise credentials_exception
user = get_user(username)
if user is None:
raise credentials_exception
return user
13. 中间件
添加中间件:
from fastapi import Request
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
14. CORS (跨域资源共享)
启用 CORS:
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
15. 测试 FastAPI 应用
使用 TestClient 编写测试:
from fastapi.testclient import TestClient
client = TestClient(app)
def test_read_root():
response = client.get("/")
assert response.status_code == 200
assert response.json() == {"message": "Hello, World!"}
def test_read_item():
response = client.get("/items/42")
assert response.status_code == 200
assert response.json() == {"item_id": 42}
16. 部署 FastAPI 应用
16.1 生产服务器
在生产环境中,使用:
- Gunicorn + Uvicorn (推荐)
- Hypercorn
- Daphne
使用 Gunicorn 运行多个 Uvicorn 工作进程:
gunicorn -w 4 -k uvicorn.workers.UvicornWorker main:app
16.2 Docker 部署
创建 Dockerfile:
FROM python:3.9
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "80"]
构建并运行:
docker build -t myfastapi .
docker run -d -p 80:80 myfastapi
18. 最佳实践
- 使用类型提示:充分利用 Python 的类型提示功能
- 模块化路由:使用
APIRouter组织大型应用 - 环境变量:使用
pydantic.BaseSettings管理配置 - 异步支持:尽可能使用
async/await - 错误处理:提供有意义的错误消息和状态码
- 文档:利用 FastAPI 的自动文档功能并补充描述
- 测试:编写全面的测试覆盖
- 安全性:实施适当的安全措施(HTTPS、CORS、认证等)
总结
通过本文,你已经学会了如何:
- 安装和设置 FastAPI
- 创建基本路由和路径操作
- 处理路径参数和查询参数
- 使用 Pydantic 模型验证请求和响应数据
- 实现基本的错误处理
- 处理表单和文件上传
- 使用依赖注入系统
- 集成数据库
- 实现认证和授权
- 添加中间件
- 启用 CORS
- 测试你的应用
- 部署 FastAPI 应用
FastAPI 是一个功能强大且易于使用的框架,它结合了现代 Python 特性,提供了极高的开发效率和运行时性能。随着你对框架的深入了解,你将能够构建更加复杂和强大的 Web API。