logo

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

作者:宇宙中心我曹县2025.09.23 11:56浏览量:0

简介:本文深入解析FastAPI框架中请求与响应的核心机制,涵盖路径参数、查询参数、请求体处理、响应模型构建及状态码管理等关键模块。通过完整代码示例展示如何高效处理HTTP请求并返回结构化响应,帮助开发者快速掌握FastAPI的API开发核心技能。

『FastAPI』快速掌握”请求与响应”的基础用法

一、FastAPI请求处理核心机制

FastAPI基于Starlette和Pydantic构建的请求处理系统,通过装饰器模式实现路径操作函数的声明式定义。其核心请求处理流程包含三个关键阶段:

  1. 路径匹配阶段:根据请求路径和方法匹配对应的路由处理函数
  2. 依赖解析阶段:自动解析路径参数、查询参数和请求体
  3. 响应生成阶段:将处理结果序列化为指定格式的响应
  1. from fastapi import FastAPI, Path, Query
  2. app = FastAPI()
  3. @app.get("/items/{item_id}")
  4. async def read_item(
  5. item_id: int = Path(..., description="物品唯一标识"),
  6. q: str = Query(None, max_length=50)
  7. ):
  8. return {"item_id": item_id, "q": q}

二、请求参数处理详解

1. 路径参数处理

FastAPI通过类型注解自动转换路径参数类型,支持内置类型和自定义类型:

  1. @app.get("/users/{user_id}/posts/{post_id}")
  2. async def get_post(
  3. user_id: int,
  4. post_id: int = Path(..., ge=1, le=1000)
  5. ):
  6. return {"user_id": user_id, "post_id": post_id}

关键特性:

  • 自动类型转换(字符串转数字)
  • 参数验证(通过Path的ge/le参数)
  • 路径参数顺序无关性(通过类型注解匹配)

2. 查询参数处理

查询参数支持多种声明方式:

  1. @app.get("/search/")
  2. async def search_items(
  3. q: str = None, # 可选参数
  4. limit: int = Query(10, le=100), # 带默认值的必选参数
  5. sort: str = Query(..., regex="^(asc|desc)$") # 正则验证
  6. ):
  7. results = {"items": [f"Item {i}" for i in range(limit)]}
  8. return results

高级用法:

  • 参数别名:alias="search_term"
  • 弃用参数:deprecated=True
  • 多值参数:tags: List[str] = Query(...)

3. 请求体处理

FastAPI通过Pydantic模型实现自动请求体验证:

  1. from pydantic import BaseModel
  2. class Item(BaseModel):
  3. name: str
  4. description: str = None
  5. price: float
  6. tax: float = None
  7. @app.post("/items/")
  8. async def create_item(item: Item):
  9. item_dict = item.dict()
  10. if item.tax:
  11. price_with_tax = item.price + item.tax
  12. item_dict.update({"price_with_tax": price_with_tax})
  13. return item_dict

验证机制:

  • 自动类型转换
  • 字段必选/可选控制
  • 嵌套模型验证
  • 自定义验证器

三、响应处理高级技巧

1. 响应模型控制

通过response_model参数控制返回数据结构:

  1. from fastapi import FastAPI
  2. from pydantic import BaseModel
  3. class OutputItem(BaseModel):
  4. id: int
  5. name: str
  6. @app.post("/items/", response_model=OutputItem)
  7. async def create_item(item: Item):
  8. # 业务逻辑处理
  9. return OutputItem(id=1, name=item.name)

优势:

  • 数据过滤(排除敏感字段)
  • 序列化控制
  • 文档自动生成

2. 状态码管理

FastAPI支持显式状态码设置:

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

常用状态码:

  • 200 OK:默认GET响应
  • 201 Created:资源创建
  • 400 Bad Request:客户端错误
  • 404 Not Found:资源不存在

3. 自定义响应

支持多种响应形式:

  1. from fastapi.responses import JSONResponse, HTMLResponse, StreamingResponse
  2. @app.get("/json")
  3. async def get_json():
  4. return JSONResponse({"key": "value"})
  5. @app.get("/html")
  6. async def get_html():
  7. return HTMLResponse("<h1>Hello World</h1>")
  8. @app.get("/stream")
  9. async def stream_data():
  10. def generate():
  11. for i in range(10):
  12. yield f"Data chunk {i}\n"
  13. return StreamingResponse(generate(), media_type="text/plain")

