Examples
Configurations
While the Configuration documentation contains all available options in detail, this page shows them in conjunction to provide different examples on how to display pydantic models and settings.
Default
This example shows the default out-of-the-box configuration of autodoc_pydantic. In contrast, it also shows how standard sphinx autodoc displays the same example code.
- pydantic settings ExampleSettings[source]
Document your project settings very conveniently. Applies like wise to pydantic models.
Show JSON schema
{ "title": "ExampleSettings", "description": "Document your project settings very conveniently. Applies like wise\nto pydantic models.", "type": "object", "properties": { "field_without_default": { "title": "Field Without Default", "env_names": "{'foo_field_without_default'}", "type": "string" }, "field_plain_with_validator": { "title": "Field Plain With Validator", "default": 100, "env_names": "{'foo_field_plain_with_validator'}", "type": "integer" }, "BarFoo": { "title": "Barfoo", "default": "FooBar", "env": "BarFoo", "env_names": "{'barfoo'}", "type": "string" }, "field_with_constraints_and_description": { "title": "Field With Constraints And Description", "description": "Shows constraints within doc string.", "default": 5, "minimum": 0, "maximum": 100, "env_names": "{'foo_field_with_constraints_and_description'}", "type": "integer" } }, "required": [ "field_without_default" ], "additionalProperties": false }
- Config:
allow_mutation: bool = True
env_prefix: str = foo_
- Fields:
- Validators:
- field field_plain_with_validator: int = 100
Show standard field with type annotation.
- Validated by:
- field field_with_constraints_and_description: int = 5
Shows constraints within doc string.
- Constraints:
minimum = 0
maximum = 100
- field field_with_validator_and_alias: str = 'FooBar' (alias 'BarFoo')
Shows corresponding validator with link/anchor.
- Validated by:
- field field_without_default: str [Required]
Shows the [Required] marker in the signature.
- validator check_max_length_ten » field_plain_with_validator, field_with_validator_and_alias[source]
Show corresponding field with link/anchor.
- class ExampleSettings(_env_file: str | PathLike | List[str | PathLike] | Tuple[str | PathLike, ...] | None = '<object object>', _env_file_encoding: str | None = None, _env_nested_delimiter: str | None = None, _secrets_dir: str | PathLike | None = None, *, field_without_default: str, field_plain_with_validator: int = 100, BarFoo: str = 'FooBar', field_with_constraints_and_description: ConstrainedIntValue = 5)[source]
Document your project settings very conveniently. Applies like wise to pydantic models.
- classmethod check_max_length_ten(v)[source]
Show corresponding field with link/anchor.
- attribute field_plain_with_validator: int
Show standard field with type annotation.
- attribute field_with_constraints_and_description: int
- attribute field_with_validator_and_alias: str
Shows corresponding validator with link/anchor.
- attribute field_without_default: str
Shows the [Required] marker in the signature.
from pydantic import BaseSettings, validator, Field
class ExampleSettings(BaseSettings):
"""Document your project settings very conveniently. Applies like wise
to pydantic models.
"""
field_without_default: str
"""Shows the *[Required]* marker in the signature."""
field_plain_with_validator: int = 100
"""Show standard field with type annotation."""
field_with_validator_and_alias: str = Field("FooBar",
alias="BarFoo",
env="BarFoo")
"""Shows corresponding validator with link/anchor."""
field_with_constraints_and_description: int = Field(
default=5,
ge=0,
le=100,
description="Shows constraints within doc string."
)
@validator("field_with_validator_and_alias", "field_plain_with_validator")
def check_max_length_ten(cls, v):
"""Show corresponding field with link/anchor.
"""
if len(v) >= 10:
raise ValueError("No more than 10 characters allowed")
return v
class Config:
env_prefix = "foo_"
allow_mutation = True
.. autopydantic_settings:: target.example_setting.ExampleSettings
Complete
This example represents a rendered output for which all features are enabled. It deviates from the default configuration above because it contains redundant information which is most likely not required. However, for demonstration purposes, this scenario covers all available display options for pydantic models/settings.
- pydantic settings ExampleSettings[source]
Document your project settings very conveniently. Applies like wise to pydantic models.
Show JSON schema
{ "title": "ExampleSettings", "description": "Document your project settings very conveniently. Applies like wise\nto pydantic models.", "type": "object", "properties": { "field_without_default": { "title": "Field Without Default", "env_names": "{'foo_field_without_default'}", "type": "string" }, "field_plain_with_validator": { "title": "Field Plain With Validator", "default": 100, "env_names": "{'foo_field_plain_with_validator'}", "type": "integer" }, "BarFoo": { "title": "Barfoo", "default": "FooBar", "env": "BarFoo", "env_names": "{'barfoo'}", "type": "string" }, "field_with_constraints_and_description": { "title": "Field With Constraints And Description", "description": "Shows constraints within doc string.", "default": 5, "minimum": 0, "maximum": 100, "env_names": "{'foo_field_with_constraints_and_description'}", "type": "integer" } }, "required": [ "field_without_default" ], "additionalProperties": false }
- Config:
allow_mutation: bool = True
env_prefix: str = foo_
- Fields:
- Validators:
- field field_plain_with_validator: int = 100
Show standard field with type annotation.
- Validated by:
- field field_with_constraints_and_description: int = 5
Shows constraints within doc string.
- Constraints:
minimum = 0
maximum = 100
- field field_with_validator_and_alias: str = 'FooBar' (alias 'BarFoo')
Shows corresponding validator with link/anchor.
- Validated by:
- field field_without_default: str [Required]
Shows the [Required] marker in the signature.
- validator check_max_length_ten » field_plain_with_validator, field_with_validator_and_alias[source]
Show corresponding field with link/anchor.
- model Config[source]
- allow_mutation = True
- env_prefix = 'foo_'
.. autopydantic_settings:: target.example_setting.ExampleSettings
:noindex:
:settings-show-config-member: True
:validator-list-fields: True
from pydantic import BaseSettings, validator, Field
class ExampleSettings(BaseSettings):
"""Document your project settings very conveniently. Applies like wise
to pydantic models.
"""
field_without_default: str
"""Shows the *[Required]* marker in the signature."""
field_plain_with_validator: int = 100
"""Show standard field with type annotation."""
field_with_validator_and_alias: str = Field("FooBar",
alias="BarFoo",
env="BarFoo")
"""Shows corresponding validator with link/anchor."""
field_with_constraints_and_description: int = Field(
default=5,
ge=0,
le=100,
description="Shows constraints within doc string."
)
@validator("field_with_validator_and_alias", "field_plain_with_validator")
def check_max_length_ten(cls, v):
"""Show corresponding field with link/anchor.
"""
if len(v) >= 10:
raise ValueError("No more than 10 characters allowed")
return v
class Config:
env_prefix = "foo_"
allow_mutation = True
Entity-Relationship Diagram
This example shows the redered output of a pydantic model including an Entity-Relationship Diagram.
- pydantic model Response[source]
HTTP Response representation.
Show JSON schema
{ "title": "Response", "description": "HTTP Response representation.", "type": "object", "properties": { "data": { "title": "Data" }, "error": { "$ref": "#/definitions/Error" } }, "definitions": { "Error": { "title": "Error", "description": "HTTP error representation.", "type": "object", "properties": { "code": { "title": "Code", "type": "integer" }, "message": { "title": "Message", "type": "string" } }, "required": [ "code", "message" ] } } }
- Fields:
- Validators:
- field data: DataT | None = None
- field error: Error | None = None
- Validated by:
.. autopydantic_model:: target.example_generics.Response
:model-erdantic-figure: True
:model-erdantic-figure-collapsed: False
from typing import Generic, TypeVar, Optional, List
from pydantic import BaseModel, validator
from pydantic.generics import GenericModel
DataT = TypeVar('DataT')
class Error(BaseModel):
"""HTTP error representation."""
code: int
message: str
class DataModel(BaseModel):
"""Payload representation."""
numbers: List[int]
people: List[str]
class Response(GenericModel, Generic[DataT]):
"""HTTP Response representation."""
data: Optional[DataT]
error: Optional[Error]
@validator('error', always=True)
def check_consistency(cls, v, values):
if v is not None and values['data'] is not None:
raise ValueError('must not provide both data and error')
if v is None and values.get('data') is None:
raise ValueError('must provide data or error')
return v
Fields only
In this scenario everything is hidden except actual pydantic fields. Validators and model/setting config is hidden.
- pydantic settings ExampleSettings[source]
Document your project settings very conveniently. Applies like wise to pydantic models.
- Fields:
- field field_plain_with_validator: int = 100
Show standard field with type annotation.
- field field_with_constraints_and_description: int = 5
Shows constraints within doc string.
- Constraints:
minimum = 0
maximum = 100
- field field_with_validator_and_alias: str = 'FooBar' (alias 'BarFoo')
Shows corresponding validator with link/anchor.
- field field_without_default: str [Required]
Shows the [Required] marker in the signature.
.. autopydantic_settings:: target.example_setting.ExampleSettings
:settings-show-json: False
:settings-show-config-member: False
:settings-show-config-summary: False
:settings-show-validator-members: False
:settings-show-validator-summary: False
:field-list-validators: False
from pydantic import BaseSettings, validator, Field
class ExampleSettings(BaseSettings):
"""Document your project settings very conveniently. Applies like wise
to pydantic models.
"""
field_without_default: str
"""Shows the *[Required]* marker in the signature."""
field_plain_with_validator: int = 100
"""Show standard field with type annotation."""
field_with_validator_and_alias: str = Field("FooBar",
alias="BarFoo",
env="BarFoo")
"""Shows corresponding validator with link/anchor."""
field_with_constraints_and_description: int = Field(
default=5,
ge=0,
le=100,
description="Shows constraints within doc string."
)
@validator("field_with_validator_and_alias", "field_plain_with_validator")
def check_max_length_ten(cls, v):
"""Show corresponding field with link/anchor.
"""
if len(v) >= 10:
raise ValueError("No more than 10 characters allowed")
return v
class Config:
env_prefix = "foo_"
allow_mutation = True
Specifics
This section focuses rendered documentation examples of pydantic specific concepts such as root validators, required/optional fields or generic models.
Asterisk and root validators
This example highlights how asterisk
(@validator('*')
) and root validators (@root_validator
)
are represented. Since they validate all fields, their corresponding field reference is replaced
with a simple all fields
marker which hyperlinks to the related model itself.
- pydantic model ExampleValidators[source]
Show usage of asterisk and root validators.
Show JSON schema
{ "title": "ExampleValidators", "description": "Show usage of asterisk and root validators.\n\n ", "type": "object", "properties": { "name": { "title": "Name", "type": "string" }, "email": { "title": "Email", "type": "string" } }, "required": [ "name", "email" ] }
- Fields:
- Validators:
check_contains_letters
»all fields
check_non_whitespaces
»all fields
- field email: str [Required]
- Validated by:
- field name: str [Required]
- Validated by:
.. autopydantic_model:: target.example_validators.ExampleValidators
from pydantic import BaseModel, validator, root_validator
class ExampleValidators(BaseModel):
"""Show usage of asterisk and root validators.
"""
name: str
email: str
@validator("*")
def check_non_whitespaces(cls, v):
"""Confirm that string contains non whitespace characters.
"""
stripped = v.strip()
if stripped:
return v
else:
raise ValueError("String contains only whitespace characters.")
@root_validator
def check_contains_letters(cls, values):
"""Confirm that string contains at least one letter.
"""
for key, value in values.items():
has_letter = any(x.isalpha() for x in value)
if not has_letter:
raise ValueError(f"Field '{key}' does not contain a letter.")
return values
Note
By default the function signature of validators is replaced with hyperlinks to validated fields by autodoc_pydantic. You can disable this behaviour via validator-replace-signature.
Required/Optional fields
Pydantic has different ways to represent required or optional fields as described in the official documentation . The following example outlines all available combinations with the default autodoc_pydantic settings:
- pydantic model RequiredOptionalField[source]
Outlines different representations of required/optional fields.
Show JSON schema
{ "title": "RequiredOptionalField", "description": "Outlines different representations of required/optional fields.\n\n ", "type": "object", "properties": { "required_standard": { "title": "Required Standard", "type": "integer" }, "required_optional_with_ellipsis": { "title": "Required Optional With Ellipsis", "type": "integer" }, "required_optional_with_field": { "title": "Required Optional With Field", "type": "integer" }, "optional_standard": { "title": "Optional Standard", "default": 1, "type": "integer" }, "optional_with_optional": { "title": "Optional With Optional", "type": "integer" }, "optional_with_default_factory": { "title": "Optional With Default Factory", "type": "integer" } }, "required": [ "required_standard", "required_optional_with_ellipsis", "required_optional_with_field" ] }
- Fields:
- field required_standard: int [Required]
No default value given:
required_standard: int
- field required_optional_with_ellipsis: int | None [Required]
Requires either integer or None:
required_optional_with_ellipsis: Optional[int] = ...
- field required_optional_with_field: int | None [Required]
Requires either integer or None:
required_optional_with_field: Optional[int] = Field(...)
- field optional_standard: int = 1
Optional value with default value 1:
optional_standard: int = 1
- field optional_with_optional: int | None = None
Optional value with default value None:
optional_with_optional: Optional[int]
- field optional_with_default_factory: int [Optional]
Optional value with default factory:
optional_with_default_factory: int = Field(default_factory=lambda: 1)
.. autopydantic_model:: target.example_required_optional_fields.RequiredOptionalField
:member-order: bysource
:model-summary-list-order: bysource
from typing import Optional
from pydantic import BaseModel, Field
class RequiredOptionalField(BaseModel):
"""Outlines different representations of required/optional fields.
"""
required_standard: int
"""No default value given:
:code:`required_standard: int`
"""
required_optional_with_ellipsis: Optional[int] = ...
"""Requires either integer or None:
:code:`required_optional_with_ellipsis: Optional[int] = ...`
"""
required_optional_with_field: Optional[int] = Field(...)
"""Requires either integer or None:
:code:`required_optional_with_field: Optional[int] = Field(...)`
"""
optional_standard: int = 1
"""Optional value with default value *1*:
:code:`optional_standard: int = 1`
"""
optional_with_optional: Optional[int]
"""Optional value with default value *None*:
:code:`optional_with_optional: Optional[int]`"""
optional_with_default_factory: int = Field(default_factory=lambda: 1)
"""Optional value with default factory:
:code:`optional_with_default_factory: int = Field(default_factory=lambda: 1)`
"""
Swap field name with alias
It is possible to completely replace the field name with the provided field alias when field-swap-name-and-alias is enabled:
- pydantic model SwapFieldWithAlias[source]
SwapFieldWithAlias.
Show JSON schema
{ "title": "SwapFieldWithAlias", "description": "SwapFieldWithAlias.", "type": "object", "properties": { "aliased_field": { "title": "Aliased Field", "default": 5, "type": "integer" }, "field_without_alias": { "title": "Field Without Alias", "default": 5, "type": "integer" } } }
- Fields:
- Validators:
- validator check » field_without_alias, aliased_field[source]
Check.
- Validates:
- pydantic model SwapFieldWithAlias[source]
SwapFieldWithAlias.
Show JSON schema
{ "title": "SwapFieldWithAlias", "description": "SwapFieldWithAlias.", "type": "object", "properties": { "aliased_field": { "title": "Aliased Field", "default": 5, "type": "integer" }, "field_without_alias": { "title": "Field Without Alias", "default": 5, "type": "integer" } } }
- Fields:
- Validators:
- field field_with_alias: int = 5 (alias 'aliased_field')
Field with alias.
- Validated by:
- field field_without_alias: int = 5
Field without alias.
- Validated by:
- validator check » field_without_alias, field_with_alias[source]
Check.
- Validates:
.. autopydantic_model:: target.example_swap_name_with_alias.SwapFieldWithAlias
:field-swap-name-and-alias:
:validator-list-fields:
from pydantic import BaseModel, validator, Field
class SwapFieldWithAlias(BaseModel):
"""SwapFieldWithAlias."""
field_with_alias: int = Field(default=5, alias="aliased_field")
"""Field with alias."""
field_without_alias: int = 5
"""Field without alias."""
@validator("field_with_alias", "field_without_alias")
def check(cls, v) -> str:
"""Check."""
return v
Generic Models
Generic pydantic models can be documented just as normal models, too. The following example is borrowed from the official pydantic documentation for generic models :
- pydantic model DataModel[source]
Payload representation.
Show JSON schema
{ "title": "DataModel", "description": "Payload representation.", "type": "object", "properties": { "numbers": { "title": "Numbers", "type": "array", "items": { "type": "integer" } }, "people": { "title": "People", "type": "array", "items": { "type": "string" } } }, "required": [ "numbers", "people" ] }
- field numbers: List[int] [Required]
- field people: List[str] [Required]
- pydantic model Error[source]
HTTP error representation.
Show JSON schema
{ "title": "Error", "description": "HTTP error representation.", "type": "object", "properties": { "code": { "title": "Code", "type": "integer" }, "message": { "title": "Message", "type": "string" } }, "required": [ "code", "message" ] }
- Fields:
- field code: int [Required]
- field message: str [Required]
- pydantic model Response[source]
HTTP Response representation.
Show JSON schema
{ "title": "Response", "description": "HTTP Response representation.", "type": "object", "properties": { "data": { "title": "Data" }, "error": { "$ref": "#/definitions/Error" } }, "definitions": { "Error": { "title": "Error", "description": "HTTP error representation.", "type": "object", "properties": { "code": { "title": "Code", "type": "integer" }, "message": { "title": "Message", "type": "string" } }, "required": [ "code", "message" ] } } }
- Fields:
- Validators:
- field data: DataT | None = None
.. automodule:: target.example_generics
:members:
from typing import Generic, TypeVar, Optional, List
from pydantic import BaseModel, validator
from pydantic.generics import GenericModel
DataT = TypeVar('DataT')
class Error(BaseModel):
"""HTTP error representation."""
code: int
message: str
class DataModel(BaseModel):
"""Payload representation."""
numbers: List[int]
people: List[str]
class Response(GenericModel, Generic[DataT]):
"""HTTP Response representation."""
data: Optional[DataT]
error: Optional[Error]
@validator('error', always=True)
def check_consistency(cls, v, values):
if v is not None and values['data'] is not None:
raise ValueError('must not provide both data and error')
if v is None and values.get('data') is None:
raise ValueError('must provide data or error')
return v
Reused Validators
Functions can be declared as reusable validators for pydantic models. Unlike normal validators which are bound methods, a reusable validator is an actual function. Therefore, the function should be referenced and linked with corresponding pydantic fields in the generated documentation.
While declaring a reusable validator, a class method is automatically created for the pydantic model that conveys no meaningful information. Hence it can be hidden in the documentation via model-hide-resued-validator.
The following example is borrowed from the official pydantic documentation for reused validators which shows how the reused function is correctly linked within the model’s validator summary and the fields validator’s list:
- normalize(name: str) str [source]
Normalize docstring.
- pydantic model Consumer[source]
Show JSON schema
{ "title": "Consumer", "type": "object", "properties": { "name": { "title": "Name", "type": "string" } }, "required": [ "name" ] }
- Fields:
- Validators:
- field name: str [Required]
- Validated by:
- classmethod normalize_name() str
Normalize docstring.
- pydantic model Producer[source]
Show JSON schema
{ "title": "Producer", "type": "object", "properties": { "name": { "title": "Name", "type": "string" } }, "required": [ "name" ] }
- Fields:
- Validators:
- field name: str [Required]
- Validated by:
- classmethod normalize_name() str
Normalize docstring.
.. automodule:: target.example_reused_validators
:members:
:undoc-members:
from pydantic import BaseModel, validator
def normalize(name: str) -> str:
"""Normalize docstring."""
return ' '.join((word.capitalize()) for word in name.split(' '))
class Producer(BaseModel):
name: str
# validators
normalize_name = validator('name', allow_reuse=True)(normalize)
class Consumer(BaseModel):
name: str
# validators
normalize_name = validator('name', allow_reuse=True)(normalize)