「FastAPI实战」请求与响应核心机制全解析
2025.09.23 11:56浏览量:0简介:本文深度解析FastAPI中请求与响应的核心机制,涵盖路径参数、查询参数、请求体、响应模型等基础用法,通过代码示例与最佳实践帮助开发者快速掌握API开发关键技能。
FastAPI请求与响应基础用法全解析
FastAPI作为现代Python Web框架的代表,以其高性能、易用性和类型提示支持赢得了开发者的青睐。本文将系统讲解FastAPI中请求与响应的核心机制,帮助开发者快速构建健壮的API服务。
一、请求参数处理机制
1.1 路径参数与查询参数
路径参数是URL中定义的变量部分,通过花括号{}
声明。查询参数则出现在URL的?
之后,以键值对形式传递。
from fastapi import FastAPI, Query
app = FastAPI()
# 路径参数示例
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
# 查询参数示例
@app.get("/search/")
async def search_items(
q: str = None, # 可选查询参数
limit: int = Query(10, le=100) # 带验证的查询参数
):
results = {"items": [f"Item {i}" for i in range(limit)]}
if q:
results.update({"q": q})
return results
关键点:
- 路径参数强制要求类型转换,未匹配类型会返回422错误
Query()
函数提供默认值、验证规则等高级功能- 参数默认值使用
None
表示可选
1.2 请求体处理
FastAPI支持JSON、表单数据、文件上传等多种请求体格式。
from fastapi import FastAPI, Form, File, UploadFile
from pydantic import BaseModel
app = FastAPI()
# JSON请求体
class Item(BaseModel):
name: str
description: str | None = None
price: float
tax: float | None = None
@app.post("/items/")
async def create_item(item: Item):
item_dict = item.dict()
if item.tax:
price_with_tax = item.price + item.tax
item_dict.update({"price_with_tax": price_with_tax})
return item_dict
# 表单数据处理
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
# 文件上传
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
最佳实践:
- 使用Pydantic模型验证JSON请求体
- 表单数据使用
Form(...)
强制要求字段 - 文件上传区分
bytes
和UploadFile
两种模式
二、响应处理机制
2.1 基础响应
FastAPI自动处理JSON序列化,支持自定义响应。
from fastapi import FastAPI, Response
from fastapi.responses import HTMLResponse, PlainTextResponse
app = FastAPI()
# 默认JSON响应
@app.get("/json")
async def get_json():
return {"message": "Hello World"}
# 自定义响应
@app.get("/html", response_class=HTMLResponse)
async def get_html():
return "<h1>HTML Response</h1>"
@app.get("/text", response_class=PlainTextResponse)
async def get_text():
return "Plain Text Response"
# 原始响应控制
@app.get("/custom")
async def custom_response():
return Response(
content="Custom Response",
media_type="text/plain",
status_code=200
)
响应类型选择:
- 默认使用JSONResponse
- 文本内容使用PlainTextResponse
- HTML内容使用HTMLResponse
- 需要精细控制时使用Response
2.2 响应模型与状态码
Pydantic模型可作为响应模型使用,自动处理字段过滤和序列化。
from fastapi import FastAPI, status
from pydantic import BaseModel
app = FastAPI()
class OutputItem(BaseModel):
id: int
name: str
@app.post(
"/items/",
response_model=OutputItem,
status_code=status.HTTP_201_CREATED
)
async def create_item(item: Item):
return OutputItem(id=1, name=item.name)
关键特性:
response_model
自动过滤未声明字段- 支持状态码常量如
status.HTTP_201_CREATED
- 模型验证确保响应数据结构正确
三、高级请求处理
3.1 依赖注入系统
FastAPI的依赖注入系统提供强大的请求处理能力。
from fastapi import FastAPI, Depends, Header, HTTPException
app = FastAPI()
async def verify_token(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
@app.get("/secure/", dependencies=[Depends(verify_token)])
async def secure_endpoint():
return {"message": "Authenticated"}
依赖注入优势:
- 集中处理认证、权限等横切关注点
- 支持异步依赖
- 自动错误处理
3.2 路径操作装饰器
FastAPI提供多种HTTP方法装饰器。
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
return {"item_id": item_id, **item.dict()}
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
return {"message": f"Item {item_id} deleted"}
RESTful最佳实践:
- 使用对应HTTP方法的装饰器
- 保持URL结构一致
- 返回适当的HTTP状态码
四、性能优化技巧
4.1 异步处理
FastAPI原生支持异步路径操作。
import asyncio
from fastapi import FastAPI
app = FastAPI()
async def simulate_db_call():
await asyncio.sleep(1)
return {"data": "fetched"}
@app.get("/async/")
async def async_endpoint():
result = await simulate_db_call()
return result
异步优势:
- 提高I/O密集型操作性能
- 避免阻塞事件循环
- 与异步数据库驱动无缝协作
4.2 数据验证优化
利用Pydantic模型进行高效验证。
from pydantic import BaseModel, constr, conint
class StrictItem(BaseModel):
name: constr(min_length=3, max_length=50) # 字符串约束
quantity: conint(ge=1, le=100) # 整数约束
price: float
验证优化点:
- 使用
constr
进行字符串约束 - 使用
conint
/confloat
进行数值范围约束 - 自定义验证逻辑通过模型方法实现
五、完整示例
from fastapi import FastAPI, Depends, HTTPException, status, Query, Form
from pydantic import BaseModel
from typing import Optional
app = FastAPI()
# 模型定义
class Item(BaseModel):
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
class User(BaseModel):
username: str
full_name: Optional[str] = None
# 依赖项
def verify_api_key(api_key: str = Query(...)):
if api_key != "secret-key":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid API Key"
)
# 路径操作
@app.get("/")
async def root():
return {"message": "Welcome to FastAPI"}
@app.get("/items/{item_id}", dependencies=[Depends(verify_api_key)])
async def read_item(
item_id: int,
q: Optional[str] = None,
limit: int = Query(10, le=100)
):
item = {"item_id": item_id}
if q:
item.update({"q": q})
return {"item": item, "limit": limit}
@app.post("/users/", response_model=User, status_code=status.HTTP_201_CREATED)
async def create_user(user: User):
return user
@app.post("/login/")
async def login(username: str = Form(...), password: str = Form(...)):
return {"username": username}
六、总结与最佳实践
- 类型提示优先:充分利用Python类型提示获得自动文档和验证
- 分层验证:路径参数→查询参数→请求体→依赖项的多层验证
- 响应控制:根据场景选择合适的响应类型和状态码
- 异步设计:I/O操作优先使用异步实现
- 安全考虑:敏感操作必须添加认证依赖
FastAPI的请求与响应机制设计精妙,通过合理组合路径参数、查询参数、请求体和响应模型,可以构建出既安全又高效的API服务。建议开发者从简单示例入手,逐步掌握依赖注入、异步处理等高级特性,最终实现企业级API开发。
发表评论
登录后可评论,请前往 登录 或 注册