四、最佳实践与性能优化

1. 参数验证策略

  • 使用Field进行详细参数说明:
    ```python
    from pydantic import Field

class Item(BaseModel):
name: str = Field(…, min_length=3, max_length=50)
price: float = Field(…, gt=0)

  1. - 组合验证器:
  2. ```python
  3. from pydantic import validator
  4. class Item(BaseModel):
  5. price: float
  6. discount: float = 0
  7. @validator('discount')
  8. def validate_discount(cls, v, values):
  9. if 'price' in values and v > values['price']:
  10. raise ValueError('Discount cannot exceed price')
  11. return v

2. 响应性能优化

  • 使用response_model_exclude_unset减少数据传输

    1. @app.get("/items/{item_id}", response_model=Item, response_model_exclude_unset=True)
    2. async def get_item(item_id: int):
    3. # 返回可能包含未设置字段的对象
    4. pass
  • 异步响应处理:

    1. @app.get("/async-data")
    2. async def get_async_data():
    3. # 模拟异步数据获取
    4. await asyncio.sleep(1)
    5. return {"data": "async result"}

3. 调试与错误处理

自定义异常处理器:

  1. from fastapi import FastAPI, Request
  2. from fastapi.responses import JSONResponse
  3. from fastapi.exceptions import HTTPException
  4. app = FastAPI()
  5. @app.exception_handler(HTTPException)
  6. async def http_exception_handler(request: Request, exc: HTTPException):
  7. return JSONResponse(
  8. status_code=exc.status_code,
  9. content={"message": exc.detail},
  10. )
  11. @app.get("/error")
  12. async def trigger_error():
  13. raise HTTPException(status_code=404, detail="Item not found")

五、完整示例:综合应用

  1. from fastapi import FastAPI, Path, Query, HTTPException
  2. from pydantic import BaseModel, Field, validator
  3. from typing import Optional, List
  4. app = FastAPI()
  5. # 请求模型
  6. class Product(BaseModel):
  7. name: str = Field(..., min_length=2, max_length=100)
  8. price: float = Field(..., gt=0)
  9. category: str
  10. tags: List[str] = []
  11. @validator('tags')
  12. def validate_tags(cls, v):
  13. if len(v) > 10:
  14. raise ValueError('Maximum 10 tags allowed')
  15. return v
  16. # 响应模型
  17. class ProductResponse(BaseModel):
  18. id: int
  19. name: str
  20. price: float
  21. formatted_price: str
  22. category: str
  23. @app.post("/products/", response_model=ProductResponse, status_code=201)
  24. async def create_product(
  25. product: Product,
  26. product_id: int = Path(..., description="Product unique identifier"),
  27. verbose: bool = Query(False, description="Include detailed information")
  28. ):
  29. if product.price > 1000 and product.category not in ["premium", "luxury"]:
  30. raise HTTPException(
  31. status_code=400,
  32. detail="High price products must belong to premium/luxury categories"
  33. )
  34. formatted_price = f"${product.price:.2f}"
  35. response = ProductResponse(
  36. id=product_id,
  37. name=product.name,
  38. price=product.price,
  39. formatted_price=formatted_price,
  40. category=product.category
  41. )
  42. if verbose:
  43. response.tags = product.tags
  44. return response
  45. # 运行命令:uvicorn main:app --reload

六、总结与进阶建议

FastAPI的请求与响应处理机制通过类型注解和Pydantic模型实现了:

  1. 自动参数解析与验证
  2. 结构化响应生成
  3. 完整的OpenAPI文档生成

进阶学习方向:

  • 依赖注入系统
  • WebSocket支持
  • 背景任务处理
  • 中间件开发
  • 安全认证集成

建议开发者从基础参数处理入手,逐步掌握响应模型控制,最终实现完整的RESTful API开发。FastAPI的自动文档和类型安全特性可以显著提升开发效率和代码质量。

相关文章推荐

发表评论