Skip to content

Instantly share code, notes, and snippets.

@auwsome
Created August 23, 2015 21:02
Show Gist options
  • Save auwsome/6814a4d48c160a81c881 to your computer and use it in GitHub Desktop.
Save auwsome/6814a4d48c160a81c881 to your computer and use it in GitHub Desktop.
Add issue in GitHub using basic authentication and token
# from http://stackoverflow.com/questions/10367859/github-api-giving-404-when-passing-json-data-with-python-urllib2
import urllib2
import json
import getpass
import base64
# Generate a token from the username and password.
# NOTE: this is a naive implementation. Store pre-retrieved tokens if possible.
username = 'pelson'
passwd = getpass.getpass() # <- this just puts a string in passwd (plaintext)
req = urllib2.Request("https://api.github.com/authorizations")
# add the username and password info to the request
base64string = base64.encodestring('%s:%s' % (username, passwd)).replace('\n', '')
req.add_header("Authorization", "Basic %s" % base64string)
data = json.dumps({"scopes":["repo"], "note":"Access to your repository."})
result = urllib2.urlopen(req, data)
result = json.loads('\n'.join(result.readlines()))
token = result['token']
#bOnce you have this token, it can be used for any "repo" scope actions. Lets add a new issue to a repository:
# add an issue to the tracker using the new token
repo = 'name_of_repo'
data = json.dumps({'title': 'My automated issue.'})
req = urllib2.Request("https://api.github.com/repos/%s/%s/issues" % (username, repo))
req.add_header("Authorization", "token %s" % token)
result = urllib2.urlopen(req, data)
result = json.loads('\n'.join(result.readlines()))
print result['number']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment