diff --git a/litestar/dto/base_dto.py b/litestar/dto/base_dto.py index 2976f7ce05..83fc16ce9c 100644 --- a/litestar/dto/base_dto.py +++ b/litestar/dto/base_dto.py @@ -217,10 +217,13 @@ def create_openapi_schema( # generated transfer model type in the type arguments. transfer_model = backend.transfer_model_type generic_args = tuple(transfer_model if a is cls.model_type else a for a in field_definition.args) - return schema_creator.for_field_definition( - FieldDefinition.from_annotation(field_definition.origin[generic_args]) - ) - return schema_creator.for_field_definition(FieldDefinition.from_annotation(backend.annotation)) + annotation = field_definition.safe_generic_origin[generic_args] + else: + annotation = backend.annotation + + return schema_creator.for_field_definition( + FieldDefinition.from_annotation(annotation, kwarg_definition=field_definition.kwarg_definition) + ) @classmethod def resolve_generic_wrapper_type( diff --git a/tests/unit/test_dto/test_factory/test_integration.py b/tests/unit/test_dto/test_factory/test_integration.py index 21dc1c027f..5f7eafee1e 100644 --- a/tests/unit/test_dto/test_factory/test_integration.py +++ b/tests/unit/test_dto/test_factory/test_integration.py @@ -1003,3 +1003,58 @@ def get_users() -> WithCount[User]: assert not_none(schema.properties).keys() == {"count", "data"} model_schema = openapi.components.schemas["GetUsersUserResponseBody"] assert not_none(model_schema.properties).keys() == {"id", "name"} + + +def test_openapi_schema_for_dto_includes_body_examples(create_module: Callable[[str], ModuleType]) -> None: + module = create_module( + """ +from dataclasses import dataclass +from uuid import UUID + +from typing_extensions import Annotated + +from litestar import Litestar, post +from litestar.dto import DataclassDTO +from litestar.openapi.spec import Example +from litestar.params import Body + + +@dataclass +class Item: + id: UUID + name: str + + +body = Body( + title="Create item", + description="Create a new item.", + examples=[ + Example( + summary="Post is Ok", + value={ + "id": "3fa85f64-5717-4562-b3fc-2c963f66afa6", + "name": "Swatch", + }, + ) + ], +) + + +@post() +async def create_item(data: Annotated[Item, body]) -> Item: + return data + + +@post("dto", dto=DataclassDTO[Item]) +async def create_item_with_dto(data: Annotated[Item, body]) -> Item: + return data + + +app = Litestar(route_handlers=[create_item, create_item_with_dto]) +""" + ) + + openapi_schema = module.app.openapi_schema + item_schema = openapi_schema.components.schemas["Item"] + item_with_dto_schema = openapi_schema.components.schemas["CreateItemWithDtoItemRequestBody"] + assert item_schema.examples == item_with_dto_schema.examples