Skip to content

Commit

Permalink
Fix the blueprint for pydantic version 2
Browse files Browse the repository at this point in the history
Use the proper `ref_template`, specifying the `{model}` in the template.

An example is documented here: https://github.com/pydantic/pydantic/blob/main/docs/usage/json_schema.md#schema-customization

We need to specify `ref_template = '#/components/schemas/{model}'`, not `ref_template = '#/components/schemas/'` (need that extra `{model}` at the end).

`model_json_schema` generates something like this, for a `Parent` model with a `child` field of type `Child`:

```json
{
    "$defs": {
        "Child": {
            "properties": {
                "foo": {
                    "default": 5,
                    "title": "Foo",
                    "type": "integer"
                }
            },
            "title": "Child",
            "type": "object"
        }
    },
    "properties": {
        "child": {
            "anyOf": [
                {
                    "$ref": "#/components/schemas/Child"
                },
                {
                    "type": "null"
                }
            ],
            "default": null
        }
    },
    "title": "Parent",
    "type": "object"
}
```

The definitions are in a key `$defs` (not `definitions`), and the references start with `#/components/schemas` as expected.
  • Loading branch information
caarmen committed Jul 18, 2023
1 parent b7f79b7 commit d1b874a
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions docs/blueprints/pydantic2.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ def get_name(self, auto_schema, direction):
def map_serializer(self, auto_schema, direction):

# let pydantic generate a JSON schema
schema = model_json_schema(self.target, ref_template="#/components/schemas")
schema = model_json_schema(self.target, ref_template="#/components/schemas/{model}")

# pull out potential sub-schemas and put them into component section
for sub_name, sub_schema in schema.pop("definitions", {}).items():
for sub_name, sub_schema in schema.pop("$defs", {}).items():
component = ResolvedComponent(
name=sub_name,
type=ResolvedComponent.SCHEMA,
Expand Down

0 comments on commit d1b874a

Please sign in to comment.