Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement schema_extra #663

Merged
merged 6 commits into from Aug 6, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 2 additions & 0 deletions HISTORY.rst
Expand Up @@ -2,12 +2,14 @@

History
-------

v0.32 (unreleased)
..................
* add model name to ``ValidationError`` error message, #676 by @dmontagu
* **breaking change**: remove ``__getattr__`` and rename ``__values__`` to ``__dict__`` on ``BaseModel``,
deprecation warning on use ``__values__`` attr, attributes access speed increased up to 14 times, #712 by @MrMrRobat
* support ``ForwardRef`` (without self-referencing annotations) in Python3.6, #706 by @koxudaxi
* implement ``schema_extra`` in ``Config`` sub-class, #663 by @tiangolo
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Oh! Sorry, didn't notice I put it in the wrong place.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no problem, we need #665.


v0.31.1 (2019-07-31)
....................
Expand Down
24 changes: 24 additions & 0 deletions docs/examples/schema4.json
@@ -0,0 +1,24 @@
{
"title": "Person",
"type": "object",
"properties": {
"name": {
"title": "Name",
"type": "string"
},
"age": {
"title": "Age",
"type": "integer"
}
},
"required": [
"name",
"age"
],
"examples": [
{
"name": "John Doe",
"age": 25
}
]
}
26 changes: 26 additions & 0 deletions docs/examples/schema4.py
@@ -0,0 +1,26 @@
from pydantic import BaseModel


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

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


print(Person.schema())
# {'title': 'Person',
# 'type': 'object',
# 'properties': {'name': {'title': 'Name', 'type': 'string'},
# 'age': {'title': 'Age', 'type': 'integer'}},
# 'required': ['name', 'age'],
# 'examples': [{'name': 'John Doe', 'age': 25}]}
print(Person.schema_json(indent=2))
15 changes: 15 additions & 0 deletions docs/index.rst
Expand Up @@ -465,6 +465,19 @@ Outputs:

.. literalinclude:: examples/schema3.json

It's also possible to extend/override the generated JSON schema in a model.

To do it, use the ``Config`` sub-class attribute ``schema_extra``.

For example, you could add ``examples`` to the JSON Schema:

.. literalinclude:: examples/schema4.py

(This script is complete, it should run "as is")

Outputs:

.. literalinclude:: examples/schema4.json

Error Handling
..............
Expand Down Expand Up @@ -739,6 +752,7 @@ Behaviour of pydantic can be controlled via the ``Config`` class on a model.

Options:

:title: title for the generated JSON Schema
:anystr_strip_whitespace: strip or not trailing and leading whitespace for str & byte types (default: ``False``)
:min_anystr_length: min length for str & byte types (default: ``0``)
:max_anystr_length: max length for str & byte types (default: ``2 ** 16``)
Expand All @@ -764,6 +778,7 @@ Options:
:alias_generator: callable that takes field name and returns alias for it
:keep_untouched: tuple of types (e. g. descriptors) that won't change during model creation and won't be
included in the model schemas.
:schema_extra: takes a ``dict`` to extend/update the generated JSON Schema

.. warning::

Expand Down
1 change: 1 addition & 0 deletions pydantic/main.py
Expand Up @@ -98,6 +98,7 @@ class BaseConfig:
orm_mode: bool = False
alias_generator: Optional[Callable[[str], str]] = None
keep_untouched: Tuple[type, ...] = ()
schema_extra: Dict[str, Any] = {}

@classmethod
def get_field_schema(cls, name: str) -> Dict[str, str]:
Expand Down
1 change: 1 addition & 0 deletions pydantic/schema.py
Expand Up @@ -563,6 +563,7 @@ def model_process_schema(
model, by_alias=by_alias, model_name_map=model_name_map, ref_prefix=ref_prefix, known_models=known_models
)
s.update(m_schema)
s.update(model.__config__.schema_extra)
return s, m_definitions, nested_models


Expand Down
16 changes: 16 additions & 0 deletions tests/test_schema.py
Expand Up @@ -1472,3 +1472,19 @@ class Model(BaseModel):
'properties': {'color': {'title': 'Color', 'type': 'string', 'format': 'color'}},
'required': ['color'],
}


def test_model_with_schema_extra():
class Model(BaseModel):
a: str

class Config:
schema_extra = {'examples': [{'a': 'Foo'}]}

assert Model.schema() == {
'title': 'Model',
'type': 'object',
'properties': {'a': {'title': 'A', 'type': 'string'}},
'required': ['a'],
'examples': [{'a': 'Foo'}],
}