SlideShare una empresa de Scribd logo
1 de 97
JAX RS
Developing RESTful Applications
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
REFERENCES
 RESTful Java with JAX-RS 2.0, 2nd Edition
 https://www.safaribooksonline.com/library/view/restful-
java-with/9781449361433/
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)
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.
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
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
HTTP
http://www.cs.brandeis.edu/~rshaull/cs146a/project2/proxy-diagram.png
HTTP - METHODS
http://www.bogotobogo.com/python/images/python_http_web_services/HttpRequest.png
Browsers are one of the most well known users of HTTP protocol. But
they generally restrict themselves to GET and POST methods
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
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.
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>
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
STEPS TO DEVELOPING RESTFUL APPS
Define object
model
Model the URIs
Define
representation
format
Assign HTTP
methods
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.
OBJECT MODEL
 Based on the system description the object model
could be
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
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}
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
XML BASED REPRESENTATION
Read or update operation
XML BASED REPRESENTATION
Create Operation
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
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
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
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
DEVELOP A SAMPLE RESTFUL APPLICATION
FIRST APPLICATION
 Create the model class
 Define service
 Define Path and parameters
 Create the Application class
 Deploy
 Test Using Browser
HTTP METHODS AND URI MATCHING
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
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
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
@PATH EXPRESSIONS
 @Path annotations support complex expressions
 /customers/200 will match the path for method
getCustomer. While /customers/foo-bar will match
following
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
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}
JAX-RS INJECTION
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
@PATHPARAM
 @PathParam allows you to inject the value of named
URI path parameters that were defined
in @Path expressions
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
MATRIX PARAM USING @PATH AND
PATHSEGMENT
USING @MATRIXPARAM
 JAX-RS specification allows you to inject matrix
parameter values directly through
the @javax.ws.rs.MatrixParam annotation
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
INJECTING VIA FORM ELEMENT -
@FORMPARAM
 The @javax.ws.rs.FormParam annotation is used
to access application/x-www-form-url encoded
request bodies
@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
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
@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
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
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
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
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
JAX-RS CLIENT API
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
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>
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()
WEBTARGET
 The WebTarget interface represents a specific URI
you want to invoke on.
 Some of the important methods it provides are
WEBTARGET
 Request invoker can be obtained from the
Webtarget via its request methods
 Invocation.Builder allows setting up of different
types of headers
JAX-RS CONTENT HANDLING
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
BUILT-IN CONTENT MARSHALLING
 StreamingOutput is a simple callback interface
that you implement when you want to do raw
streaming of response bodies
READING DATA
 For reading request message bodies, you can use
a raw InputStream or Reader for inputting any
media type
RECEIVING OR RETURNING FILES
 Instances of java.io.File can also be used for input
and output of any media type.
JAXB
 JAXB is a specification defined to map Java
classes to XML
 JAX-RS has built in support for JAXB
JAXB JAX-RS HANDLERS
 JAX-RS spec is required to marshall and un-
marshall JAXB objects
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
IMPLEMENTING A MESSAGEBODYREADER
 An implementation needs to be annotated with
@Provider and @Consumes
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)
SERVER RESPONSES AND EXCEPTIONS
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”
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
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
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,”
SECURING YOUR SERVICES
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
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
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
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
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
HATEOAS
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
IMPLEMENTING HATEOAS
 Most XML-based RESTful applications use syntax
from the Atom Syndication Format as a means to
implement HATEOAS
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.
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
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
BUILD FROM RESOURCE
 Given a REST resource, you can build a URI
SCALING JAX-RS APPLICATIONS
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
JAX-RS AND CACHING
 JAX-RS services can specify expires header using
Response
CACHECONTROL
 JAX-RS also provides a CacheControl class to
control the cache settings
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
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
CONDITIONAL UPDATE WITH JAX-RS
 To do conditional updates with JAX-RS, you use
the Request.evaluatePreconditions() method
CONTENT NEGOTIATION
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.”
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
JAXB FOR CONNEG
 You can implement one Java method that can
service both formats
 The method would return representation as per the
ACCEPT header
INTEGRATIONS
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.
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

Más contenido relacionado

La actualidad más candente

