Skip to content

Enhancement: use msgspec tag field ClassVar annotations in OpenAPI specs #4564

@umarbutler

Description

@umarbutler

Summary

When constructing a msgspec.Struct that has a tag field that is annotated using ClassVar, the annotations of that field are not included in the OpenAPI spec automatically generated by Litestar.

This effectively makes it impossible to document discriminator fields in Litestar-generated OpenAPI specs.

I would like to request that annotations inside ClassVars on discriminator/tag fields be included in OpenAPI specs.

Basic Example

Currently, given the below spec, Litestar will not include the annotations on the version field in the automatically generated OpenAPI spec.

"""
This is a minimal reproducible example (MRE) of a Litestar bug. To run the app, create a folder named `_mre`, place this file in it and name it `app.py`, and then run, from the parent directory of `_mre`, `python -m uvicorn _mre.app:app --reload --port 2020`.

Visit http://localhost:2020/openapi.json to see the OpenAPI schema.
"""

from typing import Literal, ClassVar, Annotated

import msgspec

from litestar import get, Request, Litestar


class Resp(msgspec.Struct, tag="1", tag_field="version"):
    version: ClassVar[Annotated[Literal["1"], msgspec.Meta(description="The version of the struct.")]] = "1"
    foo: str = "bar"


@get("/")
async def home() -> Resp:
    return Resp()


@get(path=["/openapi.json"], include_in_schema=False, sync_to_thread=True)
def get_openapi(request: Request) -> dict:
    schema = request.app.openapi_schema

    return schema.to_schema()


app = Litestar(
    [home, get_openapi],
)

if __name__ == "__main__":
    import uvicorn

    try:
        uvicorn.run(
            app="_mre:app",
            host="localhost",
            port=2020,
            reload=True,
        )

    except Exception:
        uvicorn.run(
            app=app,
            host="localhost",
            port=2020,
        )

Drawbacks and Impact

N/A

Unresolved questions

N/A

Metadata

Metadata

Assignees

No one assigned

    Labels

    EnhancementThis is a new feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions