user1079404
user1079404

Reputation: 308

Creating webhook using Github API isn't working in Django using requests

I am using the following code to try and create a webhook for a repository that I own. However I keep getting the following response:

{u'documentation_url': u'https://developer.github.com/v3', 
 u'message': u'Body should be a JSON Hash'}

The code:

hook = {u'name': u'web', u'active': True, u'config': {u'url': u'http://my/payload/destination'}}
t = json.JSONEncoder().encode(hook)
p = requests.post('https://api.github.com/repos/:user/:repo/hooks', params=t, headers={'content-type': 'application/json', 'Authorization': 'token ' + token})

And here is the output of t:

{"active": true, "config": {"url": "http://my/payload/desination"}, "name": "web"}

And the authorization token in the header is formatted as such:

token REDACTED

I know this SHOULD work, so I went to http://www.hurl.it/ using the exact same info as above, and it was successful. Any idea why this is happening?

Upvotes: 0

Views: 1144

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121306

You are not providing a POST body; params is for URL query parameters. Use the data argument instead:

p = requests.post(
    'https://api.github.com/repos/:user/:repo/hooks', data=t, 
    headers={'content-type': 'application/json', 'Authorization': 'token ' + token})

params puts the parameters after the ? in the URL instead.

As of requests version 2.4.2 you can also leave the JSON encoding to the requests.post() call; just pass in the payload to be encoded as the json keyword argument. The correct Content-Type header will be added for you:

hook = {u'name': u'web', u'active': True, u'config': {u'url': u'http://my/payload/destination'}}
p = requests.post(
    'https://api.github.com/repos/:user/:repo/hooks', 
    json=hook, headers={'Authorization': 'token ' + token})

Upvotes: 3

Related Questions