Hi,
we're running Python 3.7.3 with FastAPI 0.27.2 and have the following API definition (simplified):
app.post("/url", status_code = HTTP_204_OK)
async def set_data(data: Data) -> None:
await db.set_data(data)
We return a 204 and return nothing in the body but we see that null is returned with a content length of 4. The client expect content-length = 0 for a 204 response. Can this please be fixed?
Thanks,
Daniel
FastAPI by default returns a JSONResponse and since this commit if I'm correct https://github.com/encode/starlette/commit/1654a48fa4f6edf5a4fc5dab118ef53ae0ef2ead Starlette return null for a empty JSONResponse
you can easily fix with
return Response(status_code=HTTP_204_NO_CONTENT)
To add to @euri10 's point, you can similarly fix this via:
from starlette.responses import Response
@app.post("/url", status_code = HTTP_204_OK, response_class=Response)
async def set_data(data: Data) -> None:
await db.set_data(data)
Still baffled about the null return, but workaround works so I'll close the ticket.
Thanks
Still baffled about the null return, but workaround works so I'll close the ticket.
Thanks
I agree, maybe worth a ping upstream as the current API let you return a 204 with content, which shouldn't be possible
Thanks for the help @euri10 and @dmontagu !
@CanD42 the reason for this is because, by default, FastAPI takes whatever you return and puts it in a JSON response. With all the headers, converting the data to valid JSON, etc.
And in Python, any function that doesn't return something, implicitly returns a None. And the equivalent of None in JSON is null. That's a special case where it isn't very intuitive but is actually because of the way the language works. And the fact that FastAPI takes automatically whatever "returned" by the function and puts it in JSON, instead of requiring you to return the instance of a Response class or similar.
Thanks for reporting back and closing the issue!
Nevertheless, this is a bug that should be fixed because a 204 with a non-empty body is in violation of the HTTP RFC.
https://tools.ietf.org/html/rfc2616#section-10.2.5
The 204 response MUST NOT include a message-body, and thus is always
terminated by the first empty line after the header fields.
Most helpful comment
I agree, maybe worth a ping upstream as the current API let you return a 204 with content, which shouldn't be possible