Nov 8, 2018

RESTful Web Service - JAX-RS Annotations


@PATH(your_path)
@POST
@GET
@PUT
@DELETE
@Produces(MediaType.TEXT_PLAIN[, more-types])
@Consumes(type[, more-types])
@PathParam

@GET

Annotate your Get request methods with @GET.
1
2
3
4
@GET
public String getStatus() {
  ...
}

@Produces

@Produces annotation specifies the type of output this method (or web service) will produce.
1
2
3
4
5
@GET
@Produces("application/xml")
public Contact getXML() {
  ...
}
1
2
3
4
5
@GET
@Produces("application/json")
public Contact getJSON() {
  ...
}

@Path

@Path annotation specify the URL path on which this method will be invoked.
1
2
3
4
5
6
@GET
@Produces("application/xml")
@Path("xml/{email}")
public Contact getEmail() {
  ...
}

@PathParam

@PathParam annotation can bind REST-style URL parameters to method arguments.
1
2
3
4
5
6
7
@GET
@Produces("application/xml")
@Path("xml/{email}")
public Contact getXML(@PathParam("email") String email) {
  Lead lead = leadBean.findByEmail(email);
  return lead;
}
1
2
3
4
5
6
7
@GET
@Produces("application/json")
@Path("json/{email}")
public Contact getJSON(@PathParam("email") String email) {
  Lead lead = leadBean.findByEmail(email);
  return lead;
}

@QueryParam

@QueryParam can be used to accessed request parameters in query string.
1
2
3
4
5
6
7
@GET
@Produces("application/json")
@Path("json/emails")
public Emails getJSON(@QueryParam("limit") int limit) {
  Emails list = new Emails(bean.findEmails(limit));
  return list;
}

@POST

Annotate POST request methods with @POST.
1
2
3
4
5
6
@POST
@Consumes("application/json")
@Produces("application/json")
public RestResponse<Email> create(Email email) {
...
}

@Consumes

The @Consumes annotation is used to specify the MIME media types a REST resource can consume.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Email> update(Email email) {
...
}

@FormParam

@FormParam annotation to bind HTML form parameters value to a Java method.
1
2
3
4
5
@POST
public String search(@FormParam("firstName") String firstName,
    @FormParam("lastName") String lastName) {
      ...
  }

@PUT

Annotate PUT request methods with @PUT.
1
2
3
4
5
6
7
@PUT
@Consumes("application/json")
@Produces("application/json")
@Path("{contactId}")
public RestResponse<Email> update(Email email) {
...
}

@DELETE

Annotate DELETE request methods with @DELETE.
1
2
3
4
5
6
@DELETE
@Produces("application/json")
@Path("{id}")
public RestResponse<Email> delete(@PathParam("id") int id) {
...
}