I would like to have a REST API endpoint where I can post a json object or a json array of objects.
I managed to do so by redefining the create method of my ModelViewSet:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.DATA, many=False)
if serializer.is_valid():
serializer.save()
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
else:
serializer = self.get_serializer(data=request.DATA, many=True)
if serializer.is_valid():
serializer.save()
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
I used is_valid() from the serializer to know if the data contains an object or an array (many is set to True or False), but because of that I lose the serializer validation for other purposes like field validations.
Is there a better way to achieve that behaviour?
Should I instead create another function with another url to be able to post an array of objects? What is the REST way to support both operations?