About an year ago I’ve stumbled upon this interesting little framework called Spark Java. If you are looking for a lightweight alternative to quickly develop REST APIs in Java, you might like this.
Pretty straightforward. Spark Java leverages Java 8 to provide an easy to use and understand api. Method get() registers the endpoint and starts up an embedded Jetty server to handle the incoming http requests.
Look at this other example:
Here we declare a POST endpoint that only gets called if the client sets Accept: “application/json” request header. Moreover, we return an entity that is serialized to JSON using an object that implements ResponseTransformer; it could possibly use Gson behind the scenes.
Spark Java has not invented anything new. The design is pretty much taken from Ruby’s Sinatra framework.
Simple, easy to maintain and understand.
No “magic”. Get rid of all the levels of indirection that a framework like Spring MVC introduces.
Better separation of concerns. Spark Java does not try to save the world.
Let’s go a bit fancy. Here’s a design idea you can use when there are multiple endpoints to configure.
First, create a builder interface:
Now, let’s say you have one of many other rest endpoints resources to set up:
Finally, create a RestContext class that will hold the spark instance and will enable you to configure whatever routes you wish:
You should be able to use this context class in your main method (and optionally in your test classes):