About Mike Christianson

Mike Christianson is a Senior Software Engineer focused on customers and craftsmanship. He also leads the Phoenix Software Engineering Reading Group.

Dropwizard: painless RESTful JSON HTTP web services

Java developers looking for a quick, painless way of creating production-ready RESTful JSON HTTP web services should consider the Dropwizard framework. Dropwizard brings together well-regarded libraries that compliment each other so you can get to what’s important: writing and delivering working code. For those interested in details on the libraries used, please refer to the Dropwizard overview. Fortunately, Dropwizard doesn’t make you deal with all of its individual components. You’ll be able to keep your focus on your work at hand. If you’ve got some time, stick around and let’s make something with Dropwizard.

All code for this tutorial is available at GitHub.

 

How do you get started with Dropwizard?

A single Maven, Gradle, or Ivy dependency will get you all the components necessary for making Dropwizard-powered web services.

<dependency>
    <groupId>com.yammer.dropwizard</groupId>
    <artifactId>dropwizard-core</artifactId>
    <version>0.6.2</version>
</dependency>

Note: Please refer to Dropwizard’s excellent documentation if you encounter anything you think isn’t explained sufficiently in this short posting.

What shall we make?

Let’s make a web service that returns the current date and time for a given timezone. We’ll use a configurable default timezone if a client decides not to specify one.

Configuration

Our super-simple time-service.yml configuration file will look like this.

defaultTimezone: UTC

Behind the scenes, Dropwizard will load, parse, validate, and turn that configuration into an object. All we need to do is specify it as a class.

public class TimezoneConfiguration extends Configuration {
    @NotEmpty
    @JsonProperty
    private String defaultTimezone;

    public String getDefaultTimezone() { return defaultTimezone; }
}

Service Output

Let’s say we want the output of our web service to look like this.

{ "time": "2014-02-04 13:45:02" }

The corresponding class is straightforward.

public class Time {
    private final String time;

    public Time(String time) {
        this.time = time;
    }

    public String getTime() { return time; }
}

Resource

Next, we decide we want the URL path for our web service to be /time. And we need to specify the resource will return JSON. Putting those together gives us this.

@Path("/time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeResource {
}

The only RESTful action that makes sense right now for our demo web service is GET, so let’s make a method for that. When consuming our web service, the client can provide a timezone as a query string parameter.

@GET
public Time getTime(@QueryParam("timezone") String timezone) {
}

That leaves us with three more things to do:

  1. handle a given timezone from the client
  2. substitute a default timezone if none is given
  3. format the current date and time with the timezone
@Path("/time")
@Produces(MediaType.APPLICATION_JSON)
public class TimeResource {
    private final String defaultTimezone;

    public TimeResource(String defaultTimezone) {
        this.defaultTimezone = defaultTimezone;
    }

    @GET
    public Time getTime(@QueryParam("timezone") Optional timezone) {
        DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        TimeZone timeZone = TimeZone.getTimeZone(timezone.or(defaultTimezone));
        formatter.setTimeZone(timeZone);
        String formatted = formatter.format(new Date());
        return new Time(formatted);
    }
}

Service

Now, let’s bring together all the pieces of our web service in our entry-point class we’ll call TimeService. Here we’ll use our TimezoneConfiguration to pass the default timezone to TimeResource.

public class TimeService extends Service {
    public static void main(String[] args) throws Exception {
        new TimeService().run(args);
    }

    @Override
    public void run(TimezoneConfiguration config, Environment environment) {
        String defaultTimezone = config.getDefaultTimezone();
        TimeResource timeResource = new TimeResource(defaultTimezone);
        environment.addResource(timeResource);
    }

    @Override
    public void initialize(Bootstrap timezoneConfigurationBootstrap) {
    }
}

Pencils Down

That’s it! We’ve just written a Dropwizard-based web service without mind-numbing boilerplate or mounds of obtuse XML configuration.

Running

Running your web service is as simple as executing a command-line Java application – no need to worry about .war files or servlet containers.

java -cp libraries/* name.christianson.mike.TimeService server time-service.yml

Now, point your web browser or curl at http://localhost:8080/time?timezone=MST and have fun!

  • All code for this tutorial is available at GitHub.
Reference: Dropwizard: painless RESTful JSON HTTP web services from our JCG partner Mike Christianson at the CodeAwesome blog.
Related Whitepaper:

Functional Programming in Java: Harnessing the Power of Java 8 Lambda Expressions

Get ready to program in a whole new way!

Functional Programming in Java will help you quickly get on top of the new, essential Java 8 language features and the functional style that will change and improve your code. This short, targeted book will help you make the paradigm shift from the old imperative way to a less error-prone, more elegant, and concise coding style that’s also a breeze to parallelize. You’ll explore the syntax and semantics of lambda expressions, method and constructor references, and functional interfaces. You’ll design and write applications better using the new standards in Java 8 and the JDK.

Get it Now!  

One Response to "Dropwizard: painless RESTful JSON HTTP web services"

  1. Ali says:

    Thank you for your articles. I leave a comment for tracking other comments. as it seems there is no comments feed or a feature to register an email without commenting to notify about followup comments.

Leave a Reply


× five = 25



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books