Categories: RESTTutorial

REST Web Service Tutorial-JAX-RS

Int his REST Web Service tutorial we will demonstrates how RESTful services are created using JAX-RS. We’ll be using Tomcat as our primary application server. Java API for RESTful Web Services (JAX-RS), is a set if APIs to developer REST service. JAX-RS is part of the Java EE6, and make developers to develop REST web application easily.

What Are RESTful Web Services?

RESTful web services are built to work best on the Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability, that enable services to work best on the Web. In the REST architectural style, data and functionality are considered resources and are accessed using Uniform Resource Identifiers (URIs), typically links on the Web. The resources are acted upon by using a set of simple, well-defined operations. The REST architectural style constrains an architecture to a client/server architecture and is designed to use a stateless communication protocol, typically HTTP. In the REST architecture style, clients and servers exchange representations of resources by using a standardized interface and protocol.

The following principles encourage RESTful applications to be simple, lightweight, and fast:

  • Resource identification through URI: A RESTful web service exposes a set of resources that identify the targets of the interaction with its clients. Resources are identified by URIs, which provide a global addressing space for resource and service discovery. See The @Path Annotation and URI Path Templates for more information.
  • Uniform interface: Resources are manipulated using a fixed set of four create, read, update, delete operations: PUT, GET, POST, and DELETE. PUT creates a new resource, which can be then deleted by using DELETE. GET retrieves the current state of a resource in some representation. POST transfers a new state onto a resource. See Responding to HTTP Methods and Requests for more information.
  • Self-descriptive messages: Resources are decoupled from their representation so that their content can be accessed in a variety of formats, such as HTML, XML, plain text, PDF, JPEG, JSON, and others. Metadata about the resource is available and used, for example, to control caching, detect transmission errors, negotiate the appropriate representation format, and perform authentication or access control. See Responding to HTTP Methods and Requests and Using Entity Providers to Map HTTP Response and Request Entity Bodies for more information.
  • Stateful interactions through hyperlinks: Every interaction with a resource is stateless; that is, request messages are self-contained. Stateful interactions are based on the concept of explicit state transfer. Several techniques exist to exchange state, such as URI rewriting, cookies, and hidden form fields. State can be embedded in response messages to point to valid future states of the interaction. See Using Entity Providers to Map HTTP Response and Request Entity Bodies and “Building URIs” in the JAX-RS Overview document for more information.

RESTful web API HTTP methods

Resource GET PUT POST DELETE
Collection URI, such as http://example.com/resources/ List the URIs and perhaps other details of the collection’s members. Replace the entire collection with another collection. Create a new entry in the collection. The new entry’s URI is assigned automatically and is usually returned by the operation. Delete the entire collection.
Element URI, such as http://example.com/resources/item17 Retrieve a representation of the addressed member of the collection, expressed in an appropriate Internet media type. Replace the addressed member of the collection, or if it doesn’t exist, create it. Not generally used. Treat the addressed member as a collection in its own right and create a new entry in it. Delete the addressed member of the collection.

Creating a RESTful Root Resource Class

Root resource classes are POJOs that are either annotated with @Path or have at least one method annotated with @Path or a request method designator, such as @GET, @PUT, @POST, or @DELETE. Resource methods are methods of a resource class annotated with a request method designator. This section explains how to use JAX-RS to annotate Java classes to create RESTful web services.

Developing RESTful Web Services with JAX-RS

JAX-RS is a Java programming language API designed to make it easy to develop applications that use the REST architecture.
The JAX-RS API uses Java programming language annotations to simplify the development of RESTful web services. Developers decorate Java programming language class files with JAX-RS annotations to define resources and the actions that can be performed on those resources. JAX-RS annotations are runtime annotations; therefore, runtime reflection will generate the helper classes and artifacts for the resource. A Java EE application archive containing JAX-RS resource classes will have the resources configured, the helper classes and artifacts generated, and the resource exposed to clients by deploying the archive to a Java EE server.

