Connecting to REST API Services

Using Solar2D, you can connect to various online services to get data into your app. To accomplish this, a popular option is REST (or RESTful) APIs which are based on standard HTTP protocols and are generally easy to authenticate.

REST Overview

Many services offer their data via REST and you can use the standard HTTP “verbs” to access that data:

REST uses standard HTTP URLs to define the API. For instance, with Twitter, you could access the following with a GET request to fetch a list of a user’s friends:

https://api.twitter.com/1.1/friends/list.json

Let’s inspect this in more detail:

Authentication

Most REST APIs require some form of verification or authentication, in particular if you’re trying to add or update data. Authentication can occur in various ways, for example by passing the username and password as part of the domain name:

https://username:[email protected]/someapi/dosomething.json

In this example, the username:password method is a shortcut to using a headers table. Sometimes the username and password will be referred to as the “API Key” and “secret” and they may need to be encoded in some fashion such as MD5.

An alternate method is to use a headers table, discussed in more detail below.

Making API Calls

Your REST API calls are made via network.request(). For this API, you need to provide a URL, an HTTP “verb”, a callback function to handle the completed request, and an optional table of information in which to handle headers and data passed to the server.

Basic Request

Let’s look at a simple example using basic authentication (no headers):

local json = require( "json" )

local function handleResponse( event )

    if not event.isError then
        local response = json.decode( event.response )
        print( event.response )
    else
        print( "Error!" )
    end

    return
end
 
network.request( "https://username:[email protected]/users/friends.json", "GET", handleResponse )

Headers

Alternatively, if your service can’t use basic authentication as part of the URL, you need to set up headers:

local json = require( "json" )
local mime = require( "mime" )

local function handleResponse( event )

    if not event.isError then
        local response = json.decode( event.response )
        print( event.response )
    else
        print( "Error!" )
    end
    
    return
end

local headers = {}
headers["Authentication"] = mime.b64("username:password")

local params = {}
params.headers = headers

network.request( "https://api.yourservice.com/users/friends.json", "GET", handleResponse, params )

Conclusion

Every service will have its own methods to call, so you need to research the specific API calls and learn what HTTP verbs are expected, as well as which parameters. Also, each service seems to implement authentication a little differently, but this tutorial should get you started on using REST-based APIs from various providers.