OpenAPI 中的附加响应¶
Warning
这是一个相当高级的主题。
如果您刚开始使用 FastAPI,可能暂时不需要此功能。
您可以声明带有附加状态码、媒体类型、描述等的附加响应。
这些附加响应将被包含在 OpenAPI 模式中,因此也会出现在 API 文档中。
但对于这些附加响应,您必须确保直接返回一个 Response(如 JSONResponse),并包含您的状态码和内容。
使用 model 的附加响应¶
您可以向路径操作装饰器传递一个参数 responses。
它接收一个 dict:键是每个响应的状态码(如 200),值是包含每个响应信息的其他 dict。
每个响应 dict 可以有一个键 model,包含一个 Pydantic 模型,就像 response_model 一样。
FastAPI 将获取该模型,生成其 JSON Schema 并将其包含在 OpenAPI 的正确位置。
例如,要声明另一个状态码为 404 且使用 Pydantic 模型 Message 的响应,您可以这样写:
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get("/items/{item_id}", response_model=Item, responses={404: {"model": Message}})
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
return JSONResponse(status_code=404, content={"message": "Item not found"})
Note
请记住,您必须直接返回 JSONResponse。
Info
model 键不是 OpenAPI 的一部分。
FastAPI 将从那里获取 Pydantic 模型,生成 JSON Schema,并将其放在正确的位置。
正确的位置是:
- 在键
content中,该键的值是另一个 JSON 对象(dict),包含:- 一个带有媒体类型的键,例如
application/json,该键的值是另一个 JSON 对象,包含:- 一个键
schema,其值是模型的 JSON Schema,这是正确的位置。- FastAPI 在此处添加了对 OpenAPI 中其他位置的全局 JSON Schema 的引用,而不是直接包含它。这样,其他应用程序和客户端可以直接使用这些 JSON Schema,提供更好的代码生成工具等。
- 一个键
- 一个带有媒体类型的键,例如
此路径操作在 OpenAPI 中生成的响应将是:
{
"responses": {
"404": {
"description": "Additional Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Message"
}
}
}
},
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/Item"
}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
模式被引用到 OpenAPI 模式中的另一个位置:
{
"components": {
"schemas": {
"Message": {
"title": "Message",
"required": [
"message"
],
"type": "object",
"properties": {
"message": {
"title": "Message",
"type": "string"
}
}
},
"Item": {
"title": "Item",
"required": [
"id",
"value"
],
"type": "object",
"properties": {
"id": {
"title": "Id",
"type": "string"
},
"value": {
"title": "Value",
"type": "string"
}
}
},
"ValidationError": {
"title": "ValidationError",
"required": [
"loc",
"msg",
"type"
],
"type": "object",
"properties": {
"loc": {
"title": "Location",
"type": "array",
"items": {
"type": "string"
}
},
"msg": {
"title": "Message",
"type": "string"
},
"type": {
"title": "Error Type",
"type": "string"
}
}
},
"HTTPValidationError": {
"title": "HTTPValidationError",
"type": "object",
"properties": {
"detail": {
"title": "Detail",
"type": "array",
"items": {
"$ref": "#/components/schemas/ValidationError"
}
}
}
}
}
}
}
为主响应添加附加媒体类型¶
您可以使用相同的 responses 参数为同一个主响应添加不同的媒体类型。
例如,您可以添加一个额外的媒体类型 image/png,声明您的路径操作可以返回一个 JSON 对象(媒体类型为 application/json)或一个 PNG 图像:
from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
200: {
"content": {"image/png": {}},
"description": "Return the JSON item or an image.",
}
},
)
async def read_item(item_id: str, img: Union[bool, None] = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
Note
请注意,您必须使用 FileResponse 直接返回图像。
Info
除非您在 responses 参数中明确指定了不同的媒体类型,否则 FastAPI 将假定响应具有与主响应类相同的媒体类型(默认为 application/json)。
但是,如果您指定了一个自定义响应类,其媒体类型为 None,FastAPI 将为任何具有关联模型的附加响应使用 application/json。
组合信息¶
您还可以从多个地方组合响应信息,包括 response_model、status_code 和 responses 参数。
您可以声明一个 response_model,使用默认状态码 200(或根据需要自定义),然后在 responses 中直接为 OpenAPI 模式中的同一响应声明附加信息。
FastAPI 将保留来自 responses 的附加信息,并将其与模型中的 JSON Schema 组合。
例如,您可以声明一个状态码为 404 的响应,该响应使用 Pydantic 模型并具有自定义 description。
以及一个状态码为 200 的响应,该响应使用您的 response_model,但包含自定义 example:
from fastapi import FastAPI
from fastapi.responses import JSONResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
class Message(BaseModel):
message: str
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={
404: {"model": Message, "description": "The item was not found"},
200: {
"description": "Item requested by ID",
"content": {
"application/json": {
"example": {"id": "bar", "value": "The bar tenders"}
}
},
},
},
)
async def read_item(item_id: str):
if item_id == "foo":
return {"id": "foo", "value": "there goes my hero"}
else:
return JSONResponse(status_code=404, content={"message": "Item not found"})
所有这些将被组合并包含在您的 OpenAPI 中,并显示在 API 文档中:

组合预定义响应和自定义响应¶
您可能希望有一些适用于许多路径操作的预定义响应,但希望将它们与每个路径操作所需的自定义响应组合。
对于这些情况,您可以使用 Python 的“解包”技术,使用 **dict_to_unpack 来解包一个 dict:
old_dict = {
"old key": "old value",
"second old key": "second old value",
}
new_dict = {**old_dict, "new key": "new value"}
这里,new_dict 将包含来自 old_dict 的所有键值对以及新的键值对:
{
"old key": "old value",
"second old key": "second old value",
"new key": "new value",
}
您可以使用该技术来重用路径操作中的一些预定义响应,并将它们与附加的自定义响应组合。
例如:
from typing import Union
from fastapi import FastAPI
from fastapi.responses import FileResponse
from pydantic import BaseModel
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not enough privileges"},
}
app = FastAPI()
@app.get(
"/items/{item_id}",
response_model=Item,
responses={**responses, 200: {"content": {"image/png": {}}}},
)
async def read_item(item_id: str, img: Union[bool, None] = None):
if img:
return FileResponse("image.png", media_type="image/png")
else:
return {"id": "foo", "value": "there goes my hero"}
关于 OpenAPI 响应的更多信息¶
要查看您可以在响应中包含的确切内容,您可以查看 OpenAPI 规范中的以下部分:
- OpenAPI Responses Object,它包括
Response Object。 - OpenAPI Response Object,您可以直接在
responses参数中的每个响应中包含此处的任何内容。包括description、headers、content(在此内部您可以声明不同的媒体类型和 JSON Schema)以及links。