Skip to main content

Most used JAX-RS 2.0 annotations

Collection of most-used JAX-RS annontations:

Annotation Usage
@Path('<resourcePath>') specifies the relative path of the resource
client uses this relative path to invoke the service
For example it'll be base URL + /resourcePath
https://172.20.126.118:9101/rest/api/bookmarks
https://172.20.126.118:9101/rest/api/bookmarks/1234

To build something like above your resource class should be as follows:
@Path("/bookmarks")
public class BookmarksResource{

 @Path("{bookmarkId}")
 @GET
 public Response getBookmarkById(@PathParam("bookmarkId") Long bookmarkId){
  //get bookmark by id from DB and build response and return
 }

 //invoked when you client uses /bookmarks
 @GET
 public Response getBookmarks(){
  // return all bookmarks
 }
}
@GET Method using the annotation will handle the HTTP GET requests matching
on this resource path

@Path("{bookmarkId}")
@GET
public Response getBookmarkById(@PathParam("bookmarkId") Long bookmarkId){
  //get bookmark by id from DB and build response and return
}
@POST Method using the annotation will handle the HTTP POST requests matching
on this resource path
 @POST
 @Path("/bookmark")
 public Response createBookmark(Bookmark bookmark){
  //create bookmark in DB
 }
@PUT Method using the annotation will handle the HTTP PUT requests matching
on this resource path
 @PUT
 @Path("{bookmarkId}")
 public Response updateBookmark(@PathParam("bookmarkId") Long bookmarkId, Bookmark bookmark){
  //save the updated details using bookmarkId
 }
@DELETE Method using the annotation will handle the HTTP DELETE requests matching
on this resource path
 @DELETE
 @Path("{bookmarkId}")
 public Response deleteBookmark(@PathParam("bookmarkId") Long bookmarkId){
  //delete the bookmark using id and send response message of success/ failure
 }
@HEAD HEAD method is similar to any GET request, except that the server skips the entity-body in your response
and sends only headers information. Following is a HEAD request made to BookmarksResource we built for GET. Notice the way server sent only headers info and completely removed the body


@OPTIONS  This method is used to find out what HTTP methods and other options are available on this resource in server.

@CONNECT  I have never used this in my application and just to be aware it is used by the client to establish
a network connection to a web server over HTTP.
@TRACE This is also one of the less used methods it is used for debugging the request along the path.
@Produces(MediaType.<returnType>) specifies what type of data is returned from the service to the client.

Eg:
@Produces(MediaType.TEXT_XML)
@Produces(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getBookmarks(){
  // return all bookmarks
 }
@Consumes(MediaType.<acceptedType>) specifies the type of data service accepts to process from the client.
@POST
@Path("/bookmark")
@Consumes(MediaType.APPLICATION_JSON)
public Response createBookmark(Bookmark bookmark){
  //create bookmark in DB
}
@PathParam("<paramName>") used to map the path variable to method parameter.
As below the bookmarkId provided in URI path will be mapped to the parameter of the method.
@PUT
@Path("{bookmarkId}")
public Response updateBookmark(@PathParam("bookmarkId") Long bookmarkId, Bookmark bookmark){
      //The bookmarkId will be 1234 as provided in the URL path
      //save the updated details using bookmarkId
}
@QueryParam("<paramName>") Among multiple ways of passing parameters in request query parameters is one of the most used. As other param mappers @QueryParam is also used to bind the query parameters to method parameters however these params will be separated by '?' in the URI as in below.

https://localhost:9101/rest/api/bookmarks?category=java

@GET
public Response getBookmarksByCategory(@QueryParam("category") String category){
  // return all bookmarks filtered by category
}
@MatrixParam Matrix parameters are a set of name-value in URI path which are separated by ";"
The same URI above with a matrix parameter would be:

https://localhost:9101/rest/api/bookmarks;category=java

and it can be accessed as below:
@GET
public Response getBookmarksByCategory(@MatrixParam("category") String category){
  // return all bookmarks filtered by category
}
@HeaderParam This can be used when you want to bind the request header value to a resource method parameter.
Eg: May be when you want to track analytics by browser you can access the user-agent in http header which gives the browser info.
@GET
@Path("/whoHitMe")
public Response whoHitMe(@HeaderParam("user-agent") String userAgent){
  return Response.status(200)
   .entity("invokedBy --> " + userAgent)
   .build();
}
@CookieParam If you have any information stored in cookie you can extract and bind to method parameter using this annotation.

@GET
@Path("/whoAmI")
public Response whoAmI(@CookieParam("samId") String samId){
  return Response.status(200)
   .entity("I am --> " + samId)
   .build();
}

Happy Coding ✌

Comments

Popular posts from this blog

Spring Boot - RestTemplate PATCH request fix

  In Spring Boot, you make a simple http request as below: 1. Define RestTemplate bean @Bean public RestTemplate restTemplate () { return new RestTemplate (); } 2. Autowire RestTemplate wherever you need to make Http calls @Autowire private RestTemplate restTemplate ; 3. Use auto-wired RestTemplate to make the Http call restTemplate . exchange ( "http://localhost:8080/users" , HttpMethod . POST , httpEntity , String . class ); Above setup works fine for all Http calls except PATCH. The following exception occurs if you try to make a PATCH request as above Exception: I / O error on PATCH request for \ "http://localhost:8080/users\" : Invalid HTTP method: PATCH ; nested exception is java . net . ProtocolException : Invalid HTTP method: PATCH Cause: Above exception happens because of the HttpURLConnection used by default in Spring Boot RestTemplate which is provided by the standard JDK HTTP library. More on this at this  bug Fix: This can b...

RADUS#4 - Caching the response in REST API's

  Caching in spring boot app: Caching can be used to provide a performance boost to your application users by avoiding the business logic processing involved again and again, load on your DB, requests to external systems if the users request data that's not changed frequently Different types of caching: We'll be focusing more on in-memory caching in this post i listed other options available to have an idea. In-memory caching You'll have a key-value data stores that stores the response of the request after it is served for the first time There are multiple systems like Redis, Memcached that do this distributed caching very well By default Spring provides concurrent hashmap as default cache, but you can override CacheManager to register external cache providers. Database caching Web server caching Dependencies needed: Maven < dependency > < groupId > org . springframework . boot </ groupId > < artifactId > spring - boot - starter - cache ...

Set BIND VARIABLE and EXECUTE QUERY programmatically in ADF

A very common scenario in ADF is to set a bind variable and execute query programmatically within AMImpl/ VOImpl classes. Here's a simple way to do this: To set bind variable for all rowsets:       ViewObjectImpl someVO = this.getSomeViewObject();       VariableValueManager vMngr = someVO.ensureVariableManager();        vMngr.setVariableValue("DefinedBindVariable",value);        someVO,executeQuery(); To set bind variable for default rowset:          ViewObjectImpl someVO = this.getSomeViewObject();          someVO.setNamedWhereClauseParam("DefinedBindVariable",value);          someVO,executeQuery();