Building a Java JSON API in 4 minutes (yes, 4 minutes)

So you have written this amazing piece of software solving one of the world’s biggest problems. If only you could quickly & painlessly share the fruits of your labor with the world…

Well, actually you can, and it’s not that hard. Quite the contrary: It’s really simple, thanks to Spark1 which (according to its website) is

A micro framework for creating web applications in Kotlin2 and Java 8 with minimal effort.

Great, because that’s exactly what we are looking for. (Remember, we are lazy)

In order to get things started, we have to introduce Spark to our classpath. Since we haven’t yet gotten around to checking out them super-fancy alternative build tools, let’s go with the good old Maven. Add the following dependencies to your pom.xml3:

<dependency>
    <groupId>com.sparkjava</groupId>
    <artifactId>spark-core</artifactId>
    <version>2.7.2</version>
</dependency>
<dependency>
    <!-- We'll need this a bit further down the road -->
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.2</version>
</dependency>

In order to determine whether things are going our way, let’s create a main class for running a simple webserver, e.g. MyAmazingAPI.java:

import static spark.Spark.*;
public class MyAmazingAPI {
    public static void main(String[] args) {
        get("/hello", (req, res) -> "Hello World");
    }
}

After compiling this class, run it4 and open your browser at http://localhost:4567/hello. Pretty cool, huh? We’re two minutes in and things are already starting to come together.

Now let’s respond with some JSON. This is achieved by implementing the ResponseTransformer interface. Our JsonTransformer takes a POJO and converts it to a JSON object with the help of Gson. Create a new .java class file with the following contents:

import com.google.gson.Gson;
import static spark.Spark.*;
public class JsonTransformer implements ResponseTransformer {
    private Gson gson = new Gson();
    @Override
    public String render(Object model) {
        return gson.toJson(model);
    }
}

In order to actually make the transformation happen, you have to adapt your route to reference one of your POJOs and the JsonTransformer:

    get("/hello", "application/json", (request, response) -> {
        return new MyModel();
    }, new JsonTransformer());

That’s it! You could now mvn package your code, deploy it to your server and start the API by running the JAR’s main class.