lfbet lfbet - 5 months ago 53
Python Question

Issue translating curl PUT to Python requests: "Problems parsing JSON"

I'm looking to use the Python requests library to create a new file in a GitHub repository. Entering the following in the command line works for me (replacing

LOGIN
and
TOKEN
as appropriate):

curl -X PUT -d '{"path": "testfile.txt", "message": "test", "content": "aGVsbG8y"}' https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt\?access_token\=TOKEN


But I keep running into the "Problems parsing JSON" error (status code 400) when attempting the same with requests:

data = {
"message": "test",
"content": "aGVsbG8y",
"path": "testfile.txt"
}
url = "https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt?access_token={}".format(TOKEN)
response = requests.put(url, data=data)


Any hints as to what I'm doing differently? I've checked through the similar questions, but haven't found the right tweak. Thanks!

Answer

Because just passing a data parameter automatically sends your dictionary as form encoded parameters. Instead pass it as JSON

import json
data = {
    "message": "test",
    "content": "aGVsbG8y",
    "path": "testfile.txt"
}
url = "https://api.github.com/repos/LOGIN/testrepo/contents/testfile.txt?access_token={}".format(TOKEN)
response = requests.put(url, data=json.dumps(data))

Or if you're using at least version 2.4.2 you can do it like this:

response = requests.put(url, json=data)
Comments