logo

「FastAPI核心教程」请求与响应基础用法全解析

作者:Nicky2025.09.23 11:56浏览量:1

简介:本文深入解析FastAPI中请求与响应的核心机制,涵盖路径参数、查询参数、请求体处理及响应模型构建,通过完整代码示例展示如何高效实现RESTful接口。

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

FastAPI作为现代Python Web框架的代表,以其高性能和简洁的API设计迅速成为开发者首选。本文将系统讲解FastAPI中请求与响应的核心机制,通过实际代码示例帮助开发者快速掌握基础用法。

一、请求参数处理机制

1.1 路径参数(Path Parameters)

路径参数是URL中动态变化的部分,通过花括号{}定义。FastAPI会自动将路径参数转换为函数参数,并支持类型注解。

  1. from fastapi import FastAPI
  2. app = FastAPI()
  3. @app.get("/items/{item_id}")
  4. async def read_item(item_id: int):
  5. return {"item_id": item_id}

关键特性

  • 自动类型转换:当声明item_id: int时,FastAPI会自动将字符串路径参数转为整数
  • 路径校验:若访问/items/abc会返回422错误,提示参数类型不匹配
  • 可变路径:支持正则表达式约束,如@app.get("/items/{item_id:int}")

1.2 查询参数(Query Parameters)

查询参数是URL中?后的键值对,通过函数参数默认值实现可选参数。

  1. @app.get("/items/")
  2. async def read_items(skip: int = 0, limit: int = 10):
  3. return {"skip": skip, "limit": limit}

进阶用法

  • 必选参数:移除默认值使参数变为必填
  • 多值参数:使用List[str]接收多个相同参数名
  • 参数验证:通过Query类实现更复杂的校验
  1. from fastapi import Query
  2. @app.get("/search/")
  3. async def search(q: str = Query(..., min_length=3)):
  4. return {"search_term": q}

1.3 请求体(Request Body)

FastAPI使用Pydantic模型自动处理JSON请求体,提供强大的数据验证能力。

  1. from pydantic import BaseModel
  2. class Item(BaseModel):
  3. name: str
  4. description: str | None = None
  5. price: float
  6. tax: float | None = 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

数据验证机制

  • 自动类型检查:若发送{"price": "ten"}会返回422错误
  • 字段约束:通过Field实现更复杂的验证规则
  • 嵌套模型:支持复杂的数据结构定义

二、响应处理技术

2.1 自动JSON响应

FastAPI默认将函数返回值序列化为JSON,支持多种返回类型:

  • 字典:自动转为JSON对象
  • Pydantic模型:提供结构化响应
  • 数据库模型:需手动转为字典或使用ORM的.dict()方法

2.2 响应模型(Response Model)

通过response_model参数控制响应结构,实现字段过滤和序列化控制。

  1. @app.get("/items/{item_id}", response_model=Item)
  2. async def read_item(item_id: int):
  3. # 实际可能从数据库获取
  4. return {"name": "Foo", "description": "Bar", "price": 10.5}

优势

  • 字段过滤:只返回模型定义的字段
  • 序列化控制:自动处理日期等特殊类型的转换
  • 文档集成:自动在OpenAPI文档中显示响应模型

2.3 自定义响应

需要直接控制响应时,可使用Response对象:

  1. from fastapi import Response
  2. @app.get("/download/")
  3. async def download_file():
  4. file_content = b"Binary file content"
  5. headers = {"Content-Disposition": "attachment; filename=download.bin"}
  6. 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

组合示例

  1. @app.put("/items/{item_id}")
  2. async def update_item(
  3. item_id: int,
  4. item: Item,
  5. q: str | None = None,
  6. user_agent: str = Header(...)
  7. ):
  8. results = {"item_id": item_id, **item.dict()}
  9. if q:
  10. results.update({"q": q})
  11. results.update({"user_agent": user_agent})
  12. return results

四、最佳实践建议

  1. 参数顺序规范

    • 路径参数 > 查询参数 > 请求体
    • 复杂参数使用QueryPath等类显式声明
  2. 响应模型设计

    • 为每个端点定义专用的响应模型
    • 使用Optional字段处理可选响应数据
    • 考虑分页响应时使用嵌套模型
  3. 性能优化

    • 对高频端点使用cached_property缓存计算
    • 考虑使用JSONResponse替代自动序列化处理特殊场景
    • 对大响应使用流式传输
  4. 错误处理

    • 使用HTTPException统一处理业务错误
    • 为常见错误场景定义专用异常类
    • 实现全局异常处理器

五、完整示例

  1. from fastapi import FastAPI, HTTPException, Path, Query
  2. from pydantic import BaseModel, Field
  3. from typing import Optional
  4. app = FastAPI()
  5. class Product(BaseModel):
  6. name: str = Field(..., min_length=3)
  7. price: float = Field(..., gt=0)
  8. discount: Optional[float] = Field(0, ge=0, le=1)
  9. @app.get("/products/{product_id}")
  10. async def get_product(
  11. product_id: int = Path(..., ge=1),
  12. details: bool = Query(False)
  13. ):
  14. if product_id > 1000:
  15. raise HTTPException(status_code=404, detail="Product not found")
  16. product = {
  17. "id": product_id,
  18. "name": "Sample Product",
  19. "price": 19.99,
  20. "discount": 0.1 if details else None
  21. }
  22. return product if details else {"id": product_id, "name": product["name"]}
  23. @app.post("/products/")
  24. async def create_product(product: Product):
  25. final_price = product.price * (1 - product.discount)
  26. return {
  27. **product.dict(),
  28. "final_price": round(final_price, 2),
  29. "status": "created"
  30. }

六、总结与展望

FastAPI的请求与响应处理机制通过类型注解和Pydantic模型实现了开发效率与运行性能的完美平衡。开发者应重点掌握:

  1. 参数声明方式(路径/查询/请求体)
  2. 响应模型的设计原则
  3. 错误处理的最佳实践

未来可深入探索:

  • WebSocket的请求响应模式
  • 依赖注入系统的高级用法
  • 中间件中的请求响应拦截
  • 测试客户端的模拟请求技巧

通过系统掌握这些基础用法,开发者能够快速构建出符合RESTful规范的高性能API服务,为后续的微服务架构和复杂业务实现打下坚实基础。

相关文章推荐

发表评论