Skip to content

Missing #/components/schemas/LevelOne when creating msgspec.Struct-based class whose attributes are also msgspec.Struct-based class #117

@vhbui02

Description

@vhbui02

In short, nested msgspec.Struct simply doesn't work:

# .env.example
QUART_SCHEMA_CONVERSION_PREFERENCE=msgspec
# test.py
class LevelOne(msgspec.Struct):
  a: int
  b: str

class LevelTwo(msgspec.Struct):
  lvl_one: LevelOne

#/components/schemas/LevelOne can't be found in /openapi.json

I've identified the code which leads to this behavior:

# quart_schema/conversion.py
# ...
def model_schema(
    model_class: type[Model],
    *,
    preference: str | None = None,
    schema_mode: JsonSchemaMode = "validation",
) -> dict:
    if _use_pydantic(model_class, preference):
        return TypeAdapter(model_class).json_schema(
            ref_template=PYDANTIC_REF_TEMPLATE, mode=schema_mode
        )
    elif _use_msgspec(model_class, preference):
        _, schema = schema_components([model_class], ref_template=MSGSPEC_REF_TEMPLATE)
        return list(schema.values())[0]
    elif not PYDANTIC_INSTALLED and not MSGSPEC_INSTALLED:
        raise TypeError(
            f"Cannot create schema for {model_class} - try installing msgspec or pydantic"
        )
    else:
        raise TypeError(f"Cannot create schema for {model_class}")
# ...

I see that you omit the definitions when msgspec is used. I've tried to add it but no LevelOne is found (not to mention sometimes circular dependency occurs). Is this behavior the way it is? I can workaround with Pydantic but I loved the performance gain by msgspec.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions