Skip to content

Commit

Permalink
feat: Support strings in media_type for ResponseSpec (#3729)
Browse files Browse the repository at this point in the history
  • Loading branch information
provinzkraut authored Sep 12, 2024
1 parent 6d49fc2 commit aba12c7
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 2 deletions.
7 changes: 6 additions & 1 deletion litestar/_openapi/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,12 @@ def create_additional_responses(self) -> Iterator[tuple[str, OpenAPIResponse]]:
content: dict[str, OpenAPIMediaType] | None
if additional_response.data_container is not None:
schema = schema_creator.for_field_definition(field_def)
content = {additional_response.media_type: OpenAPIMediaType(schema=schema, examples=examples)}
media_type = additional_response.media_type
content = {
get_enum_string_value(media_type)
if not isinstance(media_type, str)
else media_type: OpenAPIMediaType(schema=schema, examples=examples)
}
else:
content = None

Expand Down
2 changes: 1 addition & 1 deletion litestar/openapi/datastructures.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class ResponseSpec:
"""Generate examples for the response content."""
description: str = field(default="Additional response")
"""A description of the response."""
media_type: MediaType = field(default=MediaType.JSON)
media_type: MediaType | str = field(default=MediaType.JSON)
"""Response media type."""
examples: list[Example] | None = field(default=None)
"""A list of Example models."""
8 changes: 8 additions & 0 deletions tests/unit/test_openapi/test_responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -361,6 +361,7 @@ class UnknownError(TypedDict):
401: ResponseSpec(data_container=AuthenticationError, description="Authentication error"),
500: ResponseSpec(data_container=ServerError, generate_examples=False, media_type=MediaType.TEXT),
505: ResponseSpec(data_container=UnknownError),
900: ResponseSpec(data_container=UnknownError, media_type="application/vnd.custom"),
}
)
def handler() -> DataclassPerson:
Expand Down Expand Up @@ -398,6 +399,13 @@ def handler() -> DataclassPerson:
assert third_response[0] == "505"
assert third_response[1].description == "Additional response"

fourth_response = next(responses)
assert fourth_response[0] == "900"
assert fourth_response[1].description == "Additional response"
custom_media_type_content = fourth_response[1].content.get("application/vnd.custom") # type: ignore[union-attr]
assert custom_media_type_content
assert isinstance(custom_media_type_content, OpenAPIMediaType)

with pytest.raises(StopIteration):
next(responses)

Expand Down

0 comments on commit aba12c7

Please sign in to comment.