Annotation Description
@Path The @Path annotation’s value is a relative URI
path indicating where the Java class will be hosted: for example, /helloworld.
You can also embed variables in the URIs to make a URI
path template. For example, you could ask for the name of a user
and pass it to the application as a variable in the URI: /helloworld/{username}.
@GET The @GET annotation is a request method designator and corresponds to the similarly
named HTTP method. The Java method annotated with this request method designator will
process HTTP GET requests. The behavior of a resource is determined by the
HTTP method to which the resource is responding.
@POST The @POST annotation is a
request method designator and corresponds to the similarly named HTTP method. The Java
method annotated with this request method designator will process HTTP POST requests. The
behavior of a resource is determined by the HTTP method to which the
resource is responding.
@PUT The @PUT annotation is a request method designator and corresponds to
the similarly named HTTP method. The Java method annotated with this request method
designator will process HTTP PUT requests. The behavior of a resource is determined
by the HTTP method to which the resource is responding.
@DELETE The @DELETE annotation
is a request method designator and corresponds to the similarly named HTTP method.
The Java method annotated with this request method designator will process HTTP DELETE
requests. The behavior of a resource is determined by the HTTP method to
which the resource is responding.
@HEAD The @HEAD annotation is a request method designator and corresponds
to the similarly named HTTP method. The Java method annotated with this request
method designator will process HTTP HEAD requests. The behavior of a resource is
determined by the HTTP method to which the resource is responding.
@PathParam 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.
@Consumes The @Consumes annotation is used to specify the MIME media
types of representations a resource can consume that were sent by the client.
@Produces The @Produces annotation is used to specify the MIME media types of representations a
resource can produce and send back to the client: for example, “text/plain”.
@Provider The @Provider
annotation is used for anything that is of interest to the JAX-RS runtime,
such as MessageBodyReader and MessageBodyWriter. For HTTP requests, the MessageBodyReader is
used to map an HTTP request entity body to method parameters. On the
response side, a return value is mapped to an HTTP response entity body
by using a MessageBodyWriter. If the application needs to supply additional metadata, such
as HTTP headers or a different status code, a method can return a Response that wraps the entity and that can be built using Response.ResponseBuilder.

Contents-

REST

  1. What is REST and REST Architecture and REST Constraints
  2. JAX-RS & Jersey Hello World Example
  3. Overview of a JAX-RS Application 
  4. Using @Consumes and @Produces to Customize Request and Response 
  5. Annotations for Field and Bean Properties of Resource Classses 


Working with JSON

Create a RESTful Java client to perform “GET” and “POST” request to manipulate json data.

  1. RESTful Web Services with Jersey JAX-RS JSON on Tomcat


RESTful Java clients

Create a RESTful Java client to perform “GET” and “POST” request to manipulate json data.

  1. Create RESTful Java Client With Jersey Client Example 


Working with XML

XML support in JAX-RS.

  1. Using JAX-RS With JAXB 
  2. RESTful Web Services with Jersey JAX-RS using XML on Tomcat 


Basic Examples

Basic annotations and functions to develop REST service.

  1. JAX-RS @Path URI matching example
  2. JAX-RS @PathParam example
    Simple way to inject URI parameter that defined in @Path into Java method.
  3. JAX-RS @QueryParam example
    Example to get query paremeter in URI path, and also how to define an optional paramater.
  4. JAX-RS @MatrixParam example
    Example to get matrix parameters in URI path.
  5. JAX-RS @FormParam example
    Example to get HTML post form parameter values.
  6. Get HTTP headers in JAX-RS
    Show the use of @HeaderParam and @Context to get HTTP headers.
  7. Download text file from JAX-RS
    Example to output a text file for user to download.
  8. Download image file from JAX-RS
    Example to output an image file for user to download.
  9. Download pdf file from JAX-RS
    Example to output pdf file for user to download.
  10. Download excel file from JAX-RS
    Example to output excel file for user to download.

References
1. JAVA REST Web Services
2. Wikipedia for REST Web Service

 

<<Previous <<   || Index ||   >>Next >>
Previous
Next
Dinesh Rajput

Dinesh Rajput is the chief editor of a website Dineshonjava, a technical blog dedicated to the Spring and Java technologies. It has a series of articles related to Java technologies. Dinesh has been a Spring enthusiast since 2008 and is a Pivotal Certified Spring Professional, an author of a book Spring 5 Design Pattern, and a blogger. He has more than 10 years of experience with different aspects of Spring and Java design and development. His core expertise lies in the latest version of Spring Framework, Spring Boot, Spring Security, creating REST APIs, Microservice Architecture, Reactive Pattern, Spring AOP, Design Patterns, Struts, Hibernate, Web Services, Spring Batch, Cassandra, MongoDB, and Web Application Design and Architecture. He is currently working as a technology manager at a leading product and web development company. He worked as a developer and tech lead at the Bennett, Coleman & Co. Ltd and was the first developer in his previous company, Paytm. Dinesh is passionate about the latest Java technologies and loves to write technical blogs related to it. He is a very active member of the Java and Spring community on different forums. When it comes to the Spring Framework and Java, Dinesh tops the list!

Share
Published by
Dinesh Rajput

Recent Posts

Strategy Design Patterns using Lambda

Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…

2 years ago

Decorator Pattern using Lambda

Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…

2 years ago

Delegating pattern using lambda

Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…

2 years ago

Spring Vs Django- Know The Difference Between The Two

Technology has emerged a lot in the last decade, and now we have artificial intelligence;…

2 years ago

TOP 20 MongoDB INTERVIEW QUESTIONS 2022

Managing a database is becoming increasingly complex now due to the vast amount of data…

2 years ago

Scheduler @Scheduled Annotation Spring Boot

Overview In this article, we will explore Spring Scheduler how we could use it by…

3 years ago