Search code examples
pythonjsonpython-3.xpython-requestsgithub-api

Problem using GitHub api with Python dict "Problems parsing JSON"


I am trying to use the GitHub api for creating a new file. As per the documentation

this can be done via a PUT request.

I am using the requests package for making the request. The GitHub api endpoint accepts valid json objects as input, i.e. where strings are within double quotes.

My data has the following format -

{
  'message': 'Updated learn.md',
  'content': 'ZW51bTM0PT0xLjEuNAotZSBnaXQraHR0cHM6Ly9naXRodWIuY29tL29wZW50b2svT3BlbnRvay1QeXRob24tU0RLLmdpdEAwMzU4YTI0ZDM0ZTkzMjVjYzRhODNhYmQxZTVjMGJmYzQ2M2ZkMjYwI2VnZz1vcGVudG9rCnB5dHo9PTIwMTYuNApyZXF1ZXN0cz09Mi4xMC4wCgo=',
  'branch': 'master'
}

Since I am putting the data which is in the form of a Python dictionary it is having single quotes, but GitHub isn't accepting it and is giving a 400 response of "Problems parsing JSON" as shown below

{
  "message": "Problems parsing JSON",
  "documentation_url": "https://developer.github.com/v3/repos/contents/#update-a-file"
}

I have verified that the problem is because of quotes only by using postman to make the PUT request, in that case it was successful.

The correct data is shown below

{
  "message": "Updated learn.md",
  "content": "ZW51bTM0PT0xLjEuNAotZSBnaXQraHR0cHM6Ly9naXRodWIuY29tL29wZW50b2svT3BlbnRvay1QeXRob24tU0RLLmdpdEAwMzU4YTI0ZDM0ZTkzMjVjYzRhODNhYmQxZTVjMGJmYzQ2M2ZkMjYwI2VnZz1vcGVudG9rCnB5dHo9PTIwMTYuNApyZXF1ZXN0cz09Mi4xMC4wCgo=",
  "branch": "master"
}

Here is how I am making the call

def put_data_to_github(self, url, data):
    headers = {}
    headers['Authorization'] = "token " + self.auth_token
    response = requests.put(url, data=data, headers=headers)
    return response

How can I make valid JSON objects in Python so that GitHub api accepts it? How Can I achieve this?


Solution

  • You must convert your data to json before sending..

    import json
    ...
    response = requests.put(url, data=json.dumps(data), headers=headers)