1

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?

1 Answer 1

2

Django REST Framework does not support bulk object creation by default, but there are packages out there that add support for it, such as Django REST Framework Bulk.

It can be made to work with routers with slight modifications. This should allow you to do what you are looking for.

because of that I lose the serializer validation for other purposes like field validations.

This is because you were not passing in the serializer context, which generic views do automatically.

Sign up to request clarification or add additional context in comments.

1 Comment

Just had an issue with it (github.com/miki725/django-rest-framework-bulk/issues/22), but this is exactly what I was looking for, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.