New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
fix(open-api): support generic types for OpenAPI schema generation #2463
Conversation
Predicates like 'is_dataclass_class' did not handle generic type annotations like Foo[int]. By getting the origin, if present, this case of generic annotations are also handled.
The reason the generic types were not working was because For the following handlers, the resulting schema will be as follows: from typing import Generic, TypeVar
from dataclasses import dataclass
from litestar import get, post
from litestar.app import Litestar
T = TypeVar("T")
@dataclass
class Foo(Generic[T]):
foo: T
@get("/")
async def get_foo() -> Foo[int]:
return Foo(1)
@get("/no-type")
async def get_foo_no_type() -> Foo:
return Foo(1)
@post("/generic-type")
async def get_foo_generic(foo: Foo[T]) -> Foo[T]:
return foo
app = Litestar([get_foo, get_foo_no_type, get_foo_generic]) |
Generic Pydantic models do not work currently due to this issue. I just realized (as I was typing this :P) a simple workaround for this would be to just get the I'll add this in along with tests to this PR itself. |
878f443
to
edab314
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Sorry, ran out of time to complete my review, but a couple of comments so far. I'll pick up again later. Cheers!
@peterschutt first of all, thank you for such a fantastic analysis! Yeah so the reason for this is that in def _substitute_typevars(obj: Any, typevar_map: Mapping[Any, Any]) -> Any:
params = getattr(obj, "__parameters__", None)
if params: # this was `if params is None` before but list[str].__parameters__ returns an empty tuple instead
args = tuple(_substitute_typevars(typevar_map.get(p), typevar_map) for p in params)
return obj[args]
.... This also resolves the issue related to |
The fix for handling empty parameters tuples fixed the underlying issue.
Oh, of course! Good stuff:) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Nice work, thanks!
* refactor: _get_type_schema_name receive FieldDefinition Removes the need to call `get_args()` on the annotation by passing the field def. directly through. * Removes an unneeded call to `get_origin_or_inner_type()` * Fix type error.
Kudos, SonarCloud Quality Gate passed! |
Documentation preview will be available shortly at https://litestar-org.github.io/litestar-docs-preview/2463 |
Pull Request Checklist
Description
Close Issue(s)