Representational State Transfer
Representational State TransferRepresentational State Transfer
Representational State TransferAlexei Skachykhin
 
SAP ODATA Overview & Guidelines
SAP ODATA Overview & GuidelinesSAP ODATA Overview & Guidelines
SAP ODATA Overview & GuidelinesAshish Saxena
 
The Rest Architectural Style
The Rest Architectural StyleThe Rest Architectural Style
The Rest Architectural StyleRobert Wilson
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and ODataAnil Allewar
 
A Conversation About REST - Extended Version
A Conversation About REST - Extended VersionA Conversation About REST - Extended Version
A Conversation About REST - Extended VersionJeremy Brown
 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / conceptsPatrick Savalle
 
Simplifying RESTful Search- Impetus Webinar
Simplifying RESTful Search- Impetus WebinarSimplifying RESTful Search- Impetus Webinar
Simplifying RESTful Search- Impetus WebinarImpetus Technologies
 
Restful web-services
Restful web-servicesRestful web-services
Restful web-servicesrporwal
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUDPrem Sanil
 
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India
 
Odata V4 : The New way to REST for Your Applications
Odata V4 : The New way to REST for Your Applications Odata V4 : The New way to REST for Your Applications
Odata V4 : The New way to REST for Your Applications Alok Chhabria
 
Representational State Transfer (REST)
Representational State Transfer (REST)Representational State Transfer (REST)
Representational State Transfer (REST)Abhay Ananda Shukla
 

La actualidad más candente (20)

Standards of rest api
Standards of rest apiStandards of rest api
Standards of rest api
 
Representational State Transfer
Representational State TransferRepresentational State Transfer
Representational State Transfer
 
SAP ODATA Overview & Guidelines
SAP ODATA Overview & GuidelinesSAP ODATA Overview & Guidelines
SAP ODATA Overview & Guidelines
 
The Rest Architectural Style
The Rest Architectural StyleThe Rest Architectural Style
The Rest Architectural Style
 
Introduction to Hydra
Introduction to HydraIntroduction to Hydra
Introduction to Hydra
 
JAX-RS 2.0 and OData
JAX-RS 2.0 and ODataJAX-RS 2.0 and OData
JAX-RS 2.0 and OData
 
Hypermedia APIs
Hypermedia APIsHypermedia APIs
Hypermedia APIs
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
 
A Conversation About REST - Extended Version
A Conversation About REST - Extended VersionA Conversation About REST - Extended Version
A Conversation About REST - Extended Version
 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / concepts
 
JSON and REST
JSON and RESTJSON and REST
JSON and REST
 
Simplifying RESTful Search- Impetus Webinar
Simplifying RESTful Search- Impetus WebinarSimplifying RESTful Search- Impetus Webinar
Simplifying RESTful Search- Impetus Webinar
 
REST API
REST APIREST API
REST API
 
Restful web-services
Restful web-servicesRestful web-services
Restful web-services
 
A Look at OData
A Look at ODataA Look at OData
A Look at OData
 
The Glory of Rest
The Glory of RestThe Glory of Rest
The Glory of Rest
 
REST API and CRUD
REST API and CRUDREST API and CRUD
REST API and CRUD
 
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jerseyEclipse Day India 2015 - Rest with Java (jax rs) and jersey
Eclipse Day India 2015 - Rest with Java (jax rs) and jersey
 
Odata V4 : The New way to REST for Your Applications
Odata V4 : The New way to REST for Your Applications Odata V4 : The New way to REST for Your Applications
Odata V4 : The New way to REST for Your Applications
 
Representational State Transfer (REST)
Representational State Transfer (REST)Representational State Transfer (REST)
Representational State Transfer (REST)
 

Similar a JAX-RS. Developing RESTful APIs with Java

Network Device Database Management with REST using Jersey
Network Device Database Management with REST using JerseyNetwork Device Database Management with REST using Jersey
Network Device Database Management with REST using JerseyPayal Jain
 
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptxTransform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptxkmani5
 
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).ppt
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).pptTransform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).ppt
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).pptHusseinWassof
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!Evan Mullins
 
Rest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookKaty Slemon
 
Fundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersFundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersLemi Orhan Ergin
 
What are restful web services?
What are restful web services?What are restful web services?
What are restful web services?Aparna Sharma
 
Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Charlin Agramonte
 
Best practices and advantages of REST APIs
Best practices and advantages of REST APIsBest practices and advantages of REST APIs
Best practices and advantages of REST APIsAparna Sharma
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About RESTJeremy Brown
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About RESTMike Wilcox
 
REST Architecture with use case and example
REST Architecture with use case and exampleREST Architecture with use case and example
REST Architecture with use case and exampleShailesh singh
 

Similar a JAX-RS. Developing RESTful APIs with Java (20)

Switch to Backend 2023
Switch to Backend 2023Switch to Backend 2023
Switch to Backend 2023
 
Network Device Database Management with REST using Jersey
Network Device Database Management with REST using JerseyNetwork Device Database Management with REST using Jersey
Network Device Database Management with REST using Jersey
 
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptxTransform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx
 
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).ppt
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).pptTransform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).ppt
Transform-to-Smart-ERP-using-Custom-Mobile-Apps.pptx (3).ppt
 
Salesforce REST API
Salesforce  REST API Salesforce  REST API
Salesforce REST API
 
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
WordCamp Raleigh 2016 - WP API, What is it good for? Absolutely Everything!
 
Rest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbookRest api best practices – comprehensive handbook
Rest api best practices – comprehensive handbook
 
Fundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-DevelopersFundamentals of Web Development For Non-Developers
Fundamentals of Web Development For Non-Developers
 
REST full API Design
REST full API DesignREST full API Design
REST full API Design
 
What are restful web services?
What are restful web services?What are restful web services?
What are restful web services?
 
Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1Switch to Backend 2023 | Day 1 Part 1
Switch to Backend 2023 | Day 1 Part 1
 
Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5Xamarin Workshop Noob to Master – Week 5
Xamarin Workshop Noob to Master – Week 5
 
SFDC REST API
SFDC REST APISFDC REST API
SFDC REST API
 
Best practices and advantages of REST APIs
Best practices and advantages of REST APIsBest practices and advantages of REST APIs
Best practices and advantages of REST APIs
 
Apitesting.pptx
Apitesting.pptxApitesting.pptx
Apitesting.pptx
 
API Testing Basics.pptx
API Testing Basics.pptxAPI Testing Basics.pptx
API Testing Basics.pptx
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About REST
 
A Conversation About REST
A Conversation About RESTA Conversation About REST
A Conversation About REST
 
Restful api
Restful apiRestful api
Restful api
 
REST Architecture with use case and example
REST Architecture with use case and exampleREST Architecture with use case and example
REST Architecture with use case and example
 

Último

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Último (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

JAX-RS. Developing RESTful APIs with Java

  • 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
  • 3. REFERENCES  RESTful Java with JAX-RS 2.0, 2nd Edition  https://www.safaribooksonline.com/library/view/restful- java-with/9781449361433/
  • 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
  • 9. HTTP - METHODS http://www.bogotobogo.com/python/images/python_http_web_services/HttpRequest.png Browsers are one of the most well known users of HTTP protocol. But they generally restrict themselves to GET and POST methods
  • 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.
  • 16. OBJECT MODEL  Based on the system description the object model could be
  • 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
  • 20. XML BASED REPRESENTATION Read or update operation
  • 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
  • 26. DEVELOP A SAMPLE RESTFUL APPLICATION
  • 27. FIRST APPLICATION  Create the model class  Define service  Define Path and parameters  Create the Application class  Deploy  Test Using Browser
  • 28. HTTP METHODS AND URI MATCHING
  • 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
  • 39. MATRIX PARAM USING @PATH AND PATHSEGMENT
  • 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
  • 64. IMPLEMENTING A MESSAGEBODYREADER  An implementation needs to be annotated with @Provider and @Consumes
  • 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)
  • 66. SERVER RESPONSES AND EXCEPTIONS
  • 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
  • 83. BUILD FROM RESOURCE  Given a REST resource, you can build a URI
  • 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
  • 86. JAX-RS AND CACHING  JAX-RS services can specify expires header using Response
  • 87. CACHECONTROL  JAX-RS also provides a CacheControl class to control the cache settings
  • 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