Ruben
Ruben

Reputation: 1091

django rest api: JSON parse error - No JSON object could be decoded

I'm using postman to create a POST request to my django view

@csrf_exempt
@api_view(['POST'])
def create_user(request):
    data = JSONParser().parse(request)
    serializer = CaretakerSerializer(data=data)
    if serializer.is_valid():
        serializer.save()
        return JSONResponse(serializer.data, status=201)
    return JSONResponse(serializer.errors, status=400)

but I get the following error:

{
  "detail": "JSON parse error - No JSON object could be decoded"
}

When trying to print my request.body I get the following:

------WebKitFormBoundaryrg1JNLvBOEfjkQAT
Content-Disposition: form-data; name="name"

Rubencito
------WebKitFormBoundaryrg1JNLvBOEfjkQAT
Content-Disposition: form-data; name="email"

[email protected]
------WebKitFormBoundaryrg1JNLvBOEfjkQAT--

This is the postman screenshot:

enter image description here

Upvotes: 3

Views: 8499

Answers (1)

serg
serg

Reputation: 111365

Well you are not sending json, you are sending regular POST request with name/value pairs.

You need to switch postman to "raw" format and type something like {"name": "X", "email":"Y"}

Then on a python side you can read it as json.loads(request.body)

Upvotes: 5

Related Questions