12

I try to build API with Django rest framework

And I got Object of

type 'TypeError' is not JSON serializable

What should I do to fix?

Here's my view.py

class NewsViewSet(viewsets.ModelViewSet):
    queryset = News.objects.all()
    serializer_class = NewsSerializer

    def list(self, request, **kwargs):
        try:
            nba = query_nba_by_args(**request.query_params)
            serializer = NewsSerializer(nba['items'], many=True)
            result = dict()
            result['data'] = serializer.data
            result['draw'] = nba['draw']
            result['recordsTotal'] = nba['total']
            result['recordsFiltered'] = nba['count']
            return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)

        except Exception as e:
            return Response(e, status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
mohammadjh
  • 722
  • 5
  • 12
Ray
  • 193
  • 1
  • 1
  • 11

4 Answers4

12

Django cannot convert Exception object to JSON format and raise error. To fix it you should convert error to string and pass result to response:

except Exception as e:
    return Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
neverwalkaloner
  • 46,181
  • 7
  • 92
  • 100
  • I got error "'NoneType' object is not subscriptable" when I entered http://127.0.0.1:8000/api/news/ but I can get data when i entered http://127.0.0.1:8000/api/news/1 How can i get complete data from http://127.0.0.1:8000/api/news/ – Ray Mar 28 '18 at 15:09
  • @Ray try `return Response(result, status=status.HTTP_200_OK)` instead of `return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)` – neverwalkaloner Mar 28 '18 at 15:13
0

first

import json
from django.http import HttpResponse

Change line

  return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)

for this

   return HttpResponse(json.dumps(result),content_type="application/json")

or use

 from django.http import JsonResponse

 return JsonResponse(json.dumps(result))
blacker
  • 768
  • 1
  • 10
  • 13
0

Python exceptions are not json serializable. It's failing in try because of some connection or content unavailable issue, then going into except block where you are passing exception e as it is to Response() so that is creating the issue. Solution - check the URL and also in except block convert exception e to string and pass to Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None).

-2
except Exception as exception:
    return HttpResponse(exception)
remote007
  • 41
  • 2