API Development

I’ve recently been working on developing an API for a website. This entails tapping in to an existing web framework and developing a mechanism that allows for simple integration into mobile apps or desktop apps or whatever. There has been a small learning curve, but I’m chugging through this quickly. I figured it that adding in notes here would do me well for future reference.

JSON & PHP

The first thing to be aware of is that JSON is the defacto standard in APIs. Understanding how to properly utilize JSON both from the server and client sides is critical.

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming LanguageStandard ECMA-262 3rd Edition – December 1999. JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others. These properties make JSON an ideal data-interchange language.

PHP includes a couple of functions for working with JSON. The two that you will primarily be focusing upon are:

json_encode()
json_decode()

These prepackaged solutions work well, but it’s important to ensure that what you are stuffing into them is properly formed. To accomplish this, you need to make sure that you understand how to create the array in PHP. When I was first working with this, I kept getting malformed data on the client because of this. Here’s an example of a JSON response from a server query:

{
    "users": [
        { "id": "1", "name":"bob", "age":"35" },
        { "id": "2", "name":"alice", "age":38" }
    ]
}

Looks pretty straightforward. Make absolutely certain that when you are creating the array via PHP that you maintain a format similar to the following example:

$usersArr = array("users" => array());

You can then proceed to fill in the data via a loop such as:

while (whatever condition) {
    $usersArr['useres'][] = array("id" => $row['id'], "name" => $row['name'], "age" => $row['age']);
}

Finally, you can output the JSON in a manner such as:

echo json_encode($usersArr);

On another note, you may find that the keys of your array need to be adjusted to properly compensate for the expected JSON format. For that, feel free to use the following function:

    function fixKeys($array) {
        $numberCheck = false;
        foreach ($array as $k => $val) {
            if (is_array($val)) $array[$k] = $this->fixKeys($val); 
            if (is_numeric($k)) $numberCheck = true;
        }
        if ($numberCheck === true) {
            return array_values($array);
        } else {
            return $array;
        }
    }

Now that the server is handing out properly formatted JSON, how do we get the client to interact with it? There’s a number of ways. I’m going to supply a very simple method for this, just for example sake and notation purposes.

Let’s say that, in order to get the JSON used at the beginning of this post, that you make a GET request via AJAX to the following URI:

$SOME_HOST/api/users/get-list

First, you can parse the JSON with JavaScript in the following manner:

var obj = JSON.parse(result);

In the example above, obj now holds the JSON data in a usable object format. You can then reference every aspect of the records in a manner such as:

for (var i = 0; i < obj.users.length; i++) {
    var data = obj.users[i];
    console.log(data['name']);
}

Other examples of access include:

// how many keys in users array?
console.log(obj.users.length);

// print out some data
console.log(obj.users[0].name);
console.log(obj.users[1].name);

It should be pretty obvious from here. To test my API, I simply wrapped an HTML5 app with bootstrap and compiled with Apache Cordova to generate an APK which I then I installed on my Galaxy S5. Everything has been working as expected.

Advertisements