Thursday, May 3, 2012

Sampling GitHub API v3 in Python

Eucalyptus is in the process of moving code to GitHub, and this week I finally decided to look at the available API tools for working with GitHub.  I wanted a tool written in python, since that would be the fastest for me to extend, and I found github2.  Unfortunately, that homepage had a prominent warning that the code only worked with GitHub's old APIs, which were being turned off this week.  So I decided to investigate what I could do from scratch in a small amount of code.  I had already started using restkit in jiranemo, so that seemed to be a reasonable starting point.  Here's what I came up with:

import json
from restkit import Resource, BasicAuth, Connection, request
from socketpool import ConnectionPool

pool = ConnectionPool(factory=Connection)

# Add your username and password here, or prompt for them
auth=BasicAuth(user, password)

# Use your basic auth to request a token
# This is just an example from
authreqdata = { "scopes": [ "public_repo" ], "
                note": "admin script" }
resource = Resource('', 
                    pool=pool, filters=[auth])
response ={ "Content-Type": "application/json" }, 
token = json.loads(response.body_string())['token']

Once you have a token, you can pass that in the Authorization header
You can store this in a cache and throw away the user/password
This is just an example query.  See 
for more about the url structure
resource = Resource('', pool=pool)
headers = {'Content-Type' : 'application/json' }
headers['Authorization'] = 'token %s' % token
response = resource.get(headers = headers)
repos = json.loads(response.body_string())

There's not any magic in this code, but it took a couple of reads to wade past all of the OAuth talk in github's docs and realize that for a simple browserless tool, you can avoid using OAuth libraries altogether and still not have to store a hard-coded password.


  1. Free easy & simple way to learn programming online we provide niit projects, assignments, cycle tests and much more..
    visit ====>>>