Search code examples
pythonjsonschemapydantic

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?


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"
    }