Skip to content

Difference between TypeAdapter().json_schema and BaseModel.model_json_schema #9210

@Mark90

Description

@Mark90

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

When presented with an annotated type with multiple Field objects that set json_schema_extra, TypeAdapter seems to combine them whereas BaseModel does not.

I was used to the behavior of BaseModel of not combining anything, which I can understand because merging json schema's is non-trivial in the case of conflicting keys. I would expect TypeAdapter to follow the same rules.

Below code example outputs the following

BaseModel.model_json_schema
{'properties': {'v': {'key2': 'value2', 'title': 'V', 'type': 'string'}},  # only contains key2
 'required': ['v'],
 'title': 'Foo',
 'type': 'object'}

TypeAdapter().json_schema
{'key1': 'value1', 'key2': 'value2', 'type': 'string'}  # contains key1 and key2

Example Code

from pprint import pprint
from typing import Annotated

from pydantic import TypeAdapter, BaseModel, Field

MyStr = Annotated[
  str, 
  Field(json_schema_extra={'key1': 'value1'}), 
  Field(json_schema_extra={'key2': 'value2'})
]
class Foo(BaseModel):
    v: MyStr


print("BaseModel.model_json_schema")
pprint(Foo.model_json_schema())
print("TypeAdapter().json_schema")
pprint(TypeAdapter(MyStr).json_schema())

Python, Pydantic & OS Version

pydantic version: 2.6.4
        pydantic-core version: 2.16.3
          pydantic-core build: profile=release pgo=true
                 install path: /Users/mark/.pyenv/versions/3.12.1/envs/312pydantic26/lib/python3.12/site-packages/pydantic
               python version: 3.12.1 (main, Jan  2 2024, 17:23:05) [Clang 15.0.0 (clang-1500.0.40.1)]
                     platform: macOS-14.4.1-arm64-arm-64bit
             related packages: typing_extensions-4.11.0
                       commit: unknown

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions