SteveJ
SteveJ

Reputation: 3323

How to include $id fields in Pydantic.schema()

According to json-schema.org, it is best practice to include the $id field with objects.

I'm struggling with how to get this at the top level, for example;

class MySchema(BaseModel):

    id: str = Field(default="http://my_url/my_schema.json", alias="$id")


if __name__ == '__main__':
    pprint(MySchema.schema())

yields

{'properties': {'$id': {'default': 'http://my_url/my_schema.json',
                        'title': '$Id',
                        'type': 'string'}},
 'title': 'MySchema',
 'type': 'object'}

How do I get $id at the top level, with title and type, not as a nested property?

Upvotes: 0

Views: 1275

Answers (2)

est.tenorio
est.tenorio

Reputation: 400

In the latest version there is a json_schema_extra field when using the model_config:

from pydantic import BaseModel

class Person(BaseModel):
    model_config = ConfigDict(
        title="Person Model",
        json_schema_extra={"$id": "my person id"})
    name: str
    age: int

Upvotes: 0

alex_noname
alex_noname

Reputation: 32233

Pydantic provides a number of ways of schema customization. For example, using schema_extra config option:

from pydantic import BaseModel


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

    class Config:
        schema_extra = {
            '$id': "my.custom.schema"
        }


print(Person.schema_json(indent=2))

Output:

{
  "title": "Person",
  "type": "object",
  "properties": {
    "name": {
      "title": "Name",
      "type": "string"
    },
    "age": {
      "title": "Age",
      "type": "integer"
    }
  },
  "required": [
    "name",
    "age"
  ],
  "$id": "my.custom.schema"
}

Upvotes: 2

Related Questions