question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[FEATURE] Way to tie OpenAPI Examples to a pydantic model

See original GitHub issue

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 document 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.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Reactions:6
  • Comments:14 (8 by maintainers)

github_iconTop GitHub Comments

2reactions
tiangolocommented, Apr 14, 2020

For completeness, there are new docs about adding examples that show up in Swagger UI: https://fastapi.tiangolo.com/tutorial/schema-extra-example/

2reactions
zamiramircommented, Sep 3, 2019

Typo: “examples” should be “example”

from fastapi.applications import FastAPI
from pydantic import BaseModel


class Person(BaseModel):
    name: str
    age: int

    class Config:
        schema_extra = {
             'example': [{
                'name': 'John Doe',
                'age': 25,
            }]
        }


app = FastAPI()


@app.get('/router', responses={200: {'model': Person}})
async def handler():
    return "hello world"


if __name__ == '__main__':
    import sys
    import fastapi
    print('python version', sys.version)
    print('fastapi version', fastapi.__version__)
    import json
    print(json.dumps(app.openapi(), indent=2, ensure_ascii=False))

python version 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 16:52:21) [Clang 6.0 (clang-600.0.57)] fastapi version 0.38.1

{
  "openapi": "3.0.2",
  "info": {
    "title": "Fast API",
    "version": "0.1.0"
  },
  "paths": {
    "/router": {
      "get": {
        "responses": {
          "200": {
            "description": "Successful Response",
            "content": {
              "application/json": {
                "schema": {}
              }
            }
          }
        },
        "summary": "Handler",
        "operationId": "handler_router_get"
      }
    }
  },
  "components": {
    "schemas": {
      "Person": {
        "title": "Person",
        "required": [
          "name",
          "age"
        ],
        "type": "object",
        "properties": {
          "name": {
            "title": "Name",
            "type": "string"
          },
          "age": {
            "title": "Age",
            "type": "integer"
          }
        },
        "example": [
          {
            "name": "John Doe",
            "age": 25
          }
        ]
      }
    }
  }
}
Read more comments on GitHub >

github_iconTop Results From Across the Web

[FEATURE] Way to tie OpenAPI Examples to a pydantic model
I would like to tie a schema example to my pydantic model, but currently the only way to do it is to declare...
Read more >
Difference with pydantic - apischema
pydantic uses its own BaseModel class, or its own pseudo- dataclass , so you are forced to tie all your code to the...
Read more >
Declare Request Example Data - FastAPI
You can declare an example for a Pydantic model using Config and schema_extra , as described in Pydantic's docs: Schema customization:.
Read more >
python pydantic model attribute as an literal string - You.com
Python pydantic model get field as string ... docstring is always an attribute of an object (module, class or function), not tied to...
Read more >
How to Make the Most of Pydantic - Towards Data Science
Explore techniques for data contract validation, higher interoperability with JSON Schemas, and simplified data model processing. ... Pydantic has been a game- ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found