Django-rest-framework: JSONRenderer does not return a valid json response when `data=None`

Created on 13 Jun 2018  ·  4Comments  ·  Source: encode/django-rest-framework

Steps to reproduce

@permission_classes((AllowAny, ))
class Viewset(viewsets.ViewSet):
    renderer_classes = (JSONRenderer, )
    def list(self, request, *args, **kwargs):
        return Response()

Expected behavior

A valid json response body like null or {}

Actual behavior

No Content-Type header set and an empty response is returned - particularly painful when making requests with jquery's ajax(). It throws an parseerror and rejects the promise on a success response with an empty body. See here https://stackoverflow.com/a/6186905

PR here: https://github.com/encode/django-rest-framework/pull/6027

Most helpful comment

It looks like the Content-Type header is deleted on an empty renderer response (line 80)
https://github.com/encode/django-rest-framework/blob/master/rest_framework/response.py#L72

All 4 comments

Just a quick clarification.. I may not be recreating your exact setup, but a quick, manual test shows that the Content-Type header is correctly set to application/json.

As to the empty response, I'm inclined to agree with @kltdwrds. I don't know if the spec allows an empty body, however, both JavaScript's JSON.parse and Python's json.loads fail to decode an empty string.

That is to say, data=None should be encoded as null.


On second thought, the current behavior makes sense. Although JSON.parse and json.loads do fail, it's the responsibility of the client to check the content type before parsing. If anything, this is a bug in jQuery.

hmm I'm using

from rest_framework import viewsets
from rest_framework.renderers import JSONRenderer
from rest_framework.response import Response

Not sure where the Content-Type header gets set, but I just confirmed it missing from responses using the example above.

It looks like the Content-Type header is deleted on an empty renderer response (line 80)
https://github.com/encode/django-rest-framework/blob/master/rest_framework/response.py#L72

Our current behavior for return Response() is intentional. Although returning null would also be valid, it's more typical that we need a way to return an empty response with no content type. I'd probably rather we leave things as they are for now.

Was this page helpful?
0 / 5 - 0 ratings