简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM