Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django REST framework JSONParser().parse(request) raising error

In Django view, I am trying this-

@csrf_exempt
def customer_list(request):
    """
    List all customers, or create a new customer.
    """
    if request.method == 'GET':
        snippets = Customer.objects.all()
        serializer = CustomerSerializer(snippets, many=True)
        return JsonResponse(serializer.data, safe=False)

    elif request.method == 'POST':
        data = JSONParser().parse(request)
        serializer = CustomerSerializer(data=data)
        if serializer.is_valid():
            serializer.save()
            return JsonResponse(serializer.data, status=201)
        return JsonResponse(serializer.errors, status=400)

On posting data from postman,I get

JSON parse error - Expecting value: line 1 column 1 (char 0)

like image 812
Avin Mathew Avatar asked Sep 17 '25 07:09

Avin Mathew


1 Answers

The problem is that you are passing the entire request object to the JSON parser, instead of the body that contains the actual JSON content.

But you shouldn't do this yourself anyway. Let DRF do it for you.

from rest_framework.decorators import api_view
from rest_framework.response import Response

@api_view()
def customer_list(request):
    """
    List all customers, or create a new customer.
    """
    if request.method == 'GET':
        snippets = Customer.objects.all()
        serializer = CustomerSerializer(snippets, many=True)
        return Response(serializer.data)

    elif request.method == 'POST':
        serializer = CustomerSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=201)
        return Response(serializer.errors, status=400)

Or even better, use a class-based view which literally includes all this functionality for you already:

from rest_framework import generics

class CustomerList(generics.ListCreateAPIView):
     model = Customer
     serializer_class = CustomerSerializer

That's all you need.

like image 126
Daniel Roseman Avatar answered Sep 18 '25 21:09

Daniel Roseman