litestar icon indicating copy to clipboard operation
litestar copied to clipboard

Bug: Invalid OpenAPI schema keys generated for generic types

Open thiagozf opened this issue 7 months ago • 0 comments

Description

According to OpenAPI Specification, schemas MUST use keys that match the regular expression: ^[a-zA-Z0-9\.\-_]+$.

When using generics, the generated schema key will contain square brackets.

This is a problem because some tools won't allow invalid OpenAPI schemas to be uploaded.

URL to code causing the issue

No response

MCVE

from litestar import Litestar, get
from pydantic import BaseModel
from typing import Generic, TypeVar

T = TypeVar("T", bound=BaseModel)


class Wrapper(BaseModel, Generic[T]):
    data: T


class Foo(BaseModel):
    bar: str


@get(path="/")
async def foobar() -> Wrapper[Foo]:
    return Wrapper(data=Foo(bar="bar"))


app = Litestar([foobar])

Steps to reproduce

1. Run the provided MCE
2. Visit `/schema/openapi.json`
3. Notice the schema key generated for the response is `Wrapper[Foo]`


{
  "info": {
    "title": "Litestar API",
    "version": "1.0.0"
  },
  "openapi": "3.1.0",
  "servers": [
    {
      "url": "/"
    }
  ],
  "paths": {
    "/": {
      "get": {
        "summary": "Foobar",
        "operationId": "Foobar",
        "responses": {
          "200": {
            "description": "Request fulfilled, document follows",
            "headers": {

            },
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Wrapper[Foo]"
                }
              }
            }
          }
        },
        "deprecated": false
      }
    }
  },
  "components": {
    "schemas": {
      "Foo": {
        "properties": {
          "bar": {
            "type": "string"
          }
        },
        "type": "object",
        "required": [
          "bar"
        ],
        "title": "Foo"
      },
      "Wrapper[Foo]": {
        "properties": {
          "data": {
            "$ref": "#/components/schemas/Foo"
          }
        },
        "type": "object",
        "required": [
          "data"
        ],
        "title": "Wrapper[Foo]"
      }
    }
  }
}

Screenshots

"![SCREENSHOT_DESCRIPTION](SCREENSHOT_LINK.png)"

Logs

No response

Litestar Version

2.8.2

Platform

  • [X] Linux
  • [ ] Mac
  • [ ] Windows
  • [ ] Other (Please specify in the description above)

[!NOTE]
While we are open for sponsoring on GitHub Sponsors and OpenCollective, we also utilize Polar.sh to engage in pledge-based sponsorship.

Check out all issues funded or available for funding on our Polar.sh dashboard

  • If you would like to see an issue prioritized, make a pledge towards it!
  • We receive the pledge once the issue is completed & verified
  • This, along with engagement in the community, helps us know which features are a priority to our users.
Fund with Polar

thiagozf avatar Jul 15 '24 20:07 thiagozf