The presentation discusses the basic REST principles and how to define a RESTful API.
The presentation then looks at the various facilities provided by JAX-RS for developing REST API using Java.
All the supported annotations and its usage are discussed with example
2. JERRY KURIAN. OVER 20 YEARS EXPERIENCE.
TECHNOLOGY INNOVATOR & ENTREPRENEUR
Started coding with an Intel 486 machine more than 25
years back and enjoying it ever since. Developed using
VB, Pascal, C++, Java Enterprise and OSS, Scala,
Node JS and the saga continues. Started using Spring,
hibernate before it became hip. Started using Scala
when it was in its infancy. After spending 8 years working in various
software companies like Huawei Tech, Quidnunc
across UK, US, China and India, the
entrepreneurship bug bit in 2006 (before it was
hip!!). Built one of the pioneers in SMS social
network called CellZapp, I developed the
product on my own and sold it to marquee
customers like ESPN and Hungama Digital.
Recently launched a product in field informatics
www.isense-tech.co.in. Successfully launched
across 3 pilot customers and on track to sign up
more.
A family man with two kids, I am a passionate
weekend cricketer and an involved dad. I urge my
two sons to follow their dreams, which they do by
staying out of the conventional schooling system
and exploring their passion at a democratic free
school called BeMe. Check it out at
http://beme.org.in
4. WHY REST?
Web is one of the most successful “app” out there
The web has grown exponentially and shows no
sign of stopping
All apps need to learn and adopt from the
underlying architectural principles of the web to be
able to grow similarly
The set of these architectural principles is
called REpresentational State Transfer (REST)
5. REST PRINCIPLE
Addressable resources
The key abstraction of information and data in REST is a
resource, and each resource must be addressable via a URI
(Uniform Resource Identifier).
A uniform, constrained interface
Use a small set of well-defined methods to manipulate your
resources.
Representation-oriented
You interact with services using representations of that
service. For example, browsers need HTML, JavaScript
needs JSON.
Communicate statelessly
Stateless applications are easier to scale.
Hypermedia As The Engine Of Application
State (HATEOAS
Let your data formats drive state transitions in your
applications.
6. ADDRESSABILITY
Addressability is the idea that every object and
resource in your system is reachable through a
unique identifier.
For an SOA, the means to discover a service or
resource is a big problem and addressability
through an identifier is an ideal solution
In the REST world, addressability is managed
through the use of URIs
scheme://host:port/path?queryString#fragment
7. UNIFORM INTERFACE VIA HTTP
REST isn’t protocol specific
But REST over HTTP is the most common way in which
REST applications are developed
There have been other specifications that have
enabled distributed application development over
web
WS-* and SOAP have been most popular. It also used
HTTP but more as a transport later to bypass the
firewalls
REST uses HTTP as a very rich application
protocol that provides multitude of interesting and
useful capabilities for application developers
10. HTTP - METHODS
GET
GET is a read-only operation. It is used to query the server for specific
information. It is both an idempotent and safe operation
PUT
PUT requests that the server store the message body sent with the
request under the location provided in the HTTP message. It is usually
modelled as an insert or update. It is also idempotent.
DELETE
DELETE is used to remove resources. It is idempotent as well.
POST
POST is the only non-idempotent and unsafe operation of HTTP. Each
POST method is allowed to modify the service in a unique way.
HEAD
HEAD is exactly like GET except that instead of returning a response
body, it returns only a response code and any headers associated with
the request.
OPTIONS
OPTIONS is used to request information about the communication
options of the resource you are interested in.
Idempotent means that no matter how many times you apply the operation, the result is always the same
11. REPRESENTATION ORIENTATION
With a GET operation, you receive a representation
of the current state of a resource.
A PUT or POST passes a representation of the
resource to the server so that the underlying
resource’s state can change
In a RESTful system, the complexity of the client-
server interaction is within the representations
being passed back and forth. These
representations could be XML, JSON, YAML, or
really any format you can come up with.
12. HATEOAS
The final principle of REST is the idea of using
Hypermedia As The Engine Of Application State
(HATEOAS).
Hypermedia and Hyperlinks compose complex sets
of information from disparate sources.
<order id="111">
<customer>http://customers.myintranet.com/customers/32133</customer>
<order-entries>
<order-entry>
<quantity>5</quantity>
<product>http://products.myintranet.com/products/111</product>
13. DEVELOPING A RESTFUL JAVA APP
For a Java programmer, the ideal scenario is to
ensure they stick to Java as much as possible
As with frameworks and specs like Hibernate and
JPA, which bridges the Relational database world
with Java world, we need a way to do REST
programming using mainly Java constructs
The steps to developing RESTful application are as
follows
14. STEPS TO DEVELOPING RESTFUL APPS
Define object
model
Model the URIs
Define
representation
format
Assign HTTP
methods
15. DEFINE OBJECT MODEL
Developing enterprise applications often start with
defining its object model
The object model defined for an application can be
used to define the various resources in our RESTful
application too
Consider a typical Order entry system.
Each order in the system represents a single
transaction or purchase and is associated with a
particular customer. Orders are made up of one or more
line items. Line items represent the type and number of
each product purchased.
17. MODEL THE URIS
Java addresses a class or an entity via its package
and class name
This format is well known within a JVM for a class
to access another class
How do you make a Java class representing a
resource be known and accessible over the web?
The answer lies in providing a URI for the java
based resources
18. URIS
In our object model, we will be interacting
with Orders, Customers, and Products
We can make these resources addressable as
follows
/orders
/orders/{id}
/products
/products/{id}
/customers
/customers/{id}
19. DEFINE REPRESENTATIONAL DATA FORMAT
Within JVM, two objects talk to each other through
the state of the object or by serializing/de-serializing
object over the wire
How can the state of a Java object be made known
to a client over the web?
The representation of the state of a resource is one
of the most important things to do in a RESTful
application
XML and JSON are two of the most popular way to
represent the resource states
22. ASSIGNING HTTP METHODS
The URIs defined earlier are a means to access as
well as perform operations on the resources
A client typically would want to perform CRUD
operations on the resources
To obtain all the products, you would typically
define GET method on the URI
GET /products HTTP/1.1
To limit the number of products returned, we can
pass the limiting parameters as query parameters
GET /products?startIndex=0&size=5 HTTP/1.1
23. HTTP METHODS
To obtain an individual product, the GET operation
would be defined as
/products/{id}
GET /products/233 HTTP/1.1
To create a new product, use the PUT operation
PUT /products/664 HTTP/1.1
Drawback of using PUT is that the client is expected to
generate the ID of the new resource
POST can also be used to create a new resource
24. HTTP METHODS
Updating a resource can be achieved via a PUT
method
To delete a resource, use the DELETE method
DELETE /orders/233
Cancellation of a resource is also update of a state
and can be achieved through DELETE with specific
query parameter
DELETE /orders/233?cancel=true
25. OPERATIONS ON RESOURCES
We might need to perform operations on resources
that do not strictly result in update of resource
states
Eg of an operation would be purging of a resources,
which ultimately updates states of multiple
resources
We can model operations as sub-resources and
trigger a POST operation
POST /orders/purge HTTP/1.1
The sub-resource URI can be further extended to
add interfaces as desired
27. FIRST APPLICATION
Create the model class
Define service
Define Path and parameters
Create the Application class
Deploy
Test Using Browser
29. JAX RS ANNOTATIONS FOR HTTP METHODS
As seen in the examples, the JAX-RS API defines
support for various HTTP methods through
annotations
The annotations supported are
@javax.ws.rs.GET
@javax.ws.rs.PUT
@javax.ws.rs.POST
@javax.ws.rs.HEAD
@javax.ws.rs.DELETE
30. BINDING URIS
The resources need to be addressed in a way that
is accessible over the web
The path to the resource is annotated using
@javax.ws.rs.Path
For a Java class to be eligible to receive any HTTP
requests, the class must be annotated with at least
the @Path("/") expression
The value of the @Path annotation is an expression
that denotes a relative URI to the context root of
your JAX-RS application
31. BINDING OPERATIONS
@Path can also be applied to the java operations
The URI matching pattern is a concatenation of the
class’s @Path expression and that of the method’s
The URI pattern for getUnpaidOrders() would be
the relative URI /orders/unpaid
32. @PATH EXPRESSIONS
@Path annotations support complex expressions
/customers/200 will match the path for method
getCustomer. While /customers/foo-bar will match
following
33. REGULAR EXPRESSIONS
The .+ is a regular expression that will match any
stream of characters after /customers
The getAddress() method has a more specific
expression. Will map any characters
after/customers that ends with /address. The GET
/customers/foo/bar/address request would route to
the getAddress() method
34. SUBRESOURCE LOCATORS
JAX-RS also allows you to dynamically dispatch requests
yourself through subresource locators
Subresource locators are Java methods annotated
with @Path, without HTTP method annotation
This returns a JAX-RS annotated service which dispatches
the remaining request
Dispatches URI pattern /customers/{database}-
db/{customerId}
36. ACQUIRING DATA
Every service requires a way to acquire data being
sent by the client and respond appropriately
As seen earlier, the Jax RS services are normal
classes with operations being implemented using
the methods
There is a need to ensure that data passed by the
client is receive by the appropriate methods
Jax RS provides various annotations that bind to
input data and makes it available to methods
37. @PATHPARAM
@PathParam allows you to inject the value of named
URI path parameters that were defined
in @Path expressions
38. MATRIX PARAMS
There are times when you would want to pass an
input attribute via the path of the URI instead of
using the query params.
Such params passed via the pat are called Matrix
Params
Example. GET /cars/mercedes/e55;color=black/2006
In the example, the attribute color is passed as a
matrix parameter
40. USING @MATRIXPARAM
JAX-RS specification allows you to inject matrix
parameter values directly through
the @javax.ws.rs.MatrixParam annotation
41. USING THE QUERY STRING - @QUERYPARAM
Generally attributes to a web resources are passed
using the Query String of the HTTP protocol
The @javax.ws.rs.QueryParam annotation allows
you to inject individual URI query parameters into
your Java parameter
GET /customers?start=0&size=10
42. INJECTING VIA FORM ELEMENT -
@FORMPARAM
The @javax.ws.rs.FormParam annotation is used
to access application/x-www-form-url encoded
request bodies
43. @HEADERPARAM
The @javax.ws.rs.HeaderParam annotation is used
to inject HTTP request header values.
You could access the HTTP Referer header using
the @HeaderParam annotation
44. RAW HEADERS
In case you need access to all the headers passed
in by the request, then it can be accessed via
HttpHeaders object set via @Context
45. @COOKIEPARAMS
HTTP is stateless, but many applications might
require a state to be maintained
Maintaining states is accomplished via tools like
Sessions
Cookies
If a client app stores info in a cookie then it is also
responsible to send the data via request headers
@CookieParams annotation allows service to
access data
46. AUTOMATIC TYPE CONVERSION
Although, data sent via HTTP is usually represented as
String, the java method can receive the data in specific
type
JAX-RS converts String into desired type as long as the
type conversion matches following criteria
1. The desired type is a primitive value
2. The desired type is a Java class with a constructor that
takes a single String as input
3. The desired type is a java class that has a static method
named valueOf() that takes a single String argument and
returns an instance of the class
4. It is a java.util.List<T>, java.util.Set<T>,
or java.util.SortedSet<T>, where T is a type that satisfies
criteria 2 or 3
47. COLLECTION OF PARAMETERS
The client can pass a parameter multiple times, in
case there are multiple values to the parameter
GET /customers?orderBy=last&orderBy=first
JAX-RS provider represents these two parameters
as a java.util.List and injects this list
with one @QueryParam annotation
48. DEFAULT VALUE
Many times the client may not have value for a
specific param and may not pass it
This makes the value null. The null value may
cause problems to the service
A default value can be set in such cases
49. ENCODED VALUES
By default, JAX-RS decodes the input values
before converting them into Java types
If you wish to make use of the raw encoded values,
then it is possible via @Encoded annotation
51. WRITING RESTFUL CLIENTS
One of the major challenges in working with a
REST application is writing a client app
Most of the annotations defined earlier are for
creating a RESTful service
For writing clients, there are two options
Develop client app using java.net.URL or Apache HTTP
Client
Use JAX-RS API Client API, which makes working with
Jax RS much simpler
52. USING JERSEY FOR DEVELOPING CLIENT
The Jersey based implementation can be used for
writing JAX-RS 2 clients
Add the following dependency in pom.xml to make
use of the library
<dependencies>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.23.2</version>
</dependency>
</dependencies>
53. CREATING A CLIENT
API provides a class called javax.ws.rs.client.Client
which represents a JAX-RS client
Create a new Client object using ClientBuilder
Client client = ClientBuilder.newClient();
Create the invocation target
WebTarget target =
client.target("http://localhost:8080/SecondApp/services/c
ustomers/eg;color=black/2000");
Send a GET request
Response response = target.request().get();
Analyze the response
response.readEntity(String.class)
Close the resources
response.close()
client.close()
54. WEBTARGET
The WebTarget interface represents a specific URI
you want to invoke on.
Some of the important methods it provides are
55. WEBTARGET
Request invoker can be obtained from the
Webtarget via its request methods
Invocation.Builder allows setting up of different
types of headers
57. NEED FOR CONTENT TRANSFORMATION
Aim of a Java developer is to deal with Java object
as much as possible
RESTful services often represent data in the form
of XML or JSON
There is a need to seamlessly convert from the raw
XML or JSON format to Java object format so that
the developers can handle it easily
58. BUILT-IN CONTENT MARSHALLING
StreamingOutput is a simple callback interface
that you implement when you want to do raw
streaming of response bodies
59. READING DATA
For reading request message bodies, you can use
a raw InputStream or Reader for inputting any
media type
60. RECEIVING OR RETURNING FILES
Instances of java.io.File can also be used for input
and output of any media type.
61. JAXB
JAXB is a specification defined to map Java
classes to XML
JAX-RS has built in support for JAXB
62. JAXB JAX-RS HANDLERS
JAX-RS spec is required to marshall and un-
marshall JAXB objects
63. CUSTOM MARSHALLING
In case where there is no direct support for
marshalling and unmarshalling of JAXB objects,
JAX-RS supports creating custom marshallers
The interface to be implemented are
MessageBodyWriter
MessageBodyReader
65. PASSING OBJECTS FROM CLIENT
JAX-RS client implementation environment may not
have in-built support for JAXB transformation
In such cases it is required that the
MessageBodyReader and MessageBodyWriter is
implemented
To make the class usable, it needs to be registered
with the WebTarget
WebTarget target =
client.target("http://localhost:8080/SecondApp/services/
customers").register(CustomerReader.class).register
(CustomerWriter.class)
67. SUCCESSFUL RESPONSES
Successful HTTP response code numbers range
from 200 to 399
If a service returns null or empty body, then the
response code will be 204, “No Content”
68. ERROR RESPONSE
Standard HTTP error response code numbers
range from 400 to 599
If the client provides a URI that is not found then
the response code will be 404, “Not Found,”
If a client requests text/html response for a
resource URI that is not returning anything then the
status code will be 406, “Not Acceptable,
If the client invokes an HTTP method on a valid URI
to which no JAX-RS resource method is bound, the
JAX-RS runtime will send an error code of 405,
“Method Not Allowed.”
Example, issuing PUT request to a resource that
supports only POST
69. COMPLEX RESPONSE
For the cases where you need to control the
response, your JAX-RS resource methods can
return instances of javax.ws.rs.core.Response
A ResponseBuilder can be used to construct a
Response
70. EXCEPTION HANDLING
Errors can be reported to a client either by creating
and returning the appropriate Response object or
by throwing an exception
JAX-RS provides
the javax.ws.rs.WebApplicationException. This can
be thrown by application code and automatically
processed by JAX-RS
A Response object can be set in the exception
object which will be returned by JAX-RS service to
the client
If there is no Response object set then the server
returns 500, “Internal Server Error,”
72. SECURING APPLICATIONS
Authentication
Authentication is about validating the identity of a client
that is trying to access your services.
Authorization
Authorization is about deciding whether or not a certain
user is allowed to access and invoke on a specific URI
Encryption
Sensitive data should be protected with cryptographic
services like SSL
73. BASIC AUTHENTICATION
Basic Authentication is the simplest protocol available
for performing authentication over HTTP
It involves sending a Base 64–encoded username and
password within a request header to the server
If invoking a secure resource
GET /customers/333 HTTP/1.1
Pass Base 64 encoded username and password in
header username:password
This has to be passed in every request
Prone to hostile interception
74. AUTHORIZATION
While authentication is about establishing and
verifying user identity, authorization is about
permissions.
Authorization requires users to have one or more
roles
Roles need to be assigned permissions to perform
operations
75. AUTHORIZATION USING JAX-RS
Authentication and Authorization in JAX-RS can be
enabled either using web.xml or via Annotations
JAX-RS defines following annotations
@RolesAllowed – Lists the roles that are allowed
access
@DenyAll – Denies access to all roles
@PermitAll – Allows all roles
76. ENABLING AUTHORIZATION
For the server to check for authorization, you need
to register certain interceptors
The interceptors are specific to the implementation
Jboss Resteasy expects you to register a
@Provider that is a PreProcessInterceptor
The Pre-Processor should be registered with the
Application
78. THE WEB PARADIGM
The Internet is commonly referred to as “the Web”
because information is connected together through
a series of hyperlinks embedded within HTML
documents
The architectural principle that describes linking
and form submission is called HATEOAS
HATEOAS stands for Hypermedia As The Engine
Of Application State
79. IMPLEMENTING HATEOAS
Most XML-based RESTful applications use syntax
from the Atom Syndication Format as a means to
implement HATEOAS
80. ATOM LINKS
Atom links have some key attributes
rel
It is the logical, simple name used to reference the link
href
This is the URL you can traverse in order to get new
information or change the state of your application.
type
This is the exchanged media type of the resource the
URL points to
hreflang
Represents the language the data format is translated
into.
81. HATEOAS AND JAX-RS
HATEOAS is to be defined by the application, so
JAX-RS restricts itself to some helper methods to
construct the links
82. BUILD FROM PATH
Given a path, the builder can help create a URI
This would result in a URI
http://example.com/customers/333?param=value
85. CACHING
Caching is one of the most powerful technique to
improve performance
Any service that provides static unchanging data is
an obvious candidate for caching
Browser knows when to cache using the response
header called Expires
88. CONCURRENCY
In a highly concurrent RESTful application, care
should be taken that the a resource is not getting
updated with invalid data
This can happen if a client has obtained a resource
with a particular state and before making the
update, some other client updates the data
This problem can be overcome using conditional
PUT or POST
89. CONDITIONAL UPDATE
A client receives a GET response with its Etag and
Last-Modified headers set
When performing conditional PUT or POST, the
request should have If-Match or If-Unmodified-
Since header
90. CONDITIONAL UPDATE WITH JAX-RS
To do conditional updates with JAX-RS, you use
the Request.evaluatePreconditions() method
92. CONNEG
Clients set an Accept request header that is a
comma-delimited list of preferred formats.
The client is asking the server for /stuff formatted in
either XML or JSON. It can also specify wildcards
If the server is unable to provide the desired
format, it will respond with a status code of 406,
“Not Acceptable.”
93. JAX-RS AND CONNEG
JAX-RS does method dispatching based on the
ACCEPT header values
JAX-RS can pick one of these methods based on
what is in the Accept header
94. JAXB FOR CONNEG
You can implement one Java method that can
service both formats
The method would return representation as per the
ACCEPT header
96. EJB
Java EE requires that EJB containers support
integration with JAX-RS
When manually registering your resources via
your Application class, you must register the bean
class of the EJB via
the Application.getClasses() method.
97. EXAMPLE
Create an app with following features
Create a Product (Only allowed for Admin)
Place an Order.
Order Can include multiple Products
View Pending Order (Only allowed for Admin)
List All Customers
Also return the list of orders as HATEOAS