2

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!

1 Answer 1

8

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.