Monday, December 17, 2007

Creating RESTful JSON services with AppJet

The newly launched AppJet makes it extremely easy to host your own JSON services. Firstly, hosting is free. Secondly, serialization of objects (which are in JavaScript, to start with) into JSON is almost equally effortless.

Just to show how easy it is to do this, I've created a simple Contacts List service hosted at http://contactsapi.appjet.net/ (view the source). The API exposes CRUD operations on a Contacts List. This list is a collection of simple contacts, each containing only a Name and an Email.

AppJet let's you write and host JavaScript web applications. (That's right, server-side JavaScript programming, and from inside your browser.) Besides full-fledged applications with flashy UIs, I've found it works just as well for bare-bones web services. If you haven't yet checked it out, I suggest you do, it rocks!

How I created the services:

  • I called page.setMode("plain"), so I could output what I needed - in this case, JSON representation of Contact objects - and nothing more, no default xhtml document structures.

  • AppJet doesn't support PUT and DELETE, so I relied on POST and GET only to design a REST-styled API interface. I wired up Controller-esque URL-routing using patternDispatch() with request.isGet and request.isPost to come up with the necessary CRUD operations over HTTP.

  • Finally, for the GET requests, I return serialized JavaScript data resources by simply calling Print() on the Contacts objects and arrays. This works for about 96% of the serialization I used in this example (Print() auto formats some of the objects into HTML tables), and I suspect using a ported version of the JSON stringifier found on json.org will close this gap.

Adding client-side JavaScript callbacks to the JSON results? No-brainer, just output a query-specified callback to the end of the returned JSON. Email validation for the contacts? A quick Google search yielded this regex match test.

I forgot to mention I used AppJet's excellent persistent storage classes to store the Contact List. Couple features like that with the remote-web-request-capable wget() and wpost() and you have a wonderful zero-configuration, fast-deploy, mashup-ready platform.

0 comments: