logo

「FastAPI实战」请求与响应核心机制全解析

作者:半吊子全栈工匠2025.09.23 11:56浏览量:0

简介:本文深度解析FastAPI中请求与响应的核心机制,涵盖路径参数、查询参数、请求体、响应模型等基础用法,通过代码示例与最佳实践帮助开发者快速掌握API开发关键技能。

FastAPI请求与响应基础用法全解析

FastAPI作为现代Python Web框架的代表,以其高性能、易用性和类型提示支持赢得了开发者的青睐。本文将系统讲解FastAPI中请求与响应的核心机制,帮助开发者快速构建健壮的API服务。

一、请求参数处理机制

1.1 路径参数与查询参数

路径参数是URL中定义的变量部分,通过花括号{}声明。查询参数则出现在URL的?之后,以键值对形式传递。

  1. from fastapi import FastAPI, Query
  2. app = FastAPI()
  3. # 路径参数示例
  4. @app.get("/items/{item_id}")
  5. async def read_item(item_id: int):
  6. return {"item_id": item_id}
  7. # 查询参数示例
  8. @app.get("/search/")
  9. async def search_items(
  10. q: str = None, # 可选查询参数
  11. limit: int = Query(10, le=100) # 带验证的查询参数
  12. ):
  13. results = {"items": [f"Item {i}" for i in range(limit)]}
  14. if q:
  15. results.update({"q": q})
  16. return results

关键点

  • 路径参数强制要求类型转换,未匹配类型会返回422错误
  • Query()函数提供默认值、验证规则等高级功能
  • 参数默认值使用None表示可选

1.2 请求体处理

FastAPI支持JSON、表单数据、文件上传等多种请求体格式。

  1. from fastapi import FastAPI, Form, File, UploadFile
  2. from pydantic import BaseModel
  3. app = FastAPI()
  4. # JSON请求体
  5. class Item(BaseModel):
  6. name: str
  7. description: str | None = None
  8. price: float
  9. tax: float | None = None
  10. @app.post("/items/")
  11. async def create_item(item: Item):
  12. item_dict = item.dict()
  13. if item.tax:
  14. price_with_tax = item.price + item.tax
  15. item_dict.update({"price_with_tax": price_with_tax})
  16. return item_dict
  17. # 表单数据处理
  18. @app.post("/login/")
  19. async def login(username: str = Form(...), password: str = Form(...)):
  20. return {"username": username}
  21. # 文件上传
  22. @app.post("/upload/")
  23. async def upload_file(file: UploadFile = File(...)):
  24. return {"filename": file.filename}

最佳实践

  • 使用Pydantic模型验证JSON请求体
  • 表单数据使用Form(...)强制要求字段
  • 文件上传区分bytesUploadFile两种模式

二、响应处理机制

2.1 基础响应

FastAPI自动处理JSON序列化,支持自定义响应。

  1. from fastapi import FastAPI, Response
  2. from fastapi.responses import HTMLResponse, PlainTextResponse
  3. app = FastAPI()
  4. # 默认JSON响应
  5. @app.get("/json")
  6. async def get_json():
  7. return {"message": "Hello World"}
  8. # 自定义响应
  9. @app.get("/html", response_class=HTMLResponse)
  10. async def get_html():
  11. return "<h1>HTML Response</h1>"
  12. @app.get("/text", response_class=PlainTextResponse)
  13. async def get_text():
  14. return "Plain Text Response"
  15. # 原始响应控制
  16. @app.get("/custom")
  17. async def custom_response():
  18. return Response(
  19. content="Custom Response",
  20. media_type="text/plain",
  21. status_code=200
  22. )

响应类型选择

  • 默认使用JSONResponse
  • 文本内容使用PlainTextResponse
  • HTML内容使用HTMLResponse
  • 需要精细控制时使用Response

2.2 响应模型与状态码

Pydantic模型可作为响应模型使用,自动处理字段过滤和序列化。

  1. from fastapi import FastAPI, status
  2. from pydantic import BaseModel
  3. app = FastAPI()
  4. class OutputItem(BaseModel):
  5. id: int
  6. name: str
  7. @app.post(
  8. "/items/",
  9. response_model=OutputItem,
  10. status_code=status.HTTP_201_CREATED
  11. )
  12. async def create_item(item: Item):
  13. return OutputItem(id=1, name=item.name)

