An Introduction to JAX-RS Annotations (Part 1)
The JAX-RS API forms an important part of the Java EE platform's commitment to providing standards-driven technology. The ubiquitous nature of the Internet and that recent increasing interest in the microservice architecture has put more focus on small, scalable, autonomous services and their interoperability. The principal methodology used to allow microservices to communicate with each other and the ‘outside world’ is REST and its use in developing RESTful APIs. The technology that Java EE provides for this is the JAX-RS: Java API for RESTful Web Services.
The Goals of JAX-RS
The goals of the JAX-RS API are:
- POJO-based: To provide a collection of classes/interfaces and associated annotations to be used with POJOs so as to expose them as Web resources.
- HTTP-centric: To use HTTP as the underlying network protocol and provide a clear mapping between HTTP and URI elements and the corresponding API classes and annotations.
- Format independence: To be applicable to a wide variety of HTTP entity body content types and provide the necessary pluggability to allow additional types to be added.
- Container independence: To ensure that artifacts using the API are deployable in a range of Web servers.
- Inclusion in Java EE: To allow Java EE features and components to be used within a Web resource class.
Overview of JAX-RS Annotations
Annotations in the JAX-RS API are used to provide meta-data around the web resource. A typical example is to use the @GET annotation with the @Path annotation to identify the method that should handle a GET request to the specified URI in the @Path annotation.
What follows is a very quick overview of the annotations available to mark the methods and classes used to construct web resources. This is not an exhaustive list, there are a few more annotations in the JAR-RS arsenal, however, as the majority of the work of JAX-RS is in configuration and handling web resources, this is where you will find the majority of the API's annotations put to use.
This is the first in a three-part series looking at JAX-RS annotations.
Part two covers:
- The @Path Annotation and @PathParam
- The @QueryParamter Annotation
- The @Produces Annotation
- The @Consumes Annotation
Part three covers:
- The @FormParam Annotation
- The @MatrixParam Annotation
- The @CookieParam Annotation
- The @HeaderParam Annotation
- The @Provider Annotation
Let’s get started.
The @ApplicationPath Annotation
Let’s start at the top of the trees with the @ApplicationPath annotation:
@ApplicationPath("/api")
public class RESTConfig extends Application {}
This is where you start defining the URI to your resources. Here we are saying that all our resources are to be found at the root /api. The URL should look something like this: http://localhost:8080/webcontext/api/ where webcontext is the name of your application.
The @Path Annotation
Next, comes the URI path to the resource. In a bookshop application, this might be /books/.
@Path("/books")
public class BookResource {}
Now, the URI to the book resource is /api/books and the URL would be http://localhost:8080/webcontext/api/books. It is the convention to name the resource as a noun and in the plural.
Once the path to our resource has been defined the individual resource method are configured for the HTTP method and context type. This is where the fun begins.
There is an annotation for each of the HTTP methods.
The @GET HTTP Method Annotation
Methods annotation with the @GET annotation respond to HTTP get requests.
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getAllBooks() {
List<Book> books = BookRepository.getAllBooks(); // queries database for all books
GenericEntity<List<Book>> list = new GenericEntity<List<Book>>(books) {};
return Response.ok(list).build();
}
Note that the GenericEntity wrapper is used to maintain the generic type of the List as Book.
The @POST HTTP Method Annotation
Methods annotated @POST respond to POST method requests.
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveBook(Book book) {
book = bookRepository.saveBook(book);
return Response.ok(book).build();
}
The POST HTTP method is commonly used to create a resource. This example code persists the new book object in the database.
The @PUT HTTP Method Annotation
The @PUT annotation is used for updating a record and method annotated this way respond to an HTTP PUT request.
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateBook(Book book) {
book = bookRepository.updateBook(book);
return Response.ok(book).build();
}
The @DELETE HTTP Method Annotation
Methods annotated @DELETE are expected to delete a resource.
@DELETE
@Path("{isbn}")
@Produces(MediaType.APPLICATION_JSON)
public Response deleteBook(@PathParam("isbn") String isbn) {
Book book = bookRepository.deleteBookByIsbn(isbn);
return Response.ok(book).build();
}
Usually, the resource or its id is passed to the resource method parameter from the URI variable as you can see in this example.
The @OPTIONS HTTP Method Annotation
Methods annotated with @OPTIONS respond to HTTP Option requests.
@OPTIONS
public Response preflight() {
return Response.ok().header("Allow", true).build();
}
The options method is used as a request when the client wishes to make a complex HTTP request to a different domain. It is done in order to determine if the client is allowed to make the request or not.
The @HEAD HTTP Method Annotation
The HTTP HEAD method is identical to HTTP GET method except that the server mustn’t respond with a body in the response.
@HEAD
public Response headsUp() {
return Response.ok().build();
}
This method is to obtain meta-data regarding the entity without sending back the entity body itself.
Code Repository
The source code for this article is in my GitHub repository. Code for all my articles is in the ReadLearnCode Articles repository.
What Next?
That is it for part one, coming up next is part two where you will learn more about the annotations used to make RESTful web endpoints.
Further Reading
I have published more articles about JAX-RS which I hope you find interesting:
- JAX-RS Resource Entities is an article about creating resource entities
- Ever wondered what @javax.ws.rs.core.Context annotation is all about?
- Learn more about @Consumes and @Produces annotations, and finally
- You cannot write robust endpoints without knowing about bean validation failure management