Reference: http://sparkjava.com/
Spark is an extremely easy to use Java Web Framework. It embeds Jetty within and you can run as a standalone web server. You can create a Java web application or an API server in less than 15 minutes with Spark. Below shows an example of creating a JSON API.
Step 1: Create a new Java project with JDK8 and let's use maven to manage the dependency.
Step 2: Add spark java and GSON as a dependency.
<dependency> <groupId>com.sparkjava</groupId> <artifactId>spark-core</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.7</version> </dependency>
Step 3: Create a main Class to hold your main method.
import static spark.Spark.*; public class Main { public static void main(String[] args) { } }
Step 4: Setup Spark by specifying the listening port and threads.
public static void main(String[] args) { port(4000); threadPool(20, 2, 60000); }
Step 5: Let's write an Endpoint to return system time in JSON
public static void main(String[] args) { port(4000); threadPool(20, 2, 60000); get("/time", (req, res) -> { res.type("application/json"); res.status(200); return new TimeResult(String.valueOf(Instant.now().toEpochMilli())); }, new JsonTransformer()); }
Step 6: Here we also define a JsonTransformer to handle the response. It basically transforms POJO into Json by using Gson.
public class JsonTransformer implements ResponseTransformer { private Gson gson = new Gson(); @Override public String render(Object model) { return gson.toJson(model); } } public class TimeResult { private String result = ""; public TimeResult(String result) { setResult(result); } public String getResult() { return result; } public void setResult(String result) { this.result = result; } }
Step 7: Run the app and access it from your browser.