Commit Graph

2 Commits

Author SHA1 Message Date
pre-commit-ci-lite[bot] 68a08572c1
🎨 Auto format 2026-02-15 11:12:42 +00:00
Charisn 05d1effc23 Fix UnboundLocalError in OpenAPI schema generation with custom response classes
When a route uses a custom response class whose __init__ does not expose
a status_code parameter with an int default, and the route decorator
does not specify an explicit status_code, the status_code local variable
in get_openapi_path() was never assigned. This caused an
UnboundLocalError at the point where status_code is used to populate
the operation responses dict.

The bug does not surface with standard Starlette response classes
(JSONResponse, HTMLResponse, PlainTextResponse, StreamingResponse, etc.)
because they all declare status_code: int = 200 (or 307 for redirects)
in their __init__ signatures. It triggers when users define custom
response classes that wrap or omit the status_code parameter, e.g.:

    class CustomResponse(Response):
        def __init__(self, content, **kwargs):
            super().__init__(content=content, status_code=200, **kwargs)

    @app.get("/items", response_class=CustomResponse)
    async def get_items(): ...

Accessing /openapi.json or /docs would crash with:
    UnboundLocalError: cannot access local variable 'status_code'

Fix: initialize status_code = "200" before the conditional block so it
always has a safe default. The existing branches that extract status_code
from the route or from the response class signature still override this
default when applicable.
2026-02-15 13:09:14 +02:00