Category Archives: Phish

Creating a JSON API

I was assisting someone recently in building an API for their website and it occurred to me that while the current trend is generally using XML/REST/SOAP for APIs, there is quite a bit of benefit to using plain old Javascript and JSON.  Most users won’t venture into API territory, so if your goal is to make your API accessible – and this goes double if your primary purpose is embedding content in a third party site – it’s hard to argue with Javascript.

The Phish.net API, for example, is a simple HTTP request to an endpoint that returns JSON.  If you provide a callback function name as an argument, and then pre-define that function, it will return the contents wrapped in a function call.  In short, if you define a function called “example()” that accepts JSON an array/object as an argument, then by requesting the API with a callback of “example”, the response will be returned like so:

example(json response);

The benefit, of course, is that it allows a user to embed your code easily. If you host your own callback functions, you can very easily walk a user through a data embed. For example, on Phish.net, we offer the band’s latest setlist.  So we host a callback called pnet3setlist().  Then we offer the API response.  Embedding the setlist is literally as easy as this:

<script src="http://api.phish.net/callbacks/pnet3-setlist.js" type="text/javascript"></script>
<script src="https://api.phish.net/api.json?method=pnet.shows.setlist.recent&amp;amp;callback=pnet3setlist" type="text/javascript"></script>

I’m going to dig more into this later, but the gist of this is that the API can be constructed in a way that allows novice users to interact with it in their WordPress- or Blogger-blogs with little to no modification, it allows semi-skilled users to modify it slightly and tweak it for display purposes, and it allows advanced users to control virtually all aspects. Since virtually every major web language can encode and decode JSON (Javascript, PHP, Ruby, ASP, etc), it’s a near-universal way to exchange data. It doesn’t carry the overhead or complexity of XML, nor does it have the limited scope of something like serialized PHP.

Javascript-based APIs may not be the ultimate solution to a fully interconnected web, but they’re certainly going to be one of the best and simplest methods of data exchange for the foreseeable future.