Working with Gist API from Lua

Now that I can make HTTPS calls using Lua, I can use this functionality to interact with GitHub API, which requires HTTPS.

I am going to use lua-spore module, which provides implementation of Specification to a POrtable Rest Environment. This module already includes specification for Gist API, but for an older version of the API that is no longer supported by GitHub. Fortunately, it is very easy to provide your own specification and still use all the functionality provided by the module:

local Spore = require 'Spore'
local client = Spore.new_from_string [[{
  "base_url" : "https://api.github.com/",
  "version" : "0.41",
  "methods" : {
    "get_gist" : {
      "path" : "/gists/:gist_id",
      "method" : "GET",
      "required_params" : [
        "gist_id"
      ]
    },
    "list_gists" : {
      "path" : "/users/:login/gists",
      "method" : "GET",
      "required_params" : [
        "login"
      ]
    }
  },
  "expected_status" : [ 200 ],
  "name" : "GitHub",
  "authority" : "http://github.com/ZeroBraneStudio",
  "meta" : {
    "documentation" : "http://developer.github.com/v3/gists/",
    "module" : "gist",
    "enable_if" : "get_gist_content"
  }
}]]

This specification describes two methods -- get_gist and list_gists -- which map to specific URLs in the GitHub API and are now provided by the module. Here is how we can use them:

local res = client:get_gist{ gist_id = 2278953 }
print(res.body)

This fragment will print the body of the messages returned by GitHub. The Spore library provides a convenient way to parse this response into Lua structures; you just need to enable a specific format on the client side with client:enable 'Format.JSON':

client:enable 'Format.JSON'
local res = client:get_gist{ gist_id = 2278953 }
print(res.body.description)

This fragment will print the description of one of the gists I created: "A test for running Lua in a browser (http://notebook.kulchenko.com/) #lua #browser #javascript". JSON decoding requires one of JSON modules to be installed; I used pure Lua jf-JSON with few tweaks to make it compatible with the interface required by the Spore library.

A bit more complex example will return the list of all gists I created and all the files included in those gists:

client:enable 'Format.JSON'
local gists = client:list_gists{ login = 'pkulchenko' }
for _,g in ipairs(gists.body) do
  print(g.url)
  for f in pairs(g.files) do print("  "..f) end
end
You should get a copy of my slick ZeroBrane Studio IDE and follow me on twitter here.

Leave a comment

what will you say?
(required)
(required)

About

I am Paul Kulchenko.
I live in Kirkland, WA with my wife and three kids.
I do consulting as a software developer.
I study robotics and artificial intelligence.
I write books and open-source software.
I teach introductory computer science.
I develop a slick Lua IDE and debugger.

Recommended

Close