FastAPI 默认返回 200 OK,但您可以控制 status code(通过装饰器或 response 对象)和 headers 当您需要不同的行为时 — 这对正确的 REST 语义很重要。
在路由上设置默认状态码
python
fastapi status
():
item
():
...
status_code 装饰器参数设置默认成功状态。使用 status 常量(例如 status.HTTP_201_CREATED)比硬编码数字更清晰。正确的代码很重要:创建返回 201,无内容返回 204 等。
from fastapi import Response
@app.get("/items/{id}")
def get_item(id: int, response: Response):
item = db.get(id)
if not item:
response.status_code = status.HTTP_404_NOT_FOUND # set dynamically
return {"error": "not found"}
response.headers["X-Custom"] = "value" # set a custom header
return item
注入 Response 参数让您可以在运行时 有条件地 设置状态码和 headers。
from fastapi import HTTPException
@app.get("/items/{id}")
def get_item(id: int):
item = db.get(id)
if not item:
raise HTTPException(status_code=404, detail="Item not found",
headers={"X-Error": "NotFound"}) # status + detail + headers
return item
对于错误响应,raise HTTPException(...) 是惯用的方法 — 它设置状态、JSON detail 消息和可选的 headers。
from fastapi.responses import JSONResponse
return JSONResponse(content={...}, status_code=202, headers={"X-Custom": "v"})
正确的状态码和 headers 对于构建正确、表现良好的 REST API 至关重要 — 客户端和工具依赖于标准的 HTTP 语义(创建返回 201、未找到返回 404、无内容返回 204 等),因此返回正确的代码是优质 API 契约的一部分。
FastAPI 提供了清晰的控制:路由上的默认 status_code 用于常见情况,可注入的 Response 对象用于动态代码/headers,以及 HTTPException 作为用适当状态和 JSON detail 表示错误的惯用方式。
理解这些机制 — 并使用 status 常量以提高清晰度 — 是构建行为正确、与使用者清晰沟通的 API 的日常知识。