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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

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


× one = 9



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
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.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close