This tutorial is beginners guide for learning how to build and deploy your first Dropwizard applications. In this tutorial, I explain the basic concept of dropwizard and how to write a simple REST services using this framework. I have been working on Spring Boot for the last couple of months and very much inspired by it concepts and building the microservice REST applications.

Also Read : Best Practices for REST API Design

That forced me to look for alternative framework for building the REST services and compare that with the Spring Boot. So, finally I am here to walk you through with Dropwizard framework. My next tutorial will be comparing Spring Boot and Dropwizard. Please subscribe here to get the updates.

Table Of Contents

What is Dropwizard? Dropwizard default libraries Maven configuration Define configuration class Define an Application class Define a Representation class Define a Resource class Registering a resource Build your application Running your application How to change context path? Resources for learning Dropwizard Download source code Summary

1. What is Dropwizard?

Dropwizard is a microservices framework. This helps you to package your applications that can be easily deployable in the production environment as a standalone service. Dropwizard autoconfigures set of frameworks and libraries for building RESTful Web Services. While bundling several libraries, it uses opinionated default values that are best for your applications.

If you are an application developer, you are no longer going to worry about configurations required for each library that are used by your application(like hibernate, ehcache, etc) that are available in the classpath. Dropwizard will takes care of configuring the sensible defaults for your applications.

2. Dropwizard Default Libraries

Dropwizard uses the sensible default libraries for your applications to up and running quickly. The following are the list of default libraries used if you have not explicitly mentioned in your build file:

Jetty : You would require HTTP for running a web application. Dropwizard embeds the Jetty servlet container for running the web applications. Instead of deploying your applications to a application server or web server, dropwizard defines a main method that invokes the Jetty server as a standalone process. As of now, dropwizard recommends only running the application with Jetty, no other web services like Tomcat is not officially supported.

Jersey : Jersey is one of the best REST API implementation out in the market. Also it follows the standard JAX-RS specification and it is the reference implementation for the JAX-RS specification. Dropwizard uses Jersey as the default framework for building the RESTful web applications.

Jackson : Jackson is the defacto standard for JSON format handling. It is one of the best object mapper API for the JSON format.

Metrics : Dropwizard has it’s own metrics module for exposing the application metrics through HTTP endpoints.

Guava : which, in addition to highly optimized immutable data structures, provides a growing number of classes to speed up development in Java.

Logback and Slf4j : These two are used for the better logging mechanisms.

Freemarker and Mustache : Choosing template engines for your application is one of the key decision. The chosen template engine has to be more flexible for writing the better scripts. Dropwizard uses the well known and popular template engines Freemarker and Mustache for building the user interfaces.

Apart from the above list, there are many other libraries like Joda Time, Liquibase, Apache HTTP Client and Hibernate Validadtor are used by dropwizard for building REST services.

3. Maven Configuration

It is recommended to use the Maven for the dropwizard applications. You could use other build tools like Ant / Ivy, Buildr, Gradle, SBT, Leiningen, etc. But, if you are using Maven, that is cool and easy to configure your applications since most of the guides use Maven as the build tool.

Setting up Maven is the first step on configuring dropwizard application. Please add the following entry in your Maven’s pom.xml file:

<dependencies> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-core</artifactId> <version>${dropwizard.version}</version> </dependency> </dependencies>

Before adding the above entry, you could add the dropwizard.version as below:

<properties> <dropwizard.version>INSERT VERSION HERE</dropwizard.version> </properties>

That’s it. You have done with writing the Maven configurations. The above configurations would fetch all the required libraries to your project. Now, we will move on to writing our first real application using dropwizard. At the end of this tutorial, I have uploaded the entire source code used for this tutorial.

4. Define Configuration Class

Dropwizard supports the YAML configuration file for passing the messages. You can create the configuration.yml . in the project root. This file will be then deserialized to an instance of your application’s configuration class and validated. Your application’s configuration file is the subclass of the Configuration class which will be directly mapping it’s properties to the configuration.yml .

Here is the simple example for your configuration class:

import io.dropwizard.Configuration; import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.NotEmpty; public class EmployeeConfiguration extends Configuration { @NotEmpty private String message; @NotEmpty private String defaultText1; @NotEmpty private String defaultText2; @JsonProperty public String getMessage() { return message; } @JsonProperty public void setMessage(String message) { this.message = message; } @JsonProperty public String getDefaultText1() { return defaultText1; } @JsonProperty public void setDefaultText1(String defaultText1) { this.defaultText1 = defaultText1; } @JsonProperty public String getDefaultText2() { return defaultText2; } @JsonProperty public void setDefaultText2(String defaultText2) { this.defaultText2 = defaultText2; } }

