RESTful

RESTful Service in Java

Posted on Updated on

RESTful Service in Java.

Table of Contents:-

  1. What is RESTful service in Java ?
  2. How to implement it in Web Application ?

 

What is RESTful service in Java ?

Representation state transfer(REST) is architecture style that specifies constraints i.e Uniform resource identifier(URI). REST architecture style represents data,functionality as resources that are accessed by URI. REST create a bridge between Client/Server architecture and communicate over stateless HTTP protocol and Client/Server exchange representation  resources by using standardized interface and protocol.

URL ( Uniform Resource Locator ) formation :-

URL : <Protocol> ://< Hostname> :< port>/<Context-name>/<URL>

http://localhost:8080/RESTfulExample1/rest/user/102

RESTful ( JAX-RS) annotation summary :-

  • @path : – It’s used to represents an URI path template which the resource response it.
  • @consume :- It’s used to specify MIME media type representation of a resource can consume that were sent by client.
  • @produce :- it’s used to specify MIME media type representation of a resource can produce that send back to client like “application/json”,”application/text”.
  • @ParamPath :- The @PathParam annotation is a type of parameter that you can extract for use in your resource class.URI path parameters are extracted from the request URI, and the parameter names correspond to the URI path template variable names specified in the @Path class-level annotation.
  • @QueryParam :- The @QueryParam annotation is a type of parameter that you can extract for use in your resource class. Query parameters are extracted from the request URI query parameters.
  • @Context :- @Context can be used to obtain contextual Java types related to the request or response.

How to convert an Object into Response Type (“JSON/Text/Xml”):-

Using javax.ws.rs.core.Response , contract between a returned instance and the runtime when an application needs to provide metadata to the runtime.

@GET
 @Produces(MediaType.APPLICATION_JSON)
 public Response getUsers(){
 return Response.ok().entity(userRepo.getAllUsers()).build();
 }

HTTP methods :-

  • GET : – it’s used to read a specified resource.
  • POST :- it’s used to create a specified resource.
  • PUT :-  it’s used to update a specified resources
  • DELETE :-it’s used to delete a specified resources
  • HEAD :- Same as GET but returns only HTTP headers and no document body

Key Points :-

  • It’s not a protocol.
  • It’s a architecture style that represent a resources that are accessed by URI.
  • Communication over HTTP is stateless.
  • It’s scalable,reliable and portable by nature.

Example with source code below :

  1. RESTful example with Tomcat and Maven.