Friday, June 30, 2017

How to a Build Standalone REST Application in Java

There are many frameworks that allow you to build REST easily in Java. In this blog, however, I am going tho show you how to build a standalone REST application without any framework. We are going to use the following libraries:
  1. Jetty for web server
  2. Jersey for REST
  3. Jackson for JSON
  4. Swagger for API documentation

First we need the build script. I am going to use Gradle for this.
plugins {
    id "com.github.johnrengelman.shadow" version "2.0.1"
    id "java"

apply plugin: "java"
apply plugin: "com.github.johnrengelman.shadow"

defaultTasks = ["clean", "build", "shadowJar"]

repositories {

dependencies {
    // Jetty dependencies
    compile "org.eclipse.jetty:jetty-server:9.4.6.v20170531"
    compile "org.eclipse.jetty:jetty-servlet:9.4.6.v20170531"

    // Jersey dependencies
    compile "org.glassfish.jersey.core:jersey-server:2.25.1"
    compile ""
    compile "org.glassfish.jersey.containers:jersey-container-servlet:2.25.1"

    // Swagger dependencies
    compile "io.swagger:swagger-core:1.5.15"
    compile "io.swagger:swagger-annotations:1.5.15"
    compile "io.swagger:swagger-jersey2-jaxrs:1.5.15"
    // Required by BeanConfig
    runtime "org.codehaus.groovy:groovy:2.4.12"

    // Required by Swagger
    runtime "ch.qos.logback:logback-core:1.2.3"
    runtime "ch.qos.logback:logback-classic:1.2.3"

jar {
    manifest {
        attributes "Main-Class": ""

Second, we will write a typical JAX-RS application with JAX-RS, Jackson, and Swagger annotations.

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;


@Api(value = "/hello", description = "API for Hello")
public class HelloResource {
    public static class HelloRequest {
        @ApiModelProperty(value = "The name", required = true)
        private final String name;

        public HelloRequest(@JsonProperty("name") String name) {
   = name;

        public String getName() {
            return name;

    public static class HelloResponse {
        @ApiModelProperty(value = "The message", required = true)
        private final String message;

        public HelloResponse(@JsonProperty("message") String message) {
            this.message = message;

        public String getMessage() {
            return message;

    @ApiOperation(value = "Gets the message", response = HelloResponse.class)
    @ApiResponse(code = 200, message = "Successful operation")
    public Response getMessage(HelloRequest request) {
        return Response.ok(new HelloResponse("Hello, " + request.getName())).build();

Third, we will need to register our REST resource into Jetty and start the server.

import com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.HandlerList;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.resource.Resource;
import org.glassfish.jersey.server.ServerProperties;
import org.glassfish.jersey.servlet.ServletContainer;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import java.util.StringJoiner;

public class HelloServer {
    public static class Bootstrap extends HttpServlet {
        public void init(ServletConfig config) throws ServletException {

            BeanConfig beanConfig = new BeanConfig();
            beanConfig.setTitle("Hello API");
            beanConfig.setSchemes(new String[]{"http"});

    public static void main(String[] args) throws Exception {
        ServletContextHandler servletHandler = new ServletContextHandler(ServletContextHandler.SESSIONS);

        ServletHolder jerseyServlet = servletHandler.addServlet(ServletContainer.class, "/api/*");

            new StringJoiner(",")

        ResourceHandler staticHandler = new ResourceHandler();
        staticHandler.setWelcomeFiles(new String[]{"index.html"});

        HandlerList handlers = new HandlerList();
        // Add two handlers, one for static content and the other one for dynamic content.
        handlers.setHandlers(new Handler[]{staticHandler, servletHandler});

        // The mapping doesn't really matter here.
        ServletHolder swaggerServlet = servletHandler.addServlet(Bootstrap.class, "/");

        Server jettyServer = new Server(8080);

        try {
        } finally {

Few important things to note.
  1. Add the Jersey servlet container (org.glassfish.jersey.servlet.ServletContainer). This servlet implementation comes from Jersey library.
  2. Register some providers, such as our own REST provider (, Jackson provider (com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider), and Swagger providers (io.swagger.jaxrs.listing.ApiListingResource and io.swagger.jaxrs.listing.SwaggerSerializers). The Swagger providers will create swagger.json specified by the servlet mapping path, which is api/swagger.json in this case.

Lastly, we need to add some Swagger UI so that we can display the API documentation in a nice format. What we need is basically download Swagger UI from and copy the dist directory into src/main/resources. The goal of this is to keep the Swagger UI in the JAR and is available in the classpath. Swagger UI is just a static content and we can tell Jetty to serve static content by using org.eclipse.jetty.server.handler.ResourceHandler. Make sure to modify the URL in Swagger's index.html from to http://localhost:8080/api/swagger.json since that's where our swagger.json file lives. To build and run the example, we can type the following command.
./gradlew && java -jar build/libs/java-rest-swagger-example-all.jar
Full source code can be found here.

No comments:

Post a Comment