FastAPI – Cannot use `Response` as a return type when `status_code` is set to 204

Question:

I’ve been using the following code for my /healthz:

@router.get("/healthz", status_code=status.HTTP_204_NO_CONTENT, tags=["healthz"],
            summary="Service for 'Health Check'",
            description="This entrypoint is used to check if the service is alive or dead.",
            # include_in_schema=False
            )
def get_healthz() -> Response:
    return Response(status_code=status.HTTP_204_NO_CONTENT)

This has been working since some years ago.

Today I updated FastAPI from 0.88.0 to 0.89.0 and now I get AssertionError: Status code 204 must not have a response body. The full tracebakc can be seen below:

Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 1234, in _handle_fromlist
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "......../src/routers/healthz.py", line 20, in <module>
    @router.get("/healthz", status_code=status.HTTP_204_NO_CONTENT, tags=["healthz"],
     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/Users/..../.local/share/virtualenvs/........../lib/python3.11/site-packages/fastapi/routing.py", line 633, in decorator
    self.add_api_route(
  File "/Users/..../.local/share/virtualenvs/......../lib/python3.11/site-packages/fastapi/routing.py", line 572, in add_api_route
    route = route_class(
            ^^^^^^^^^^^^
  File "/Users/...../.local/share/virtualenvs/....../lib/python3.11/site-packages/fastapi/routing.py", line 396, in __init__
    assert is_body_allowed_for_status_code(
AssertionError: Status code 204 must not have a response body
python-BaseException

Here:
enter image description here

My question is:

Is this a bug from the version 0.89.0 , or should I write the /heathz In a different way?

Even with return Response(status_code=status.HTTP_204_NO_CONTENT, content=None) is failling.

Changelog of 0.89.0:
enter image description here

Thanks

Asked By: Rui Martins

||

Answers:

Answered By: Rui Martins
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.