I am writing a FastAPI app in python and I would like to use the openapi docs which are automatically generated. In particular, I would like to specify examples for the response value. I know how to do it when the response_model
is a class that inherits from pydantic's BaseModel
, but I am having trouble when it is a list of such classes. Here's a minimal example:
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
}
]
In the automatically generated openapi docs, the example value for a successful response for /person
is
{
"name": "Alice",
"age": 83
}
which is what I want. However, for /people
it is
[
{
"name": "Alice",
"age": 83
}
]
but I would prefer for it to be
[
{
"name": "Alice",
"age": 83
},
{
"name": "Bob",
"age": 77
}
]
Is there any way to achieve that? Thank you in advance!
You can specify your example in responses parameter:
@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
}
]
With this code, the example is specified for status code 200, but you can also configure example for errors (or you can remove 404 entry if you do not want it to appear in your openapi).
For more information you can check FastAPI documentation: https://fastapi.tiangolo.com/advanced/additional-responses/