Java Reference
In-Depth Information
You have seen some simple URI constructions that consist of one resource noun and a URI variable.
How do you deal with a more complicated URI, such as
GET /users/123456/followers/456789
?
You do it in the same way as before, just with a slightly more complicated
@Path
and
@PathParam
.
@GET
@Path("/{user_id}/followers/{follower_id}")
@Produces(MediaType.APPLICATION_JSON)
public Response getUser(
@PathParam("user_id") String user_id,
@PathParam("follower_id") String follower_id)
You have looked in detail at the
GET
HTTP method. What about the
POST
,
PUT
, and
DELETE
methods? To write a method that responds to an HTTP
POST
request, you do almost the same as
you would with
GET
, but you change two elements. You annotate the method with
@POST
instead of
@GET
and
@Consumes
in place of
@Produces
. Here's a simple example:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Path("/{user_id}/followers/")
public Response createUser(@PathParam("user_id") String user_id, String body)
This example works in the same way as for the
GET
methods, but notice that there is no explicit
mapping of the HTTP request body to a method parameter. The mapping is implicit. The content of
the HTTP body is passed to the only unannotated parameter that it i nds in the method signature.
No more than one is allowed to avoid confusion.
The
PUT
and
DELETE
HTTP methods operate in a similar way to the
POST
method.
Your URI may contain query parameters. You can retrieve these from the URI by annotating a
parameter in the method signature with
@QueryParam("page")
. This annotation retrieves the page
query parameter from the URI
/users?page=10
.
There are many more annotations in the JAX‐RS API that facilitate the design of a good RESTful
API. It's recommended that you familiarize yourself with all of them.
HATEOAS
As has already been discussed, HATEOAS is at the highest level of REST implementation in the
Richardson Maturity Model and should be considered the nirvana of RESTfulness.
Imagine that a client requests a resource that represents all the posts in the system that the user has
permission to view. The URI would be
GET /posts
, and the response, if successful, might return
with the following HTTP body:
{
"posts": [
{
"id": 71892,
"title": "Best movie of 2015",
"content": "I think the best movie of 2015 is the Golden Egg of Siam.",
"links": [
{