Thanks to visit codestin.com
Credit goes to github.com

Skip to content

model serialization / validation schemas leaking into schema #7209

@commonism

Description

@commonism

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

As already discussed in fastapi/fastapi#10019 (comment) current pydantic defines different models in the schema when using both modes (validation/serialization) on a model - "{}Input" & "{}Output".
FastAPI started using mode=serialization for response models in 0.101 - bringing this issue up fastapi/fastapi#10039 fastapi/fastapi#10041.

This breaks all existing clients and invalidates every client code written due to changing the class name.
Current pydantic choose to change the name of the models again - adding a "-" before the Input/Output.

I understand there is a requirement to have different personalities, but the schema should be limited to a single personality - validation.

Example Code

import io

import yaml

from pydantic import BaseModel
from pydantic.json_schema import models_json_schema


class Pet(BaseModel):
    name: str
    weight: int | None
    color: str | None = None

data = models_json_schema([(Pet,"serialization"),(Pet,"validation")])
f = io.StringIO()
for d in data:
    for k,v in d.items():
        print(yaml.dump(v, f, indent=4))
f.seek(0)
print(f.read())
$ref: '#/$defs/PetOutput'
$ref: '#/$defs/PetInput'
PetInput:
    properties:
        color:
            anyOf:
            -   type: string
            -   type: 'null'
            default: null
            title: Color
        name:
            title: Name
            type: string
        weight:
            anyOf:
            -   type: integer
            -   type: 'null'
            title: Weight
    required:
    - name
    - weight
    title: Pet
    type: object
PetOutput:
    properties:
        color:
            anyOf:
            -   type: string
            -   type: 'null'
            default: null
            title: Color
        name:
            title: Name
            type: string
        weight:
            anyOf:
            -   type: integer
            -   type: 'null'
            title: Weight
    required:
    - name
    - weight
    - color
    title: Pet
    type: object

Python, Pydantic & OS Version

pydantic version: 2.2.1
        pydantic-core version: 2.6.1
          pydantic-core build: profile=release pgo=true
                 install path: ~/venv/openapi3/lib/python3.10/site-packages/pydantic
               python version: 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0]
                     platform: Linux-6.2.0-26-generic-x86_64-with-glibc2.35
     optional deps. installed: ['email-validator', 'typing-extensions']

Selected Assignee: @adriangb

Metadata

Metadata

Assignees

Labels

bug V2Bug related to Pydantic V2

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions