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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With