当 response_model 是模型列表时,如何为 FastAPI 文档指定几个示例?

How can I specify several examples for the FastAPI docs when response_model is a list of models?

我正在 python 中编写一个 FastAPI 应用程序,我想使用自动生成的 openapi 文档。特别是,我想指定响应值的示例。当 response_model 是继承自 pydantic 的 BaseModel 的 class 时,我知道该怎么做,但是当它是这样的 class 列表时我遇到了麻烦。这是一个最小的例子:

from fastapi import FastAPI

from typing import List
from pydantic import BaseModel, Field


class Person(BaseModel):
    name: str = Field(
        ...,
        title="Name",
        description="The name of the person",
        example="Alice"
    )

    age: int = Field(
        ...,
        title="Age",
        description="The age of the person",
        example=83
    )

    class Config:
        schema_extra = {
            'examples': [
                {
                    "name": "Alice",
                    "age": 83
                },
                {
                    "name": "Bob",
                    "age": 77
                }
            ]
        }


app = FastAPI()


@app.get('/person', response_model=Person)
def person():
    return {
        "name": "Alice",
        "age": 83
    }


@app.get('/people', response_model=List[Person])
def people():
    return [
        {
            "name": "Alice",
            "age": 83
        },
        {
            "name": "Bob",
            "age": 77
        }
    ]

在自动生成的 openapi 文档中,/person 成功响应的示例值为

{
  "name": "Alice",
  "age": 83
}

这就是我想要的。但是,/people

[
  {
    "name": "Alice",
    "age": 83
  }
]

但我希望它是

[
  {
    "name": "Alice",
    "age": 83
  },
  {
    "name": "Bob",
    "age": 77
  }
]

有什么办法可以实现吗?提前致谢!

您可以在 responses 参数中指定示例:

@app.get('/people', response_model=List[Person], responses={
    200: {
        "description": "People successfully found",
        "content": {
            "application/json": {
                "example": [
                    {
                        "name": "Alice",
                        "age": 83
                    },
                    {
                        "name": "Bob",
                        "age": 77
                    }
                ]
            }
        }
    },
    404: {"description": "People not found"}
})
def people():
    return [
        {
            "name": "Alice",
            "age": 83
        },
        {
            "name": "Bob",
            "age": 77
        }
    ]

使用此代码,示例为状态代码 200 指定,但您也可以针对错误配置示例(或者如果您不希望它出现在您的 openapi 中,您可以删除 404 条目)。

有关更多信息,您可以查看 FastAPI 文档:https://fastapi.tiangolo.com/advanced/additional-responses/