Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{'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?

>Solution :

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"
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading