APIs open up your applications so developers and other applications can interact with them. In this demo I developed an API in php to serve POST requests over http for anyone with an API key. Click the 'Make API call' button to get the number of Customer Service Cases closed from a MySQL database for a particular person. Although the demo runs on a LAMP stack, the build principles should still hold for other dev stacks.


Demo


The API url is the location of the php file to POST the request to. The response it'll provide is JSON. Here's a quick reference to some of the options you can specify for the API parameters:

apiKey For this demo use the key 6421C1AC76496D6EAF7C76D1F81F9 which expires in 2016
function getCountCaseClosed - counts the number of customer service cases have been closed by the user
user Either Kunal or John

Build

source code on GitHub

Server-side:
  • PHP
    • Check if posted data contains api key or function, if not return an error as json
    • Otherwise if the api key is good, try to call the function requested
    • Since the call requires information from a MySQL db, parameterise the query to prevent against SQL injection
    • Echo the json encoded array to return json
  • Apache Server
    • Enable CORS to allow cross domain calls to the api (see GitHub htaccess file)
Client-side:
  • JavaScript
    • Use XmlHttpRequest to call api

Reflect

Gotcha's:
  • SQL bind statements: locally my parameterised SQL queries worked fine but failed in production. I had to recode them to use fetch/bind.
  • Enabling other domains to call my api: there's a lot of talk of CORS on SE and other forums but the mechanics of which file to create, to contain what info and where it should be placed was limited, I spent hours fiddling around with this to get it to work. I've included my .htaccess file in the source code which enables these cross domain calls to work (I placed this in the same directory as my .php api file.
Improvements:
  • Server side; save hashed api key for better security, return a callback function so user can use JSONP, design the api RESTfully, use versioning to allow for future api change
  • Client side; use inbuilt jQuery .ajax methods to make api call, use callback function for JSONP