「FastAPI核心教程」请求与响应基础用法全解析
2025.09.23 11:56浏览量:1简介:本文深入解析FastAPI中请求与响应的核心机制,涵盖路径参数、查询参数、请求体处理及响应模型构建,通过完整代码示例展示如何高效实现RESTful接口。
『FastAPI』快速掌握”请求与响应”的基础用法
FastAPI作为现代Python Web框架的代表,以其高性能和简洁的API设计迅速成为开发者首选。本文将系统讲解FastAPI中请求与响应的核心机制,通过实际代码示例帮助开发者快速掌握基础用法。
一、请求参数处理机制
1.1 路径参数(Path Parameters)
路径参数是URL中动态变化的部分,通过花括号{}
定义。FastAPI会自动将路径参数转换为函数参数,并支持类型注解。
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
关键特性:
- 自动类型转换:当声明
item_id: int
时,FastAPI会自动将字符串路径参数转为整数 - 路径校验:若访问
/items/abc
会返回422错误,提示参数类型不匹配 - 可变路径:支持正则表达式约束,如
@app.get("/items/{item_id:int}")
1.2 查询参数(Query Parameters)
查询参数是URL中?
后的键值对,通过函数参数默认值实现可选参数。
@app.get("/items/")
async def read_items(skip: int = 0, limit: int = 10):
return {"skip": skip, "limit": limit}
进阶用法:
- 必选参数:移除默认值使参数变为必填
- 多值参数:使用
List[str]
接收多个相同参数名 - 参数验证:通过
Query
类实现更复杂的校验
from fastapi import Query
@app.get("/search/")
async def search(q: str = Query(..., min_length=3)):
return {"search_term": q}
1.3 请求体(Request Body)
FastAPI使用Pydantic模型自动处理JSON请求体,提供强大的数据验证能力。
from pydantic import BaseModel
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
数据验证机制:
- 自动类型检查:若发送
{"price": "ten"}
会返回422错误 - 字段约束:通过
Field
实现更复杂的验证规则 - 嵌套模型:支持复杂的数据结构定义
二、响应处理技术
2.1 自动JSON响应
FastAPI默认将函数返回值序列化为JSON,支持多种返回类型:
- 字典:自动转为JSON对象
- Pydantic模型:提供结构化响应
- 数据库模型:需手动转为字典或使用ORM的
.dict()
方法
2.2 响应模型(Response Model)
通过response_model
参数控制响应结构,实现字段过滤和序列化控制。
@app.get("/items/{item_id}", response_model=Item)
async def read_item(item_id: int):
# 实际可能从数据库获取
return {"name": "Foo", "description": "Bar", "price": 10.5}
优势:
- 字段过滤:只返回模型定义的字段
- 序列化控制:自动处理日期等特殊类型的转换
- 文档集成:自动在OpenAPI文档中显示响应模型
2.3 自定义响应
需要直接控制响应时,可使用Response
对象:
from fastapi import Response
@app.get("/download/")
async def download_file():
file_content = b"Binary file content"
headers = {"Content-Disposition": "attachment; filename=download.bin"}
return Response(content=file_content, headers=headers)
常见场景:
- 文件下载:设置
Content-Disposition
头 - 自定义状态码:
return JSONResponse(status_code=404, content={"message": "Not found"})
- 流式响应:处理大文件或实时数据
三、路径操作装饰器
FastAPI提供多种HTTP方法装饰器,每个都支持特定的参数:
装饰器 | 对应HTTP方法 | 典型参数 |
---|---|---|
@app.get |
GET | path, query, header |
@app.post |
POST | path, query, body |
@app.put |
PUT | path, query, body |
@app.delete |
DELETE | path, query |
组合示例:
@app.put("/items/{item_id}")
async def update_item(
item_id: int,
item: Item,
q: str | None = None,
user_agent: str = Header(...)
):
results = {"item_id": item_id, **item.dict()}
if q:
results.update({"q": q})
results.update({"user_agent": user_agent})
return results
四、最佳实践建议
参数顺序规范:
- 路径参数 > 查询参数 > 请求体
- 复杂参数使用
Query
、Path
等类显式声明
响应模型设计:
- 为每个端点定义专用的响应模型
- 使用
Optional
字段处理可选响应数据 - 考虑分页响应时使用嵌套模型
性能优化:
- 对高频端点使用
cached_property
缓存计算 - 考虑使用
JSONResponse
替代自动序列化处理特殊场景 - 对大响应使用流式传输
- 对高频端点使用
错误处理:
- 使用
HTTPException
统一处理业务错误 - 为常见错误场景定义专用异常类
- 实现全局异常处理器
- 使用
五、完整示例
from fastapi import FastAPI, HTTPException, Path, Query
from pydantic import BaseModel, Field
from typing import Optional
app = FastAPI()
class Product(BaseModel):
name: str = Field(..., min_length=3)
price: float = Field(..., gt=0)
discount: Optional[float] = Field(0, ge=0, le=1)
@app.get("/products/{product_id}")
async def get_product(
product_id: int = Path(..., ge=1),
details: bool = Query(False)
):
if product_id > 1000:
raise HTTPException(status_code=404, detail="Product not found")
product = {
"id": product_id,
"name": "Sample Product",
"price": 19.99,
"discount": 0.1 if details else None
}
return product if details else {"id": product_id, "name": product["name"]}
@app.post("/products/")
async def create_product(product: Product):
final_price = product.price * (1 - product.discount)
return {
**product.dict(),
"final_price": round(final_price, 2),
"status": "created"
}
六、总结与展望
FastAPI的请求与响应处理机制通过类型注解和Pydantic模型实现了开发效率与运行性能的完美平衡。开发者应重点掌握:
- 参数声明方式(路径/查询/请求体)
- 响应模型的设计原则
- 错误处理的最佳实践
未来可深入探索:
- WebSocket的请求响应模式
- 依赖注入系统的高级用法
- 中间件中的请求响应拦截
- 测试客户端的模拟请求技巧
通过系统掌握这些基础用法,开发者能够快速构建出符合RESTful规范的高性能API服务,为后续的微服务架构和复杂业务实现打下坚实基础。
发表评论
登录后可评论,请前往 登录 或 注册