Simple server mock for REST services

Michaël van Leeuwen

When working on a mobile Android application, I was confronted with the fact that the backend server wasn’t available yet to deliver the REST service. But I needed a server or good dummy for testing the Android client against the REST services. So I began my search for a REST mock server.

I started out using the SoapUI REST functionality, but that still lacks a good implementation for my purpose of reacting on REST calls. I ended up with a 10-minute build-your-own REST mock using the Play framework. This blogs describes how this was accomplished.

The Play framework crossed my path earlier. It is a very simple yet powerful application framework for web applications. It is almost trivial to set it up for mocking REST services. First make sure you download and unpack the framework. Then execute the following commands to create a new project:

    play new RestMockServer 
    play eclipsify RestMockServer 
    play run RestMockServer

The project is running and now ready to be worked on in eclipse (see ‘play help’ for other IDEs). Changes in code and configuration will be picked up by the framework automatically. Just point your browser to http://localhost:9000/ to see the application running.

The next step is to add the REST URLs to the routing table. Let us say I ‘m creating a system for storing photos containing meta data and the image URL. Open the file ‘conf/routes’ and add the following lines before the ‘Catch all’ entry:

    PUT    /photo            PhotoController.create
    POST   /photo            PhotoController.update
    GET    /photo/{id}       PhotoController.read
    DELETE /photo/{id}       PhotoController.delete

This defines the CRUD actions on a photo object. First in line is the http method on which the framework should react. The second part is the URL with optional parameters which will be mapped onto the method indicated in the first part.

The following action is to define a controller handling the calls. The implementation uses a very simple response technique based on text. The mapping of the id to the actual response is left to the reader to implement. You could for example read a file based on the URL parameter and return the content of it. For now, we just return the identifier specified in the URL.

Save the file below as ‘PhotoController.java’ and call http://localhost:9000/photo/123 and see your favorite number showing on screen. Note that the name between curly braces should match the name of the parameter. The mapping on type will be done auto-magically by the framework.

package controllers;
import java.util.Random;
import com.google.gson.JsonObject;
import play.mvc.Controller;

public class PhotoController extends Controller {
    public static void read(int id) {
        try {
            response.contentType = "application/json";
            renderText(id);
        } catch (Exception e) {
            notFound(e.getMessage());
        }
    }
}

The next step is to implement the other methods. Since I’m using JSON as data format, I have to add a specific binder for the JsonObject type, used both by the create and update method. The ‘ok’ just returns a 200 status code. Upon creation of an object I need the identifier of the newly stored data object, so for test purposes I return a random integer.

Add the following method implementations to PhotoController.java:

    public static void delete(int id) {
        ok();
    }

    public static void update(JsonObject body) {
        ok();
    }

    public static void create(JsonObject body) {
        response.contentType = "application/json";
        renderText("\"id\":"+Math.abs(new Random().nextInt()));
    }

The binder is also automatically found by the framework. I’ve created a new package ‘util’ in which I placed the following class:

package util;
import java.lang.annotation.*;
import java.lang.reflect.Type;
import com.google.gson.*;
import play.data.binding.*;

@Global
public class GsonBinder implements TypeBinder<jsonobject> {
    @Override
    public Object bind(String name, Annotation[] a, String value, Class c, Type t) throws Exception
    {
        return new JsonParser().parse(value);
    }
}

And that is basically all to set up your mock server for REST services using the Play framework! From your favorite REST client, call the URL: http://localhost:9000/photo with a PUT request and set the entity of the request to some JSON content.

Happy development!

Comments (4)

  1. Burc Sade - Reply

    August 10, 2011 at 1:01 pm

    Thanks for sharing! Just developing a mock application for our internal framework, this can be a better and more productive way for me. I'll definitely consider it.

  2. Pankaj - Reply

    September 3, 2011 at 10:26 pm

    Thanks for Sharing,
    In addition to Play, you can also have a look on Scooterframework for java, which makes it very easy to generate the UI as well as the ReST based API's for the data maintained in the database. Give it a try, and I Hope u will start driving it very soon. The advantage is you can deploy the web app in any of the App Server/Servlet Container however the same is not the case with play, as it is working on Jboss Netty ( perhaps )...........

  3. Jacques - Reply

    September 13, 2011 at 1:56 pm

    To test any REST webservice http://www.oniontest.org 🙂
    Write an onion !

  4. Jacek - Reply

    November 14, 2012 at 12:54 am

    You can also try my mocking tool:

    https://sourceforge.net/projects/soaprest-mocker/

Add a Comment