David542
David542

Reputation: 110173

DRF failing when content type = json

I am using Django Rest Framework with an angularJS application and it works fine. However, when I try using python requests to communicate to any of its endpoints I get an error whenever I set the Content-Type = "application/json". Here's an example:

import requests
res = requests.post(url, data=data, headers={
    "Authorization": "Bearer %s" % token_json['access'],
    "Content-Type": "application/json"
})

# And in my django view
path = request.data['path']

{'detail': 'JSON parse error - Expecting value: line 1 column 1 (char 0)'}

However, as soon as I remove the Content-Type: application/json line, things start working -- though my json isn't properly passed (for example, 2 is passed as the string "2" instead of the number 2).

Upvotes: 1

Views: 361

Answers (1)

David542
David542

Reputation: 110173

Use the json parameter, which has been available since version 2.4.2.

An example would be:

import requests
res = requests.post(url, json=data, headers={
    "Authorization": "Bearer %s" % token_json['access']
})

Notice how we're setting json=data instead of data=data, and omitting the Content-Type header. It automatically encodes the python object you pass using json.dumps, and also sets the correct Content-Type header for you too.

Upvotes: 1

Related Questions