关键特性

  • response_model自动过滤未声明字段
  • 支持状态码常量如status.HTTP_201_CREATED
  • 模型验证确保响应数据结构正确

三、高级请求处理

3.1 依赖注入系统

FastAPI的依赖注入系统提供强大的请求处理能力。

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

依赖注入优势

  • 集中处理认证、权限等横切关注点
  • 支持异步依赖
  • 自动错误处理

3.2 路径操作装饰器

FastAPI提供多种HTTP方法装饰器。

  1. @app.get("/items/{item_id}")
  2. async def read_item(item_id: int):
  3. return {"item_id": item_id}
  4. @app.put("/items/{item_id}")
  5. async def update_item(item_id: int, item: Item):
  6. return {"item_id": item_id, **item.dict()}
  7. @app.delete("/items/{item_id}")
  8. async def delete_item(item_id: int):
  9. return {"message": f"Item {item_id} deleted"}

RESTful最佳实践

  • 使用对应HTTP方法的装饰器
  • 保持URL结构一致
  • 返回适当的HTTP状态码

四、性能优化技巧

4.1 异步处理

FastAPI原生支持异步路径操作。

  1. import asyncio
  2. from fastapi import FastAPI
  3. app = FastAPI()
  4. async def simulate_db_call():
  5. await asyncio.sleep(1)
  6. return {"data": "fetched"}
  7. @app.get("/async/")
  8. async def async_endpoint():
  9. result = await simulate_db_call()
  10. return result

异步优势

  • 提高I/O密集型操作性能
  • 避免阻塞事件循环
  • 与异步数据库驱动无缝协作

4.2 数据验证优化

利用Pydantic模型进行高效验证。

  1. from pydantic import BaseModel, constr, conint
  2. class StrictItem(BaseModel):
  3. name: constr(min_length=3, max_length=50) # 字符串约束
  4. quantity: conint(ge=1, le=100) # 整数约束
  5. price: float

验证优化点

  • 使用constr进行字符串约束
  • 使用conint/confloat进行数值范围约束
  • 自定义验证逻辑通过模型方法实现

五、完整示例

  1. from fastapi import FastAPI, Depends, HTTPException, status, Query, Form
  2. from pydantic import BaseModel
  3. from typing import Optional
  4. app = FastAPI()
  5. # 模型定义
  6. class Item(BaseModel):
  7. name: str
  8. description: Optional[str] = None
  9. price: float
  10. tax: Optional[float] = None
  11. class User(BaseModel):
  12. username: str
  13. full_name: Optional[str] = None
  14. # 依赖项
  15. def verify_api_key(api_key: str = Query(...)):
  16. if api_key != "secret-key":
  17. raise HTTPException(
  18. status_code=status.HTTP_403_FORBIDDEN,
  19. detail="Invalid API Key"
  20. )
  21. # 路径操作
  22. @app.get("/")
  23. async def root():
  24. return {"message": "Welcome to FastAPI"}
  25. @app.get("/items/{item_id}", dependencies=[Depends(verify_api_key)])
  26. async def read_item(
  27. item_id: int,
  28. q: Optional[str] = None,
  29. limit: int = Query(10, le=100)
  30. ):
  31. item = {"item_id": item_id}
  32. if q:
  33. item.update({"q": q})
  34. return {"item": item, "limit": limit}
  35. @app.post("/users/", response_model=User, status_code=status.HTTP_201_CREATED)
  36. async def create_user(user: User):
  37. return user
  38. @app.post("/login/")
  39. async def login(username: str = Form(...), password: str = Form(...)):
  40. return {"username": username}

六、总结与最佳实践

  1. 类型提示优先:充分利用Python类型提示获得自动文档和验证
  2. 分层验证:路径参数→查询参数→请求体→依赖项的多层验证
  3. 响应控制:根据场景选择合适的响应类型和状态码
  4. 异步设计:I/O操作优先使用异步实现
  5. 安全考虑:敏感操作必须添加认证依赖

FastAPI的请求与响应机制设计精妙,通过合理组合路径参数、查询参数、请求体和响应模型,可以构建出既安全又高效的API服务。建议开发者从简单示例入手,逐步掌握依赖注入、异步处理等高级特性,最终实现企业级API开发。

相关文章推荐

发表评论