mercredi 19 janvier 2011

How to export objects as JSON with Play framework

With Play, it is extremely easy to create a REST service that exposes some model objects in JSON format.


If we write this line in the routes file :

GET /albums.json            Application.listAlbumsInJson

And this method in the controller :

public static void listAlbumsInJson(){
        List<Album> albums = Album.findAll();
        renderJSON(albums);
    }

Calling http://myapp/albums.json URL will return the album list in JSON format. It could not be simpler!

Another trick (I discovered on zengularity.com website) : to determine the data format directly from the URL, it is possible to use this syntax in the routes file :

GET /albums.{<json|xml>format} Application.listAlbums

If we call /albums.xml , Play will call listAlbums() with the 'format' parameter set to 'xml', and calling /albums.json will set the same parameter to 'json'.

We can use it in the controller :

public static void listAlbums() {
               List<Album> albums = Album.all().fetch();
         if(request.format.equals("json"))
            renderJSON(albums);
         else render(albums);
    }

If you reach /albums.xml, Play will look for an XML template file named listAlbums.xml (an other file extension would work too).

For more information about writing REST (and XML) API with Play, you can read this post.
I also updated my Play sample application by adding some JSON services.