Why request.post does not accept dictionary

Screen Link: https://app.dataquest.io/m/110/challenge%3A-working-with-the-reddit-api/6/upvoting-a-comment

Why following does not work
My Code:
Option 1:

headers = {"Authorization": "bearer 13426216-4U1ckno9J5AiK72VRbpEeBaMSKk", "User-Agent": "Dataquest/1.0"}
url = 'https://oauth.reddit.com/api/vote'
upvote = {'dir':1, 'id':'d16y4ry'}

status = requests.post(url, data=upvote), headers=headers).status_code

or even this Option 2:

headers = {"Authorization": "bearer 13426216-4U1ckno9J5AiK72VRbpEeBaMSKk", "User-Agent": "Dataquest/1.0"}
url = 'https://oauth.reddit.com/api/vote'
upvote = {'dir':1, 'id':'d16y4ry'}

status = requests.post(url, data=json.dumps(upvote), headers=headers).status_code

What I expected to happen:
Expected that data accepts dictionary so Option 1 should work. If it does not accept dictionary and requires JSON (which was not clear from the Requests 2.25.0) then it should accept json which Option 2 would convert into

This is what actually works:

headers = {"Authorization": "bearer 13426216-4U1ckno9J5AiK72VRbpEeBaMSKk", "User-Agent": "Dataquest/1.0"}
url = 'https://oauth.reddit.com/api/vote'
upvote = {'dir':1, 'id':'d16y4ry'}

status = requests.post(url, json=json.upvote, headers=headers).status_code
1 Like

So, I have been trying to look into this for some time, and I haven’t yet found a concrete answer.

But, based on what I have found so far -

  • Your Option 1 doesn’t work because the reddit API expects the data in JSON format. So, data=upvote is invalid.
  • Your Option 2 doesn’t work because you most likely need to also modify headers to indicate that the Content-Type is json. You can do this by adding "Content-Type":"application/json" to headers. However, instead of the 400 status code, this produces a 401 status code which indicates some sort of unauthorized authentication. I think the latter happens because of what DQ expects from the POST request here because of how they have set up this mock environment on their backend. I can’t be sure however.
  • The last one is the best possible option, even as per the docs, as it handles the encoding itself without us having to worry about it.
2 Likes