If you want to post a list you have to pass in JSON
encoded data.
headers = {"Token": "35754sr7cvd7ryh454"}
recipients = [{'name': 'Ut est sed sed ipsa',
'email': '[email protected]',
'group': 'signers'},
{'name': 'Development Ltda.',
'email': '[email protected]',
'group': 'signers'}
]
requests.post(url, json=recipients, headers=headers)
requests.post(url, json=recipients, headers=headers)
Use json
keyword argument (not data
) so the data is encoded to JSON
and the Content-Type header
is set to application/json
.
By default, Django Rest Framework assumes you are passing it a single object. To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True
flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.
To do it, you'll have to override the .create()
method of your view:
def create(self, request, *args, **kwargs):
many = True if isinstance(request.data, list) else False
serializer = self.get_serializer(data=request.data, many=many)
serializer.is_valid(raise_exception=True)
self.perform_create(serializer)
headers = self.get_success_headers(serializer.data)
return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers)
Documentation: https://www.django-rest-framework.org/api-guide/serializers/#dealing-with-multiple-objects