Making the acquaintance of a web API


  1. First you need to identify the API's location. For example:

    http://catfacts-api.appspot.com/api/facts

  2. Then you have to read the documentation and experiment with calling the API from your browser. The parameters to an API request are typically given as a query string. For example, the above API can be called as follows:

    http://catfacts-api.appspot.com/api/facts?number=3

    After the question mark, there can be any number of pairs field-value, indicating the values for the parameters accepted by the API -- look up the documentation! In this simple case, the field is "number" and the value is 3, indicating that we wish to retrieve a number of 3 facts.

  3. The request will result in an output that usually takes either XML or JSON format. A possible output to the above query is the following:

    {"facts": ["Declawing a cat is the same as cutting a human's fingers off at the knuckle. There are several alternatives to a complete declawing, including trimming or a less radical (though more involved) surgery to remove the claws. Instead, train your cat to use a scratching post.", "Cats purr at the same frequency as an idling diesel engine, about 26 cycles per second.", "On average, a cat will sleep for 16 hours a day."], "success": "true"}

  4. Admittedly, this is not very readable! But the output is not meant for the humans to read. Here, it is structured as JSON, the object notation for Javascript. You can paste this output in any online JSON viewers, such as this one. This allows you to see the tree-like structure of the output, and therefore to know how to access it from your Javasript code. Here, you will need to recall Javascript objects and arrays

  5. Note that some APIs require a key which needs to be included in every query string. The key needs to be obtained from the API provider.

Here is some sample code for communicating with the API. It involves both PHP and Javascript.


Another nice API to experiment with is this weather API. At this link you can find some sample code for interacting with the API. The code involves only the client side (so no PHP required). Note that, in order for the code to run properly, you need to plug in your API key in the indicated place in the file. The key can be obtained from the website after after you have signed up.