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.
Table of Contents
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.
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.
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.
Service Output
Let’s say we want the output of our web service to look like this.
The corresponding class is straightforward.
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.
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.
That leaves us with three more things to do:
- handle a given timezone from the client
- substitute a default timezone if none is given
- format the current date and time with the timezone
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
.
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.