Java REST tutorial

Create a RESTful API Using Java and Jersey in IntelliJ Idea.



Take Five — REST in Five Minutes

Let’s face it — now that web Services written in crufty old XML are yesterday’s news, we all want to be hanging out with the cool kids writing RESTful APIs that use JSON. Best of all, because Java’s JAX-RS specification makes RESTful APIs so easy to create and test, hanging out with the cool kids who are writing RESTful APIs turns out to be a good deal easier than hanging out with the cool kids ever was in high school.

This tutorial is an easy and 100%-wedgie-free way to create a RESTful API using Jersey, the reference implementation for the JAX-RS specification.

REST is an architectural style which favors APIs that exposes resources through standard HTTP verbs. REST APIs are stateless, i.e., every request should carry sufficient information to execute the request without resorting to a session on the server side, including authentication information. (Note that in the spirit of a “Hello world” tutorial, we won’t get into RESTful authentication in this article. We may take this up in a later article, but for now we refer you to the Jersey Security page.)

Though not strictly speaking a requirement, combinining JSON with REST is a popular choice since it makes RESTful APIs Javascript and mobile-app friendly.

A resource can be anything, a person, a todo list item, a contact in an address book. The simplicity of REST is that resources can be read or manipulated using only four HTTP verbs. RESTful clients submit the following verbs:

  • POST — to create a new resource.
  • GET — to read (return) a single resource or a list of resources.
  • PUT — to update an existing resource.
  • DELETE — to delete a resource.

Keeping It Simple – No Database Connection Needed

Let’s start with some example resource, a task. A task has an id, a description, and the email address of the person to whom it is assigned.

Our API will allow us to perform CRUD (Create, Read, Update, and Delete) operations using our four HTTP verbs, but to keep things simple our entire “model layer” consists of the world’s dumbest in-memory, NoSQL database — a simple map of keys to values. We even start out with a test object pre-populated, so we’re not standing on ceremony here. The important point is to create a class that can act like a database class might act — returning a list of all the objects, returning a single object by a primary key, etc.

Setting up the Jersey Project in Maven and IntelliJ Idea

We’ll be using Maven and IntelliJ idea to build and run our project. Here’s the Maven pom.xml file:

As you can see we’ve taken the strange step of excluding our only unit test from the Maven build. The reason for this is that our “unit test” is really more of an integration test because it is a RESTful client that relies on the Tomcat server running the application.

The procedure for importing the POM file into an Idea project is documented here, but since you’ll also be needing configuration to run the web application in Tomcat and to run the client side test, the easiest thing to do at this point is to fork the project from Github and open the project in IntelliJ Idea.

The Restful API

To make the Jersey magic happen, we set up a base URL on our web server “/webapi/*”. Any requests underneath that base pattern will be handled by Jersey’s ServletContainer class, which will know how to handle the RESTful API we’ll develop. To do this, we the web.xml shown below into src/main/webapp/WEB-INF:

The Jersey ServletContainer works in conjunction with annotations we’ll import from the package, javax.ws.rs. It will scan the package we’ve specified, com.codesolid.tutorials.restfulwebservice, for Jersey provider files.For example, our API is defined in the file TaskRestfulService.java, shown below:

The @Path(“tasks”) annotation marks the class as a resource that Jersey’s ServletContainer will serve for us. Because we earlier specified /webapi as our root all our resources, the path string here, “tasks” this will get tacked on to the end of that, so the relative URLs for our task resource will look like with “/webapi/tasks”.

Inside the class we declare a model object for our “database”, and we see our first RESTful method (below). There’s no additional path annotation here, just an annotation @GET, so the result is that a simple GET on /webapi/tasks/ returns a list of all the tasks object we have in memory.

Because our file imports org.codehaus.jackson.map.ObjectMapper, and because we’ve used the annotation “@Produces(MediaType.APPLICATION_JSON)”, even though we’re returning a list of Task objects from the method, Jersey’s going to be kind enough to use Jackson to automagically convert your objects to JSON strings.

Don’t you love it when things just go your way?

Returning a single object from our API via a GET request is also straightforward because it’s almost identical to our first method. All we need to add is a way to specify an id for the object we want. We use @Path(“{id}”) to specify a path variable parameter, so our GET URL becomes /webapi/tasks/{id}, where {id} is some primary key for the object. We then use the expression “@PathParam(“id”) Integer id” to have Jersey read the id into an Integer variable we can pass to the model.

Once again, conversion to JSON will be automatic in this case.

In our handler to POST a new Task object, to give you an idea of what’s going on behind the scenes, we make our code considerably more verbose by handling the JSON conversion to a Java object ourselves.

Our verbose POST method is equivalent to the much more eye-friendly:

Strictly speaking, PUT is used to update a new task. We read the id from the URL and ensure that that’s the id of the task we’re updating. We don’t return the new task. According to the HTTP Protocol Standard, however, PUT can also be used to store a new resource.

And of course, we need a way to bid our objects a fond (or not) farewell.

Testing the Server: A Jersey REST client

In addition to being a fine API for easily setting up a RESTful API on the Server side, Jersey provides excellent services that you can use to create a RESTful client. In the next listing, we show how to construct an integration test to exercise our client. Each of our methods tests a specific part of the API, with the HTTP verb in caps, for example “canPOSTaNewTask” or “canGETaTaskList”. We use the Jackson ObjectMapper to convert our entities to and from the JSON our REST API consumes.

Putting it All Together

We’ve bundled it all up for you in a ZIP file download that has everything you need to get started. (If you prefer, you can [browse the code](https://github.com/CodeSolid/tutorials/tree/master/RestfulWebService) on Github.)

In the IntelliJ project, you’ll need to re-point your Tomcat instance to a Tomcat instance running on your local machine (Run / Edit Configurations / Tomcat Server / Tomcat7 then press the “Configure button” to set up your Tomcat instance). In the Run dropdown, select Tomcat first and run that, and once Tomcat runs up your integration tests should all be green.

If you enjoyed this tutorial, we’ll happily accept Github love via the links below. (Shameless, I know, but thanks!)



Leave a Reply