FastAPI请求与响应全攻略:从入门到实战指南

FastAPI请求与响应全攻略:从入门到实战指南

FastAPI作为基于Python的现代Web框架,以其高性能、自动生成API文档和类型提示支持等特性,迅速成为开发RESTful API的首选工具。本文将系统梳理FastAPI中请求与响应的核心机制,通过代码示例和最佳实践帮助开发者快速掌握基础用法。

一、请求处理机制解析

1. 路径参数与查询参数

路径参数是URL中动态定义的部分,用于标识特定资源。FastAPI通过Path类提供类型验证和元数据支持:

  1. from fastapi import FastAPI, Path
  2. app = FastAPI()
  3. @app.get("/items/{item_id}")
  4. async def read_item(
  5. item_id: int = Path(..., title="物品ID", ge=1, le=1000)
  6. ):
  7. return {"item_id": item_id}

上述代码中,Pathgele参数分别限制最小值和最大值,...表示必填参数。查询参数则通过函数参数直接声明:

  1. @app.get("/search/")
  2. async def search_items(
  3. query: str = None,
  4. limit: int = 10,
  5. sort: str = "desc"
  6. ):
  7. results = {"query": query, "limit": limit, "sort": sort}
  8. return results

2. 请求体处理

FastAPI支持多种请求体格式,包括JSON、表单数据和文件上传。使用Body类可实现嵌套模型验证:

  1. from fastapi import Body
  2. from pydantic import BaseModel
  3. class Item(BaseModel):
  4. name: str
  5. description: str | None = None
  6. price: float
  7. tax: float | None = None
  8. @app.put("/items/{item_id}")
  9. async def update_item(
  10. item_id: int,
  11. item: Item = Body(..., example={"name": "Foo", "price": 35.4})
  12. ):
  13. result = {"item_id": item_id, **item.dict()}
  14. return result

Bodyexample参数在自动生成的Swagger UI中提供示例数据,提升API可测试性。

3. 表单与文件处理

处理表单数据时需指定Form参数:

  1. from fastapi import Form
  2. @app.post("/login/")
  3. async def login(
  4. username: str = Form(...),
  5. password: str = Form(...)
  6. ):
  7. return {"username": username}

文件上传通过UploadFileFile实现:

  1. from fastapi import UploadFile, File
  2. @app.post("/upload/")
  3. async def create_upload_file(
  4. file: UploadFile = File(...)
  5. ):
  6. contents = await file.read()
  7. return {"filename": file.filename, "size": len(contents)}

二、响应模型与状态码

1. 响应模型定义

使用Pydantic模型可统一响应格式:

  1. from fastapi import FastAPI
  2. from pydantic import BaseModel
  3. class Message(BaseModel):
  4. msg: str
  5. app = FastAPI()
  6. @app.get("/message", response_model=Message)
  7. async def get_message():
  8. return Message(msg="Hello World")

response_model参数会自动将返回数据序列化为指定格式,并在文档中显示模型结构。

2. 状态码控制

FastAPI支持显式设置HTTP状态码:

  1. from fastapi import status
  2. @app.post("/items/", status_code=status.HTTP_201_CREATED)
  3. async def create_item(item: Item):
  4. return item

常用状态码可通过status模块直接引用,提升代码可读性。

3. 响应头设置

通过Response对象可自定义响应头:

  1. from fastapi import Response
  2. @app.get("/download/")
  3. async def download_file(response: Response):
  4. response.headers["Content-Disposition"] = "attachment; filename=data.txt"
  5. return b"file_content"

三、高级请求处理技巧

1. 依赖注入系统

FastAPI的依赖注入可简化参数处理:

  1. from fastapi import Depends, Header
  2. async def verify_token(x_token: str = Header(...)):
  3. if x_token != "fake-super-secret-token":
  4. raise HTTPException(status_code=400, detail="X-Token header invalid")
  5. @app.get("/items/")
  6. async def read_items(token: str = Depends(verify_token)):
  7. return [{"item": "Foo"}, {"item": "Bar"}]

2. 路径操作装饰器

单个路由可定义多个操作:

  1. @app.post("/items/")
  2. async def create_item(item: Item):
  3. return item
  4. @app.put("/items/{item_id}")
  5. async def update_item(item_id: int, item: Item):
  6. return {"item_id": item_id, **item.dict()}

3. 中间件实现

全局中间件可处理跨域和日志:

  1. from fastapi import Request
  2. @app.middleware("http")
  3. async def add_process_time_header(request: Request, call_next):
  4. start_time = time.time()
  5. response = await call_next(request)
  6. process_time = time.time() - start_time
  7. response.headers["X-Process-Time"] = str(process_time)
  8. return response

四、最佳实践建议

  1. 类型提示优先:充分利用Python类型提示,IDE能提供更好的代码补全和错误检查
  2. 模型分层设计:将请求/响应模型分离,避免数据泄露
  3. 文档增强:为路径操作添加详细描述和示例
    1. @app.get("/items/{item_id}")
    2. async def read_item(
    3. item_id: int = Path(..., description="物品唯一标识符")
    4. ):
    5. """
    6. 获取物品详情
    7. - **item_id**: 物品的数字ID
    8. """
    9. return {"item_id": item_id}
  4. 性能优化:对高频接口使用@cache装饰器缓存结果
  5. 安全防护:限制请求体大小,防止DoS攻击

五、调试与测试技巧

  1. 交互式文档:访问/docs使用Swagger UI测试接口
  2. 请求验证:故意传入错误类型参数测试验证机制
  3. 日志配置:在生产环境启用适当的日志级别
    ```python
    import logging
    from fastapi.logger import logger

logger.setLevel(logging.INFO)

  1. 4. **测试客户端**:使用`TestClient`编写单元测试
  2. ```python
  3. from fastapi.testclient import TestClient
  4. def test_read_item():
  5. with TestClient(app) as client:
  6. response = client.get("/items/5")
  7. assert response.status_code == 200
  8. assert response.json() == {"item_id": 5}

通过系统掌握上述请求与响应机制,开发者能够高效构建出符合RESTful规范的API服务。FastAPI的类型安全特性和自动化文档生成能力,可显著提升开发效率和接口可靠性。建议结合实际项目需求,逐步实践本文介绍的各项技术点。