FastAPI请求与响应实战指南:从基础到进阶
2025.09.18 18:04浏览量:0简介:本文系统讲解FastAPI中请求与响应的核心机制,涵盖路径参数、查询参数、请求体解析、响应模型等关键技术点,通过完整代码示例演示如何构建高效API接口。
FastAPI请求与响应实战指南:从基础到进阶
FastAPI作为现代Python Web框架的佼佼者,以其高性能、自动文档生成和类型安全特性深受开发者青睐。本文将深入探讨FastAPI中请求与响应的核心机制,通过实际代码示例帮助开发者快速掌握基础用法。
一、请求参数处理机制
1.1 路径参数解析
路径参数是RESTful API设计的基础元素,FastAPI通过类型注解自动完成参数解析:
from fastapi import FastAPI
app = FastAPI()
@app.get("/items/{item_id}")
async def read_item(item_id: int):
return {"item_id": item_id}
关键特性:
- 类型转换自动完成(字符串自动转为int)
- 路径参数必须与端点路径中的占位符同名
- 支持复杂类型(如UUID、自定义类)
1.2 查询参数处理
查询参数通过函数参数声明实现,支持可选参数和默认值:
from fastapi import Query
@app.get("/items/")
async def read_items(
skip: int = 0,
limit: int = Query(10, le=100),
sort: str = None
):
results = {"items": [f"Item {i}" for i in range(skip, skip+limit)]}
if sort:
results.update({"sort": sort})
return results
高级用法:
Query()
提供更精细的控制(最小值、最大值、正则验证)- 必选参数需设置
default=...
或移除默认值 - 支持列表参数:
tags: List[str] = Query([])
1.3 请求体解析
FastAPI支持多种请求体格式,最常用的是Pydantic模型:
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
数据验证机制:
- 自动类型转换和验证
- 字段可选性控制(
= None
) - 嵌套模型支持
- 自动生成JSON Schema
二、响应控制技术
2.1 响应模型定制
通过response_model
参数控制返回数据结构:
from fastapi import Response
@app.get("/items/{item_id}/", response_model=Item)
async def read_item(item_id: int):
# 实际业务逻辑可能返回更复杂的数据
return {"name": "Foo", "description": "Bar", "price": 10.5, "tax": 0.5}
优势:
- 数据序列化控制
- 字段过滤(排除模型中未声明的字段)
- 类型安全保障
- 自动文档集成
2.2 自定义响应
需要完全控制响应时可使用Response
对象:
from fastapi.responses import JSONResponse, HTMLResponse
@app.get("/custom-response/")
async def custom_response():
content = {"message": "Custom JSON response"}
return JSONResponse(content=content, status_code=200)
@app.get("/html/")
async def get_html():
return HTMLResponse(content="<h1>Hello World</h1>")
常见响应类型:
JSONResponse
:自定义JSON响应HTMLResponse
:返回HTML内容StreamingResponse
:流式响应FileResponse
:文件下载
2.3 状态码管理
FastAPI支持多种状态码设置方式:
from fastapi import status
@app.post("/items/", status_code=status.HTTP_201_CREATED)
async def create_item(item: Item):
return item
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
return Response(status_code=status.HTTP_204_NO_CONTENT)
最佳实践:
- 使用
status
模块中的常量提高可读性 - 201 Created用于资源创建
- 204 No Content用于成功删除
- 4xx系列用于客户端错误
三、高级请求处理
3.1 表单数据处理
处理表单提交需要额外依赖python-multipart
:
from fastapi import Form
@app.post("/login/")
async def login(
username: str = Form(...),
password: str = Form(...)
):
return {"username": username}
注意事项:
- 必须安装
python-multipart
- 表单字段必须声明为必选(
...
) - 同时支持文件上传
3.2 文件上传处理
多部分表单处理示例:
from fastapi import UploadFile, File
@app.post("/upload/")
async def upload_file(
file: UploadFile = File(...),
description: str = Form(None)
):
contents = await file.read()
return {
"filename": file.filename,
"description": description,
"content_length": len(contents)
}
关键方法:
UploadFile.read()
获取文件内容UploadFile.filename
获取原始文件名- 支持异步文件操作
3.3 请求头处理
自定义请求头可通过Header
参数获取:
from fastapi import Header, HTTPException
@app.get("/items/")
async def read_items(
user_agent: str = Header(None),
x_token: str = Header(...)
):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="Invalid X-Token header")
return {"user_agent": user_agent, "x_token": x_token}
验证技巧:
- 必选头使用
...
- 可选头设置默认值
- 结合
HTTPException
进行验证
四、最佳实践总结
- 类型安全优先:充分利用Pydantic模型和类型注解
- 分层验证:路径参数→查询参数→请求体逐层验证
- 响应控制:根据场景选择合适响应类型(JSON/HTML/流式)
- 文档友好:合理使用路径操作装饰器的文档参数
- 性能优化:对大文件上传使用流式处理
通过掌握这些核心机制,开发者可以高效构建出类型安全、文档完备的RESTful API。FastAPI的自动文档功能(访问/docs
)能实时反映接口定义,极大提升开发效率。建议从简单CRUD操作开始实践,逐步掌握更复杂的请求处理模式。
发表评论
登录后可评论,请前往 登录 或 注册