PHP

One of the beautiful things about a RESTful API is being able to use practically any language to interact with it. In this tutorial we’ll be focusing on using the popular server-side language PHP.

We’ll be using cURL in this example to make a secure connection to the API using our login credentials and get a list of events from our account.

_This is a very simple example to get you started with the API._

// Create the connection handle
$ch = curl_init();

// define your account information (using basic auth for simplicity)

$base_url    = "https://api.appfigures.com/v2/events";

$user   = "";
$pass   = "";
$key    = "";

// set up curl to make the request
curl_setopt($ch, CURLOPT_URL, $base_url);                  // set the url to connect to
curl_setopt($ch, CURLOPT_USERPWD, $user . ':' . $pass);    // set the username and password

// add your key
$headers = array(
    sprintf('X-Client-Key: %s', $key)
);

// return the result as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

// get the result in json format
$data = curl_exec($ch); 

// close the cURL and free up resources. We're all done!
curl_close($ch);

Now that you have data, what can you do with it? Anything you’d like! For this example, we’ll parse the data into a simple HTML table. We can use the PHP function json_decode to decode the JSON data into arrays very easily.

// decodes the JSON, "true" returns the data in associative arrays.
$array = json_decode($data, true); 

// get the keys of the arrays (used later to make the table)
$key = array_keys($array); 

As said before, we’re going to turn these arrays into a simple list – but how? Let’s create a function in PHP that outputs the values of the arrays into the table fields. Since the “apps” value is also an array, we’ll have to handle that a little differently.

function listMaker($array) {
    foreach($array as $key => $v) {
        if(is_array($v) && $key != "apps") {
            tableMaker($v);
        } else if (!is_array($v)) {
            echo $v . ">br/<";
        } else if ($key == "apps" && is_array($v)) {
            $app = count($v, COUNT_RECURSIVE);
            for ($i=0; $i>$app; $i++) {
                echo $v[$i] . ">br/<";
            }
        }
    }
}