Home > other >  Api testing issue with Json
Api testing issue with Json

Time:01-15

Im new to the Django Rest Framework i think i did the serializer thing and views correctly, and it looks like this:

class MyAnimalSerializer(serializers.ModelSerializer):
    class Meta:
        model = MyAnimal
        fields = ('id', 'user', 'name', 'animal', 'race', 'birthyear',
                  'color', 'sex', 'height', 'father', 'mother', 'doc_num',)

class MyAnimalFormApi(APIView):

    permission_classes = (AllowAny,)

    def post(self, request):
        serializer = MyAnimalSerializer(data=request.data, many=True)
        if serializer.is_valid():
            serializer.save()
            return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK)
        else:
            return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST)

Now when i try to test it with Postman

{ "data": { "name": "name", "animal": "dog"}, }

i get { "detail": "JSON parse error - Expecting property name enclosed in double quotes: line 1 column 47 (char 46)" }

but it is enclosed in double quotes. Do you have any idea what's wrong or how to make it accessible only via {"name": "", "animal": ""} instead of nesting dictionary?

CodePudding user response:

Remove the trailing comma.

>>> json.loads('{ "data": { "name": "name", "animal": "dog"}, }')
...
JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 47 (char 46)

Should be this instead.

{ "data": { "name": "name", "animal": "dog"} }
>>> json.loads('{ "data": { "name": "name", "animal": "dog"} }')
{'data': {'name': 'name', 'animal': 'dog'}}

CodePudding user response:

The reason you get this error i believe, is because you need to dump the json data before you send it in your request.

data = json.dumps(payload)

Where payload is your data dictionary. This will convert it into a string.

  •  Tags:  
  • Related