I initially posted this over here as an issue on @tiangolo's FastAPI's page, but was pointed over here because it would really be something that would need to be implemented in pydantic itself.
The problem
I would like to tie a schema example to my pydantic model, but currently the only way to do it is to declare the example when you're using the model, as far as I can understand. It's documented here: https://fastapi.tiangolo.com/tutorial/body-schema/#schema-extras.
The solution I would like
It would be nice, if possible, to have something like an __example__ attribute on the model that could be tied directly to the the OpenAPI schema itself. Like the first example under Request and Response Body Examples at https://swagger.io/docs/specification/adding-examples/.
Example
Something along the lines of this:
class Item(BaseModel):
name: str
description: str = None
price: float
tax: float = None
__example__ = {
"name": "Foo",
"description": "A very nice Item",
"price": 35.4,
"tax": 3.2,
}
I don't know if that specific method makes sense or is possible or right, but the general idea of tying examples to the schema itself would be nice.
Couldn't you just add example to config?
Or you could add it to docstring, then read it as rst or similar.
If your "example" variable starts with an underscore it would not be included in the model, or you could decorate with ClassVar.
Not sure what needs to be done in pydantic?
closing as no response
I'll write a PR proposing a way to extend the generated JSON Schema. This will include allowing to add examples in the generated schema.
I looked at the code in the PR. I like it. I didn't know about the Config subclass in a Pydantic Model. That does seem like the right place to put it. Thanks @tiangolo.
Most helpful comment
I looked at the code in the PR. I like it. I didn't know about the Config subclass in a Pydantic Model. That does seem like the right place to put it. Thanks @tiangolo.