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", "type": "string" }, "field_plain_with_validator": { "default": 100, "title": "Field Plain With Validator", "type": "integer" }, "BarFoo": { "default": "FooBar", "title": "Barfoo", "type": "string" }, "field_with_constraints_and_description": { "default": 5, "description": "Shows constraints within doc string.", "maximum": 100, "minimum": 0, "title": "Field With Constraints And Description", "type": "integer" } }, "additionalProperties": false, "required": [ "field_without_default" ] }
- Config:
env_prefix: str = foo_
frozen: bool = False
- 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:
ge = 0
le = 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_with_validator_and_alias, field_plain_with_validator[source]ο
Show corresponding field with link/anchor.
- <sphinxcontrib.autodoc_pydantic.directives.utility.NullType object at 0x7ffa51fb3f70> ExampleSettings(_case_sensitive: bool | None = None, _env_prefix: str | None = None, _env_file: DotenvType | None = PosixPath('.'), _env_file_encoding: str | None = None, _env_ignore_empty: bool | None = None, _env_nested_delimiter: str | None = None, _env_parse_none_str: str | None = None, _secrets_dir: str | Path | None = None, *, field_without_default: str, field_plain_with_validator: int = 100, BarFoo: str = 'FooBar', field_with_constraints_and_description: int = 5)[source]
Document your project settings very conveniently. Applies like wise to pydantic models.
- <sphinxcontrib.autodoc_pydantic.directives.utility.NullType object at 0x7ffa51fb3f70> check_max_length_ten(v)[source]
Show corresponding field with link/anchor.
- <sphinxcontrib.autodoc_pydantic.directives.utility.NullType object at 0x7ffa51fb3f70> field_plain_with_validator: int
Show standard field with type annotation.
- <sphinxcontrib.autodoc_pydantic.directives.utility.NullType object at 0x7ffa51fb3f70> field_with_constraints_and_description: int
- <sphinxcontrib.autodoc_pydantic.directives.utility.NullType object at 0x7ffa51fb3f70> field_with_validator_and_alias: str
Shows corresponding validator with link/anchor.
- <sphinxcontrib.autodoc_pydantic.directives.utility.NullType object at 0x7ffa51fb3f70> field_without_default: str
Shows the [Required] marker in the signature.
from pydantic import field_validator, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
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')
"""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.'
)
@field_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
model_config = SettingsConfigDict(env_prefix='foo_', frozen=False)
.. autopydantic_settings:: target.example_setting.ExampleSettings
Entity-Relationship Diagramο
This example shows the rendered output of a pydantic model including an Entity-Relationship Diagram.
- pydantic model Order[source]
Order representation.
Show JSON schema
{ "title": "Order", "description": "Order representation.", "type": "object", "properties": { "id": { "title": "Id", "type": "integer" }, "customer": { "$ref": "#/$defs/Customer" }, "products": { "items": { "$ref": "#/$defs/Product" }, "title": "Products", "type": "array" }, "total": { "title": "Total", "type": "number" } }, "$defs": { "Customer": { "description": "Customer representation.", "properties": { "id": { "title": "Id", "type": "integer" }, "name": { "title": "Name", "type": "string" } }, "required": [ "id", "name" ], "title": "Customer", "type": "object" }, "Product": { "description": "Product representation.", "properties": { "id": { "title": "Id", "type": "integer" }, "name": { "title": "Name", "type": "string" }, "category": { "$ref": "#/$defs/ProductCategory" } }, "required": [ "id", "name", "category" ], "title": "Product", "type": "object" }, "ProductCategory": { "description": "Product category representation.", "properties": { "id": { "title": "Id", "type": "integer" }, "name": { "title": "Name", "type": "string" } }, "required": [ "id", "name" ], "title": "ProductCategory", "type": "object" } }, "required": [ "id", "customer", "products", "total" ] }
- Fields:
customer (target.example_erdantic.Customer)
id (int)
products (list[target.example_erdantic.Product])
total (float)
- field customer: Customer [Required]
- field id: int [Required]
- field products: list[Product] [Required]
- field total: float [Required]
.. autopydantic_model:: target.example_erdantic.Order
:model-erdantic-figure: True
:model-erdantic-figure-collapsed: False
from __future__ import annotations
from pydantic import BaseModel
class ProductCategory(BaseModel):
"""Product category representation."""
id: int
name: str
class Product(BaseModel):
"""Product representation."""
id: int
name: str
category: ProductCategory
class Customer(BaseModel):
"""Customer representation."""
id: int
name: str
class Order(BaseModel):
"""Order representation."""
id: int
customer: Customer
products: list[Product]
total: float
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:
ge = 0
le = 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-summary: False
:settings-show-validator-members: False
:settings-show-validator-summary: False
:field-list-validators: False
from pydantic import field_validator, Field
from pydantic_settings import BaseSettings, SettingsConfigDict
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')
"""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.'
)
@field_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
model_config = SettingsConfigDict(env_prefix='foo_', frozen=False)
Specificsο
This section focuses rendered documentation examples of pydantic specific concepts such as model validators, required/optional fields or generic models.
Model validatorsο
This example highlights how model validators
(@model_validator
or @field_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.", "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, field_validator, model_validator
class ExampleValidators(BaseModel):
"""Show usage of asterisk and root validators."""
name: str
email: str
@field_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.')
@model_validator(mode='after')
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.", "type": "object", "properties": { "required_standard": { "title": "Required Standard", "type": "integer" }, "required_optional_with_ellipsis": { "anyOf": [ { "type": "integer" }, { "type": "null" } ], "title": "Required Optional With Ellipsis" }, "required_optional_with_field": { "anyOf": [ { "type": "integer" }, { "type": "null" } ], "title": "Required Optional With Field" }, "optional_standard": { "default": 1, "title": "Optional Standard", "type": "integer" }, "optional_with_optional": { "anyOf": [ { "type": "integer" }, { "type": "null" } ], "title": "Optional With Optional" }, "optional_with_default_factory": { "title": "Optional With Default Factory", "type": "integer" } }, "required": [ "required_standard", "required_optional_with_ellipsis", "required_optional_with_field", "optional_with_optional" ] }
- 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 [Required]ο
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": { "default": 5, "title": "Aliased Field", "type": "integer" }, "field_without_alias": { "default": 5, "title": "Field Without Alias", "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": { "default": 5, "title": "Aliased Field", "type": "integer" }, "field_without_alias": { "default": 5, "title": "Field Without Alias", "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, field_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."""
@field_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": { "items": { "type": "integer" }, "title": "Numbers", "type": "array" }, "people": { "items": { "type": "string" }, "title": "People", "type": "array" } }, "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": { "anyOf": [ {}, { "type": "null" } ], "title": "Data" }, "error": { "anyOf": [ { "$ref": "#/$defs/Error" }, { "type": "null" } ] } }, "$defs": { "Error": { "description": "HTTP error representation.", "properties": { "code": { "title": "Code", "type": "integer" }, "message": { "title": "Message", "type": "string" } }, "required": [ "code", "message" ], "title": "Error", "type": "object" } }, "required": [ "data", "error" ] }
- Fields:
- Validators:
- field data: DataT | None [Required]ο
.. automodule:: target.example_generics
:members:
from typing import Generic, TypeVar, Optional, List
from pydantic import BaseModel, field_validator
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(BaseModel, Generic[DataT]):
"""HTTP Response representation."""
data: Optional[DataT]
error: Optional[Error]
@field_validator('error')
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:
- 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:
- normalize_name() str
Normalize docstring.
.. automodule:: target.example_reused_validators
:members:
:undoc-members:
from pydantic import BaseModel, field_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 = field_validator('name')(normalize)
class Consumer(BaseModel):
name: str
# validators
normalize_name = field_validator('name')(normalize)