13 Oct 2013

I've been playing with the GitHub API, through Emacs. For all the interesting stuff, it needs OAuth2 authorization, and though there's good support in Emacs for OAuth2, I couldn't find a getting started guide. So, here goes:

First you'll need an access token. The standard way of getting an access token - redirect to the service (Github), authorize, redirect back to your website - isn't going to help us much. We don't have a website to come back to. It's just an Emacs client. But there's an alternative, and all the providers I've played around with so far support it. They'll issue you an access token manually for personal use.

So, we head off to Github > Account Settings > Applications and there's a box marked "Personal Access Tokens". Creating one of those gives us a token like 70ea4b4d58f5fb41a534d9d021d3c5bcfeb2d5ae.

With that magic string we're away. Require the package (you may need to M-x package-install it first), then create an oauth2-token struct:

(require 'oauth2)
(defvar my-token
  (make-oauth2-token :access-token "70ea4b4d58f5fb41a534d9d021d3c5bcfeb2d5ae"))

With that we turn to oauth2-url-retrieve-synchronously. It will take a token and a url and return a buffer containing the HTTP request. We can dip into that buffer and read the json like this:

(require 'json)
(defvar user-data
      (oauth2-url-retrieve-synchronously my-token "https://api.github.com/user")
    (goto-char url-http-end-of-headers)

Job done. Let's just pull out an item:

(cdr (assoc 'name user-data))
Kris Jenkins

And that's all there is to it. (Or at least, enough to get you started…)

comments powered by Disqus