add 'description' to Pydantic schema when using pydantic.dataclasses

Viewed 2202

Pydantic supports generating OpenApi/jsonschema schemas. When using Pydantic's BaseModel to define models one can add description and title to the resultant json/yaml spec.

class DescriptionFromBasemodel(BaseModel):
    with_desc: int = Field(
        42,
        title='my title',
        description='descr text',)

and this is carried over to the schema: DescriptionFromBasemodel.schema_json()

{
    ... schema title, description, type top-level ...
    "properties": {
        "with_desc": {
            "title": "my title",
            "description": "descr text",
            "type": ...
       ...

however, I cannot determine how to plumb this using pydantic.dataclasses which my application must use to play nicely elsewhere. you can add metadata to stdlib dataclass Field(...)s, but pydantic does not use them (?)

from pydantic.dataclasses import dataclass
from dataclasses import field

@dataclass
class DataclassWithDescription:
   a_field: int = field(metadata=dict(
       description="descr text"))

and no description is generated output using DataclassWithDescription.__pydantic_model__.schema_json()

1 Answers

I find this works (note usage of Pydantic's Field),

from pydantic import Field
from pydantic.dataclasses import dataclass

@dataclass
class DataclassWithDescription:
   a_field: int = Field(description="descr text")
Related