litestar-org/litestar

Bug: openapi spec. generation does not respect Response status_code

Closed this issue · 2 comments

Description

When changing the status_code in a Response object for a handler the status_code used in generation stays the default one.
Looks like the Response object status_code field is not used in generation of the openapi.json
See screenshot:
image

URL to code causing the issue

No response

MCVE

from litestar import Litestar, post, Response
from litestar.status_codes import HTTP_200_OK


@post("/test")
async def test() -> Response[dict[str, str]]:
    return Response(
        {"detail": "Test succesfull"},
        status_code=HTTP_200_OK,
    )


app = Litestar(route_handlers=[test])

Steps to reproduce

1. Start the app
2. Use your favorite openapi renderer
3. Execute the endpoint, returned status is 200, status in rendered openapi is 201.

Screenshots

"![SCREENSHOT_DESCRIPTION](SCREENSHOT_LINK.png)"

Logs

No response

Litestar Version

2.9.0

Platform

  • 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

In case you are not aware, you can do this explicitly by configuring responses as shown in https://docs.litestar.dev/latest/usage/openapi/schema_generation.html.

Question to you. In your example it is just one response that is being returned, what if your route handler has more than one return, like the following. Having to parse the function body to retrieve this would be an overhead. I do not think this is an overhead the framework has to do, with this context, would you still consider this a bug?

if some_condition:
    return Response(
        {"detail": "Test succesfull"},
        status_code=HTTP_200_OK,
    )
elif some_other_condition:
    return Response(
        {"detail": "Test succesfull"},
        status_code=HTTP_201_CREATED,
    )
elif not_found:
    return Response(
        {"detail": "not found"},
        status_code=HTTP_404_NOT_FOUND,
    )

@TheZwieback as @Alc-Alcb explained, this is not really a bug. Litestar does not know what you're doing inside your functions, so you'll have to tell it.

You can set the status code on the handler like so

@post("/test", status_code=HTTP_200_OK)
async def test() -> Response[dict[str, str]]:
    return Response(
        {"detail": "Test succesfull"},
        status_code=HTTP_200_OK,
    )

which should do what you're looking for :)