OpenAPI中的其他响应

使用 model 为 response 添加额外的信息

他接受一个 dict 参数, key 是 status codes (比如 200),value 是一个 dict 用来包含一些信息。

每个响应 dict 都可以具有一个键 model,其中包含一个 Pydantic 模型。FastAPI 将采用该模型,生成其 JSON 模式,并将其包含在 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"}
    else:
        return JSONResponse(status_code=404, content={"message": "Item not found"})

 添加不同的媒体类型

# 例如,您可以添加的其他媒体类型image/png,以声明您的路径操作可以返回JSON对象(媒体类型为application/json)或PNG图片:


from typing import Optional

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: Optional[bool] = None):
    if img:
        return FileResponse("image.png", media_type="image/png")
    else:
        return {"id": "foo", "value": "there goes my hero"}

 媒体类型(默认 application/json) , media_type 参数可以不用写 , responses -> guess_type() 判断了文件的后缀名。

https://fastapi.tiangolo.com/advanced/additional-responses/

原文地址:https://www.cnblogs.com/Mint-diary/p/14813958.html