encode / apistar

The Web API toolkit. 🛠
https://docs.apistar.com
BSD 3-Clause "New" or "Revised" License
5.57k stars 411 forks source link

Set correct content-length for 204/304 responses with JSONResponse #589

Closed arthurk closed 6 years ago

arthurk commented 6 years ago

The HTTP Codes 204 (No-Content) and 304 (Not-Modified) currently return a Content-Length > 0 when using the JSONResponse:

http.JSONResponse(None, status_code=204)

This will serialize "None" and return a response with content-length of 4:

HTTP/1.1 204 No Content
content-length: 4
content-type: application/json

The same happens when passing an empty string and empty dict. The first parameter is always serialized, no matter what the status code.

This is very annoying when using a client written in Go, as the built-in http library will complain with errors such as 2018/06/17 23:56:11 Unsolicited response received on idle HTTP channel starting with "null"; err=<nil>

Sanic had a similar issue which was fixed a few months ago: https://github.com/channelcat/sanic/pull/1113

It would be great if there was an exception for status codes 204/304 and the response would set Content-Length to 0 and not return any body.

tomchristie commented 6 years ago

I’d suggest not returning a JSONResponse in the case of no content, right?

arthurk commented 6 years ago

You're right, for some reason I thought all my responses had to return application/json. Thanks!