The above class will be deserialized from the YAML file and put the values from the YAML file to this object.

The YAML file employee-details would look like this:

message : Hello %s! You are learning %s!! defaultText1: Krishna defaultText2: Dropwizard

5. Define An Application Class

Now you have to create a main applications class, which will be the subclass of your application’s configuration class. This application class would bring all the bundles together and make the application up and running for the use.

Here is the example for application class:

import io.dropwizard.Application; import io.dropwizard.setup.Bootstrap; import io.dropwizard.setup.Environment; import net.javabeat.dropwizard.resources.EmployeeResource; public class EmployeeApplication extends Application<EmployeeConfiguration> { public static void main(String[] args) throws Exception { new EmployeeApplication().run(args); } @Override public void initialize(Bootstrap<EmployeeConfiguration> bootstrap) { // nothing to do yet } @Override public void run(EmployeeConfiguration configuration, Environment environment) { final EmployeeResource resource = new EmployeeResource( configuration.getMessage(), configuration.getDefaultText1(),configuration.getDefaultText2()); environment.jersey().register(resource); } }

6. Define A Representation Class

Now we have to start thinking about our REST API and what will be the representation of our resource. We have to design the JSON format and the corresponding representation class that converts to the desired JSON format. Let’s look at the sample JSON format for this simple example:

{ {"content":"Hello Krishna! You are learning Dropwizard!!"} }

For the above JSON format, we would create the representation class as below:

import com.fasterxml.jackson.annotation.JsonProperty; import org.hibernate.validator.constraints.Length; public class Representation { @Length(max = 3) private String content; public Representation() { // Jackson deserialization } @JsonProperty public String getContent() { return content; } public void setContent(String content) { this.content = content; } public Representation(String content) { this.content = content; } }

This is fairly simple POJO.

7. Define A Resource Class

In the REST API world, resource is everything. A resource is nothing but an endpoint URI for accessing the resource in the server. In our example, this resource will be a controller class with few annotations for request URI mapping. Since dropwizard uses the JAX-RS implementation, a resource class define the URI path using the @Path annotation.

Here is a resource class for our example tutorial:

import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import com.codahale.metrics.annotation.Timed; import com.google.common.base.Optional; import net.javabeat.dropwizard.api.Representation; @Path("/emp-details") @Produces(MediaType.APPLICATION_JSON) public class EmployeeResource { private final String message; private final String defaultText1; private final String defaultText2; public EmployeeResource(String message, String defaultText1, String defaultText2) { this.message = message; this.defaultText1 = defaultText1; this.defaultText2 = defaultText2; } @GET @Timed public Representation sayHello(@QueryParam("param1") Optional<String> param1, @QueryParam("param2") Optional<String> param2) { final String value = String.format(message, param1.or(defaultText1), param2.or(defaultText2)); return new Representation(value); } }

8. Registering A Resource

Once you have created the resource class, this has to be registered with the application class which we have defined earlier in this tutorial. As I have mentioned, application class is the start up engine for the Dropwizard service, so any registration of classes has to be done in the application class. You just add the following code for:

@Override public void run(EmployeeConfiguration configuration, Environment environment) { final EmployeeResource resource = new EmployeeResource( configuration.getMessage(), configuration.getDefaultText1(),configuration.getDefaultText2()); environment.jersey().register(resource); }

9. Build Your Application

It is recommended to build the single FAT JAR file which contain all of the .class files required to run your application. The same JAR file can be deployed to the different environment from testing to the production without any change in the dependency libraries. To start building our example application as a fat JAR, we need to configure a Maven plugin called maven-shade . You have to add the following entries in the plugins section of your pom.xml file.

Here is the sample Maven configuration for building the JAR file.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>net.javabeat</groupId> <artifactId>DropWizardExample</artifactId> <packaging>jar</packaging> <version>1.0.0</version> <name>SampleApp Maven Webapp</name> <properties> <dropwizard.version>0.9.2</dropwizard.version> </properties> <dependencies> <dependency> <groupId>io.dropwizard</groupId> <artifactId>dropwizard-core</artifactId> <version>${dropwizard.version}</version> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-shade-plugin</artifactId> <version>2.3</version> <configuration> <createDependencyReducedPom>true</createDependencyReducedPom> <filters> <filter> <artifact>*:*</artifact> <excludes> <exclude>META-INF/*.SF</exclude> <exclude>META-INF/*.DSA</exclude> <exclude>META-INF/*.RSA</exclude> </excludes> </filter> </filters> </configuration> <executions> <execution> <phase>package</phase> <goals> <goal>shade</goal> </goals> <configuration> <transformers> <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer"/> <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer"> <mainClass>net.javabeat.dropwizard.EmployeeApplication</mainClass> </transformer> </transformers> </configuration> </execution> </executions> </plugin> </plugins> </build> </project>

10. Running Your Application

The final step is to run your application. It is very simple if you have successfully built your JAR file in the previous section. You have to open the command prompt and just run the following command to execute your JAR file:

java -jar target/DropWizardExample-1.0.0.jar server employee-details.yml

If your application has started without any error, then you would see something like below message in the screen:

INFO [2011-12-03 00:38:32,927] io.dropwizard.cli.ServerCommand: Starting emp-details INFO [2011-12-03 00:38:32,931] org.eclipse.jetty.server.Server: jetty-7.x.y-SNAPSHOT INFO [2011-12-03 00:38:32,936] org.eclipse.jetty.server.handler.ContextHandler: started o.e.j.s.ServletContextHandler{/,null} INFO [2011-12-03 00:38:32,999] com.sun.jersey.server.impl.application.WebApplicationImpl: Initiating Jersey application, version 'Jersey: 1.10 11/02/2011 03:53 PM' INFO [2011-12-03 00:38:33,041] io.dropwizard.setup.Environment: GET /emp-details (net.javabeat.dropwizard.resources.EmployeeResource) INFO [2011-12-03 00:38:33,215] org.eclipse.jetty.server.handler.ContextHandler: started o.e.j.s.ServletContextHandler{/,null} INFO [2011-12-03 00:38:33,235] org.eclipse.jetty.server.AbstractConnector: Started BlockingChannelConnector@0.0.0.0:8080 STARTING INFO [2011-12-03 00:38:33,238] org.eclipse.jetty.server.AbstractConnector: Started SocketConnector@0.0.0.0:8081 STARTING

Now your Dropwizard application is now listening on ports 8080 for application requests and 8081 for administration requests.

Note that server employee-details.yml is used for starting the HTTP server and passing the YAML configuration file location to the server. If you are not passing these arguments, you may get the following message in the screen:

usage: java -jar DropWizardExample-1.0.0.jar.jar [-h] [-v] {server} ... positional arguments: {server} available commands optional arguments: -h, --help show this help message and exit -v, --version show the service version and exit

You can access the applications at http://localhost:8080/emp-details or with parameters as http://localhost:8080/emp-details?param1=Ashwanth¶m2=Spring%20Boot . You would see the screen like below:

Excellent!! Finally we have implemented a microservices using dropwizard framework. Now let’s go for a break and have a cup of tea, you have done really good job :).

11. How to Change Context Path

By default, Dropwizard application will start and running in the / . For example, if you are not mentioning anything about the context path of the application, by default the application can be access from the URL http://localhost:8080/ . If you want to configure your own context path for your application, then please add the following entries to your YAML file.

server: applicationContextPath: /application

12. Resources for learning Dropwizard

Here is some of the useful dropwizard tutorials and documentations that will help you to learn dropwizrad framework.

13. Download Source Code

You can download the source code for the above tutorial here:

DropWizard Example 1 file(s) 6.27 KB Download

14. Summary

In this Dropwizard tutorial I have explained the key components and configurations required for running a REST web service using the Dropwizard framework. It includes how to create YAML configuration file, mapping to configuration class, writing application class and creating resource representation and resource class. Finally I have explained the Maven build configuration to build the FAT JAR file and run your application using the command prompt.

I have not covered any of the advanced topics in this tutorial, also I have not tried changing the default settings used for running the service. This tutorial would be very useful for the beginners who are getting started to learn Dropwizard framework. In my next tutorial, I would come up with advanced configurations for running your Dropwizard application.

If you have any questions on microservices framework like Dropwizard or Spring Boot, please post your questions here or drop me a mail.

Thank you for reading my blog!! Happy Learning!!