RESTful Webservices - JAX-RS Annotations

rest_annotations_in_java_jax-rs

Before directly jumping into the REST annotations of JAVA , lets see 3 important points which form the basis of your understanding .

1) REST ( Representational State Transfer ) is an architectural style for implementing web services

2) JAX-RS ( Java API for RESTful Web Services ) is a Java API or Specification for implementing REST in JAVA.

3) JAX-RS uses annotations introduced as part of JSE 5(Java Standard Edition 5) to simplify the development and deployment of Webservices.

List of JAX-RS Annotations :

Annotations which help us to map a resource class and its methods as web resources

Annotation Java Import Statement Description
@Path import java.ws.rs.Path; Specifies the relative path for a resource or class
@GET
@PUT
@POST
@DELETE
import java.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.POST;
import javax.ws.rs.DELETE;
Specifies the HTTP request type of a resource.
@Produces import javax.ws.rs.Produces; Specifies the MIME media type of the response
@Consumes import javax.ws.rs.Consumes; Specifies the MIME media type of the request

Annotations for method parameters to get values from a request

Annotation Java Import Statement Description
@PathParam import javax.ws.rs.PathParam; Binds the method parameter to a path segment
@QueryParam import javax.ws.rs.QueryParam; Binds the method parameter to the value of an HTTP query parameter
@MatrixParam import javax.ws.rs.MatrixParam; Binds the method parameter to the value of an HTTP matrix parameter
@HeaderParam import javax.ws.rs.HeaderParam; Binds the method parameter to an HTTP header value
@CookieParam import javax.ws.rs.CookieParam; Binds the method parameter to a cookie value
@FormParam import javax.ws.rs.FormParam; Binds the method parameter to a form value
@DefaultValue import javax.ws.rs.DefaultValue; Specifies the default value for a method parameter
@Context import javax.ws.rs.core.Context; Returns the entire context of the object

@Path

@Path  Specifies the relative path for a resource or class

Example Resource URL for calling getAllEmployees() : http://example.com/company/allemployees

// The Java class will be hosted at the URI path "/company"
@Path("/company")
public class CompanyResource {
 @GET
 @Produces("text/xml")
 @Path("/allemployees")
 public String getAllEmployees() {
        -----------------------
 }
}

@PathParam

Annotate request method parameters with @PathParam  to extract the values from request path.

@GET
@Produces("application/xml")
@Path("/employeeInfo/{id}")
public Employee getEmployeeById(@PathParam("id") String id) {
       return employeeService.findById(id);
}

@Produces

@Produces  specifies the MIME type of a response that reaches at the client

@GET
@Produces("application/xml")
public Employee getCEODetails() {
       return employeeService.getCEO();
}
@GET
@Produces("application/json")
public Employee getCEODetails() {
       return employeeService.getCEO();
}

@Consumes

Annotate a resource method with @Consumes  to specify the MIME type that it can consume.

@POST
@Consumes("application/xml")
public void post(String data) {
       ----------------------
}

 

HTTP Methods

@GET  @POST  @PUT  @DELETE  are request method designator annotations which correspond to the similarly named HTTP methods.

@GET

Annotate HTTP GET request methods with @GET

@GET
@Produces("application/json")
public EmployeeList getAllEmployees() {
       ---------------
}

@PUT

Annotate HTTP PUT request methods with @PUT

@PUT
@Path("/update/{employeeId}")
public Response update(@PathParam String employeeId, Employee employee) {
       --------------
}

@POST

Annotate HTTP POST request methods with @POST

@POST
@Consumes("application/xml")
public Response create(String content) {
       ------------------------
}

@DELETE

Annotate HTTP DELETE request methods with @DELETE

@DELETE
@Path("delete/{employeeId}")
public Response deleteEmployee(@PathParam String employeeId) {
       ---------------------
}

@QueryParam

@QueryParam  annotation is used to extract the query parameters from the query component of the request URL.

Example request URL : http://example.com/company/allemployees?minSalary=2000

@GET
@Produces("application/json")
@Path("/company/allemployees")
public EmployeeList getEmployeeList(
                                    @QueryParam("minSalary") Double minSalary
                                   ) {
       EmployeeList list = companyService.getAllEmployeesWithMinSalary(minSalary);
       return list;
}

@MatrixParam

@MatrixParam  annotation is used to extract the matrix parameters from the request URL.

Example request URL : http://example.com/about;author=prashanth;country=india

@GET
@Produces("application/xml")
@Path("/about")
public Author about(
                    @MatrixParam("author") String author, @MatrixParam("country") String country
                   ) {
       Author author = authorService.about( author, country );
       return author;
}

@HeaderParam

@HeaderParam  binds the value(s) of a HTTP header to a resource method parameter or resource class field

@Get
@Produces("application/xml")
@Path("/getForms")
public Forms getFormsBasedOnUserAgent(
                                      @HeaderParam("user-agent") String userAgent
                                     ) {
       --------------------
}

@CookieParam

Annotate resource method parameter with @CookieParam  annotation to get the cookie parameter value.

@GET
@Produces("application/xml")
@Path("/getProfile")
public Response getProfile(
                           @CookieParam("userId") String id)
                          ) {
       -----------------------
}

@FormParam

Annotate method parameters with @FormParam  to extract the parameters from the POSTed form data.

@POST
@Consumes("application/x-www-form-urlencoded")
public Response updateEmployee(
                               @FormParam("eid") String empId, @FormParam("ename") String name
                              ) {
       ------------------------
}

@DefaultValue

@DefaultValue  annotation is used on method parameter to specify the default value.

Marked line in the below snippet would assign the value 1000 to minSalary(method parameter) in case of non-existence of the minSalary parameter in the request path.

@GET
@Path("/company/allemployees")
@Produces("application/json")
public Employee getEmployeeInfo( @PathParam String id,
                                 @Default("1000") @QueryParam Double minSalary
                               ) {
       EmployeeList list = companyService.getAllEmployeesWithMinSalary(minSalary);
       return list;
}

@Context

@Context  annotation retrieves the java types related to a request or response.

The javax.ws.rs.core.UriInfo interface provides information about the components of a request URI.

The javax.ws.rs.core.HttpHeaders interface provides information about request headers and cookies.

@GET
@Path("/getUser")
@Produces("application/xml")
public Response getUser(
                        @Context UriInfo ui
                       ) {
       MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
       MultivaluedMap<String, String> pathParams = ui.getPathParameters();
       ----------------------------
}

 

References :

https://wikis.oracle.com/display/Jersey/Overview+of+JAX-RS+1.0+Features

http://docs.oracle.com/javaee/6/tutorial/doc/gkkrb.html

http://en.wikipedia.org/wiki/Java_API_for_RESTful_Web_Services

 

Submit a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

www.000webhost.com