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)
serverurl="https://api.github.com"

# 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 http://developer.github.com/v3/
authreqdata = { "scopes": [ "public_repo" ], "
                note": "admin script" }
resource = Resource('https://api.github.com/authorizations', 
                    pool=pool, filters=[auth])
response = resource.post(headers={ "Content-Type": "application/json" }, 
                         payload=json.dumps(authreqdata))
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 http://developer.github.com/v3/ 
for more about the url structure
"""
resource = Resource('https://api.github.com/user/repos', 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 comment: