0%

FastAPI自学教程(50) - 额外的状态码配置

1.基础用法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse

app = FastAPI()

@app.put("/items/{item_id}")
async def upsert_item(item_id: str):
if item_id in existing_items:
return {"item": existing_items[item_id]}
else:
new_item = {"id": item_id, "name": "New Item"}
return JSONResponse(
status_code=status.HTTP_201_CREATED,
content={"item": new_item}
)
  • 通过直接返回JSONResponse对象自定义状态码
  • 使用status_code参数设置HTTP状态码(如201表示资源已创建)
  • 流程说明:
    graph TD
      A[客户端请求] --> B{资源存在?}
      B -->|是| C[返回200状态码]
      B -->|否| D[返回201状态码]
      C --> E[返回现有资源]
      D --> F[创建并返回新资源]

2.带验证的状态码

1
2
3
4
5
6
7
8
9
10
11
12
13
from fastapi import Body, HTTPException

@app.put("/secure-items/{item_id}")
async def secure_upsert(
item_id: str,
secret: str = Body(...)
):
if secret != "valid-token":
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="无效访问凭证"
)
# ...业务逻辑
  • 结合HTTPException实现:
    • 请求拦截:当验证失败时立即终止流程
    • 状态码映射:403表示权限不足,401表示未认证
    • 错误详情:通过detail参数传递可读的错误信息

3.生产环境最佳实践

  1. 状态码常量:使用fastapi.status预定义常量(如HTTP_201_CREATED)增强可读性
  2. 响应规范化
    1
    2
    3
    4
    5
    ERROR_RESPONSE = {
    400: {"description": "参数验证失败"},
    404: {"description": "资源未找到"}
    }
    @app.get("/items", responses={**ERROR_RESPONSE})
  3. 文档集成:通过responses参数补充OpenAPI文档中的状态码说明
  4. 安全配置
    • 5xx错误不暴露服务器细节
    • 4xx错误提供清晰指引

测试命令示例:

1
2
3
4
5
# 测试创建操作
curl -X PUT -d '{"name":"test"}' http://localhost:8000/items/123

# 测试权限验证
curl -X PUT -d '{"secret":"wrong"}' http://localhost:8000/secure-items/456