📝 Fix `Reference | Schema` conflict in our OpenAPI definitions (#1491)
Currently we mix up two different things in the code:
Schema with $ref set and a Reference object with $ref set.For example, this code:
import pydantic
from pydantic.json_schema import GenerateJsonSchema
from dmr.openapi.mappers.schema_loader import load_schema
class WithDialect(GenerateJsonSchema):
def generate(self, schema, mode='validation'):
json_schema = super().generate(schema, mode=mode)
json_schema['$schema'] = self.schema_dialect
return json_schema
class Address(pydantic.BaseModel):
model_config = pydantic.ConfigDict(
json_schema_extra={'$anchor': 'address', '$comment': 'Postal address'},
)
city: str
class User(pydantic.BaseModel):
model_config = pydantic.ConfigDict(
json_schema_extra={'$comment': 'Internal note for schema readers'},
)
name: str = pydantic.Field(json_schema_extra={'$comment': 'Display name'})
address: Address = pydantic.Field(
default=Address(city='Moscow'),
description='Where the user lives',
)
raw = pydantic.TypeAdapter(User).json_schema(
ref_template='#/components/schemas/{model}',
schema_generator=WithDialect,
)
defs = raw.pop('$defs')
Produces this schema:
{
"$comment": "Internal note for schema readers",
"$schema": "https://json-schema.org/draft/2020-12/schema",
"properties": {
"name": {"$comment": "Display name", "title": "Name", "type": "string"},
"address": {
"$ref": "#/components/schemas/Address",
"default": {"city": "Moscow"},
"description": "Where the user lives"
}
},
"required": ["name"], "title": "User", "type": "object"
}
But, we would load it as
Reference object in load_schema and we will loose default and description. Which are Schema object attributes.So, what we need to do?
1. Analyze all places where
Reference can't be even used based on https://spec.openapis.org/oas/v3.2.0.html We need to grep this page with | Reference Object and check that we don't have more places that can hold Reference objects2. We must distinguish
$ref in potential Schema objects and Reference objects3. We must change how our
maybe_resolve_reference works to also resolve $ref in Schema objects, where we need it. Maybe we create a new type ResolvedSchema and use it in places where we expect flat schemas, so we won't forget to call maybe_resolve_reference#bug #good_first_issue #help_wanted #openapi #opensource_september #django_modern_rest
sent via relator