RESTful Services
Presented By
SHAKIL AKHTAR
About Me..
v Open Source Technologies Enthusiastic
v TOGAF 9 Certified
v TOGAF 9 Foundation Certified
v Introduction to Enterprise Architecture Certified
v Oracle Certifier Master Java Enterprise Architect (SCEA
5)-All Levels.
v SCJDWS certified.
v SCWCD certified
v SCJP certified
v Spring Source Groovy Grails Training Certified.
v Gemfire Cloud Training Certified
v Independent Architecture &Technology Consultant
© Shakil Akhtar
RESTful Services
© Shakil Akhtar
Agenda
v  Introduction to REST
v  Designing RESTful Services
v  First JAX-RS Service
v  HTTP Method and URI Matching
v  JAX-RS Injection
v  Scaling JAX-RS
v  Securing JAX-RS
v  RESTful Java Clients
v  Developing REST Web Services
v  REST Best Practices
v  Common Objections to REST
© Shakil Akhtar
What’s the point?
Integration Architecture
© Shakil Akhtar
Where have We Been ?
RPC CORBA POX
Big Web
Services
REST
© Shakil Akhtar
Introduction To REST
§ What is REST
§ RESTful Architectural Principles
© Shakil Akhtar
Architecture of the web
© Shakil Akhtar
REST
v  REST stands for REpresentational State Transfer.
v  REST is not a toolkit it’s an architectural style
v  Lightweight alternative to mechanisms like RPC,CORBA
and Big Web Services.
v  REST uses HTTP for CRUD operations.
© Shakil Akhtar
Thinking in Resources
v  Resource= the entity, item or things exposed by the system
to outside world.
v  Each resources must be uniquely identifiable
v  Resources are the heart of REST.
v  Resources are just concept
v  URI tells that there’s a concept somewhere
v  Client can then request a specific representation of the
concept from the representations the server makes available
© Shakil Akhtar
© Shakil Akhtar
Resources
Resources
v Things
§  Order
§  Product
v Associations
§  Enrollment
§  Membership
v Processes
§  Onboarding
§  Mentoring
v Functions
§  Driving Directions
§  Search
© Shakil Akhtar
resource
representation
representation
representation
representation
http://cafecoffee.com/order/1234
http://cafecoffee.com/order/1234.json
urn:cafecoffee.com:order:1234
ftp://cafecoffee.com/order/1234.txt
service boundary
© Shakil Akhtar
RESTful Architectural Principle
v Addressability.
v Uniform Constrained Interface
v Representation Oriented
v Communicate Statelessly.
v HATEOAS(Connectedness)
© Shakil Akhtar
Addressability
v  Addressability is the idea that every object and resource in
your system is reachable through a unique identifier.
v  In the REST world, addressability is managed through the use
of URIs.
v  URI format is of type scheme://host:port/path?
queryString#fragment
© Shakil Akhtar
Addressability
© Shakil Akhtar
Uniform Constrained Interface
v  Interaction between client and resources uses HTTP
methods.
v  HTTP methods include GET,POST,PUT and DELETE.
© Shakil Akhtar
Uniform Constrained Interface
GET Request
Customer CafeCoffee
http://cafecoffee.com/order/1234GET /order/1234
404 Not Found
500 Internal Error
200 OK
<order…/>
get error
© Shakil Akhtar
Uniform Constrained Interface
POST Request
Customer CafeCoffee
http://cafecoffee.com/order
POST /order
<order …/>
400 Bad Request
500 Internal Error
201 Created
Location http://
coffee.com/order/1234
create error
http://cafecoffee.com/order/1234
© Shakil Akhtar
Uniform Constrained Interface
PUT Request
Customer CafeCoffee
http://cafecoffee.com/order/1234
PUT /order/1234
<order …/>
404 Not Found
500 Internal Error
200 OK
or
204 No Content
put error
409 Conflict
© Shakil Akhtar
Uniform Constrained Interface
DELETE Request
Customer CafeCoffee
http://cafecoffee.com/order/1234
DELETE /order/1234
404 Not Found
503 Service Unavailable
204  No Content
delete error
405 Method Not Allowed
© Shakil Akhtar
getOrderDetails()
findMatchingBid()
listAuctions()
getUsers()
initiateProcess()
submitApplcationData()
updateQuote() cancelSubscription()
© Shakil Akhtar
Mapping Example
getFreeTimeSlots (Person) →GET /people/{id}/timeslots?state=free
rejectApplication (Application)
→POST /rejections↵
<application>http://...</application>↵
<reason>Unsuitable for us!</reason>
performTariffCalculation(Data)
→POST /contracts↵
Data
←Location: http://.../contracts/4711
→GET /contracts/4711/tariff
←Result
shipOrder (ID) →PUT /orders/0815/status↵
<status>shipped</status>
shipOrder(ID) [variation] →POST /shipments↵
Data
←Location: http://.../shipments/4711
© Shakil Akhtar
Why Uniform Interface Important?
v  Familiarity.
v  Interoperability.
v  Scalability
© Shakil Akhtar
Representation Oriented
v  Services should be representation oriented.
v  Each service is having URI and representations are exchanged
between client and server.
v  Representation could be XML,JSON,YAML or any format you
can come up.
v  Representation is the message body of request and response
v Support Content Negotiation
§  Accept Header
§  GET /customer
§  Accept : application/json
§  URI based
§  GET /customer.json
© Shakil Akhtar
Menu
Latte: $5
Espresso: $4
Cookie: $1
<xhtml>
<body>
<p><b>Menu</b></p>
<ul>
<li>Latte:$5</li>
<li>Espresso:$4</li>
<li>Cookie:$1</li>
</ul>
</body>
</xhtml>
Menu
Latte:$5
Espresso:$4
Cookie:$1
http://caffecoffee.com/menu
X
H
T
M
L
T
e
x
t
© Shakil Akhtar
Communicate Statelessly
v  No client session data storage on server.
v  Server should records and manage resources state it exposes.
v  Application state should maintained by client.
v  Everything required to process a request contained in the
request
v  The resource forgets about you while you are not directly
interacting with it.
© Shakil Akhtar
HATEOAS: connectedness
v  Stands for Hypermedia As The Engine Of Application State
v  Server can guide client from one application state to another
by sending links and forms in its representations
v  Connectedness of resources
v  Resource representations can contain other URIs
v  Links acts as state transitions
© Shakil Akhtar
HATEOAS…
© Shakil Akhtar
Links
v Response contains links
v Define link for resource self description
<order self="http://example.com/orders/101230">
<customer ref="http://example.com/customers/bar">
<product ref="http://example.com/products/21034"/>
<amount value="1"/>
</order>
© Shakil Akhtar
Link state transition Use Case
v  Possible state transitions for a coffee order
© Shakil Akhtar
Designing REST web services
© Shakil Akhtar
v The Object Model
v Model the URIs
v Defining the data format
v Assigning HTTP Methods
First REST Service
v Developing a JAX-RS RESTful service
v Deploying our service
© Shakil Akhtar
JAX-RS Injection
v  The Basics
v  @PathParam
v  @MatrixParam
v  @QuesryParam
v  @FormParam
v  @HeaderParam
v  @CookieParam
v  Common Functionality
© Shakil Akhtar
@PathParam
// At class level
// At method level
@Path("/customers")
public class CustomerResource {
}
@GET
@Path("{id}")
@Produces("application/xml")
public StreamingOutput getCustomer(@PathParam("id") int id) {
}
© Shakil Akhtar
Request Mapping
Application
Resource
@GET
Public
Resource
getCustomer
URI
Matching
Method
Matching
Content
Type
Matching
GET /customer/ HTTP 1.1
Accept: application/xml
HTTP/1.1 200 OK
Content-Type: application/xml
© Shakil Akhtar
Scope of Path Parameters
HTTP Request -> /customers/123/address/456
The addressId parameter in the getAddress() method would
Have the 456 value injected
@Path("/customers/{id}")
public class CustomerResource {
@Path("/address/{id}")
@Produces("text/plain")
@GET
public String getAddress(@PathParam("id") String addressId){
}
}
© Shakil Akhtar
@MatrixParam
GET /mercedes/e55;color=black/2006/interior;color=tan
http://www.w3.org/DesignIssues/MatrixURIs.html
@Path(“/{make}")
public class CarResource {
@GET
@Path(“/{model}/{year}")
@Produces(“image/jpeg")
public Jpeg getPicture(@PathParam(“make") String make, @PathParam(“model")
String model, @MatrixParam(“color") String color) {
}
}
© Shakil Akhtar
@QueryParam
GET /customers?start=0&limit=10
@Path("/customers")
public class CustomerResource {
@Produces(“application/xml")
@GET
public String getCustomers(@QueryParam(“start") int start
, @QueryParam(“limit") int limit){
}
}
© Shakil Akhtar
Programatic Query Parameter
GET /customers?start=0&limit=10
@GET
@Produces("application/xml")
public String getCustomers(@Context UriInfo info) {
String start = info.getQueryParameters().getFirst("start");
String size = info.getQueryParameters().getFirst("limit");
}
© Shakil Akhtar
@FormParam
<FORM action="http://mycomp.com/customers" method="post">
<P>
First name: <INPUT type="text" name="firstname"><BR>
Last name: <INPUT type="text" name="lastname"><BR>
<INPUT type="submit" value="Send">
</P>
</FORM>
@Path("/customers")
public class CustomerResource {
@POST
public void createCustomer(@FormParam("firstname") String fname,
@FormParam("lastname") String lname) {
}
}
© Shakil Akhtar
@HeaderParam
Raw Header can be accessed as follows-
@Path("/customerService")
public class CustomerService {
@Produces (“text/html")
public String get(@HeaderParam(“Referer") String referer) {
}
}
@GET
@Produces("text/html")
public String get(@Context HttpHeaders headers) {
String referer = headers.getRequestHeader("Referer").get(0);
for (String header : headers.getRequestHeaders().keySet())
{
System.out.println("This header was set: " + header);
}
} © Shakil Akhtar
@CookieParam
Raw Header can be accessed as follows-
@Path("/customerService")
public class CustomerService {
@GET
@Produces (“text/html")
public String get(@CookieParam(“customerId") int custId) {
}
}
© Shakil Akhtar
JAX-RS Content Handler
§  Built-in Content Marshaling
§  JAXB
§  Custom Marshaling
© Shakil Akhtar
Streaming Output
§  Built-in Content Marshaling
@Path("/customerservice")
public class CustomerService {
@GET
@Produces("text/plain")
StreamingOutput get() {
return new StreamingOutput() {
public void write(OutputStream output) throws IOException,
WebApplicationException {output.write(“Welcome!".getBytes());
}
};
}
© Shakil Akhtar
JAXB
§  An annotation framework that maps java classes to XML and
XML Schemas
§  Built-in support by JAX-RS
@XmlRootElement(name="customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Customer {
@XmlAttribute
private int id;
@XmlElement
private String fullName;
@XmlElement
private Address address;
//getter setter
}
© Shakil Akhtar
Scaling JAX-RS
v  Caching
v  Concurrency
© Shakil Akhtar
Caching
v  Expires Headers
GET /customer/123
HTTP/1.1 200 OK
Content-Type: application/xml
Expires:Tue, 15 May 2010 16:00 GMT
<customer id="123">...</customers>
© Shakil Akhtar
Caching
v  Cache-Controls
§  Expires Header deprecated in HTTP 1.1
§  Cache-controls added in HTTP 1.1
§  Comma delimited set of directives
ü  private
ü  public
ü  no-cache
ü  no-store
ü  no-transform
ü  max-age
© Shakil Akhtar
Revalidation and Conditional GETs
v  Last-Modified
•  Represent timestamp of the data sent by the server
•  Do conditional get call using If-Modified-Since
HTTP/1.1 200 OK
Content-Type: application/xml
Cache-Control: max-age=1000
Last-Modified:Tue, 15 May 2009 09:56 EST
<customer id="123">...</customer>
GET /customers/123 HTTP/1.1
If-Modified-Since:Tue, 15 May 2009 09:56 EST
© Shakil Akhtar
cont…
v  ETag
•  A pesudounique identifier header that represents the version of data
sent back
•  Do conditional get call using If-None-Match
HTTP/1.1 200 OK
Content-Type: application/xml
Cache-Control: max-age=1000
ETag:“3141271342554322343200”
<customer id="123">...</customer>
GET /customers/123 HTTP/1.1
If-None-Match:” 3141271342554322343200”
© Shakil Akhtar
Concurrency
v  When many clients try to update a resource
v  Conditional PUT or POST
A conditional PUT request –
PUT /customers/123 HTTP/1.1
If-Match: "3141271342554322343200"
If-Unmodified-Since:Tue, 15 May 2009 09:56 EST
Content-Type: application/xml
<customer id="123">...</customer>
© Shakil Akhtar
Web Security Concepts
v  Confidentiality
§  Keep information private while in transit or storage
v  Integrity
§  Prevent information from being changed undetectably
v  Identity
§  Authenticate parties involved in interaction
v  Trust
§  Authorizing a party to interact with a system in prescribed
manner
© Shakil Akhtar
Securing JAX-RS
v  Authentication
v  Authorization
v  Authentication and Authorization in JAX-RS
© Shakil Akhtar
Authentication
§  Basic
§  Digest
§  Client Certificate
© Shakil Akhtar
Authentication: Configure web.xml
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>admin</realm-name>
</login-config>
© Shakil Akhtar
Authentication: Configure web.xml
§  login-config
•  Defines how the HTTP requests should be authenticated
§  auth-method
•  BASIC, DIGEST, or CLIENT_CERT. corresponds to Basic,
Digest, and Client Certificate authentication, respectively
§  relam-name
•  Name for database of users and groups that identify valid users
of a web application
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>admin</realm-name>
</login-config>
© Shakil Akhtar
Authentication: Configure web.xml
§  security-constraints
•  Defines access privileges to a collection of resource
§  url-pattern
•  URL pattern you want to secure
§  http-method
•  Methods to be protected
<security-constraint>
<web-resource-collection>
<url-pattern>/secure/*</url-pattern>
<http-method>POST</http-method>
</web-resource-collection>
...
© Shakil Akhtar
Authentication: Configure web.xml
§  auth-constraints
•  Names the roles authorized to access the URL patterns and
HTTP methods declared by this security constraint
<security-constraint>
...
<auth-constraint>
<description>only let admin login </description>
<role-name>admin</role-name>
</auth-constraint>
© Shakil Akhtar
Authentication: Configure web.xml
§  User-data-constraints
•  How data will be transported between client and server
•  NONE,INTEGRAL or CONFIDENTIAL
§  url-pattern
•  URL pattern you want to secure
§  http-method
•  Methods to be protected
<security-constraint>
...
<user-data-constraint>
<description>SSL</description>
<transport-guarantee>CONFIDENTIAL</transport-guarantee>
</user-data-constraint>
</security-constraint>
© Shakil Akhtar
Authentication: Configure web.xml
§  security-role
•  lists all of the security roles used in the application
•  For every <role-name> used in <auth-constraints> must
define a corresponding <security-role>
<security-role>
<role-name>admin</role-name>
</security-role>
© Shakil Akhtar
Authentication: Configure web.xml
§  security-role-mapping
•  Assigns security role to a group or user in Application Server
realm
•  For every <role-name> used in <auth-constraints> must
define a corresponding <security-role>
<sun-web-app>
<security-role-mapping>
<role-name>admin</role-name>
<principal-name>admin</principal-name>
</security-role-mapping>
</sun-web-app>
LDAP
realm
© Shakil Akhtar
Authorization
§  Authorization is the domain of the server and application
§  Application permission constrains
§  Role base access for resources
© Shakil Akhtar
RESTful Java Clients
§  java.net.URL
§  Apache HTTPClient
§  RESTEasy Client framework
§  Spring RestTemplate
§  Jersey
© Shakil Akhtar
java.net.URL
§  Two important classes java.net.URL and
java.net.HTTPUrlConnection
§  Supports standard HTTP method calls
§  caching support using setUseCaches(boolean)
§  HTTPUrlConnection supports Basic, Digest and Client
Certificate authentication
© Shakil Akhtar
GET Method call
public class GetCall {
public static void main(String[] args) throws Exception {
URL url = new URL("http://caffecoffee.com/order/1");
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Accept", "application/xml");
if (connection.getResponseCode() != 200) {
throw new RuntimeException("Operation failed: "
+ connection.getResponseCode());
}
System.out.println("Content-Type: " + connection.getContentType());
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
connection.disconnect();
}
}
© Shakil Akhtar
Authentication with Authenticator
public void authenticateUser(final String username, final String password){
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication
getPasswordAuthentication() {
return new
PasswordAuthentication(username,
password.toCharArray());
}
});
}
© Shakil Akhtar
Apache HttpClient
public String callRestService(String uri) throws IOException {
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(uri);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
// Send GET request
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " +method.getStatusLine());
}
byte[] responseBody = method.getResponseBody();
return new String(responseBody);
}
© Shakil Akhtar
HTTP Status Codes- By HTTP Verb
© Shakil Akhtar
HTTP Status Codes- Other
© Shakil Akhtar
REST Platforms
Jersey RESTEasy Restlet
ApacheCXF Rails Grails
Django
© Shakil Akhtar
Jersey
© Shakil Akhtar
RESTEasy
© Shakil Akhtar
Restlet
© Shakil Akhtar
Apache CXF
© Shakil Akhtar
Rails
© Shakil Akhtar
Grails
© Shakil Akhtar
Django
© Shakil Akhtar
REST Best Practices
§  Provide a URI for each resource that you want (or will want)
expose.
§  Prefer URIs that are logical over URIs that are physical. For
example
•  Prefer : http://www.caffecoffee.com/orders/747
•  Over : http://www.caffecoffee.com/orders/747.html
© Shakil Akhtar
REST Best Practices
§  Use nouns in the URI not verbs. Resources are “things” not “actions”
§  Make all HTTP GETs side effect free. Doing so make the request “safe”
§  Use links in your responses to requests! Doing so connects your response
to other data. It enables client applications to be “self-propelled”.
§  Minimize the use of query strings
•  Prefer : http://www.caffecoffee.com/orders/1234
•  Over : http://www.caffecoffee.com/orders?orderid=1234
© Shakil Akhtar
REST Best Practices
§  Use the “/” in a URI to represent a parent child, whole-part
relationship.
§  Use a “gradual unfolding methodology” for exposing data to
clients.This is, a resource representation should provide links
to obtain more details.
§  Always implement a service using HTTP GET when the
purpose of the service is to allow a client to retrieve a
resource representation.
© Shakil Akhtar
Common Objections to REST
Data Services 4
Verbs and
CRUD
No formal
definition
language
Internals
exposed HTTP only
Best Practices?
No
Transactions
Unreliable No pub/sub
No
Asynchronous
Interactions
Lack of tools Security
© Shakil Akhtar
Data Service -4 Verbs+CRUD
§  Misunderstanding of Resources.
§  Associations(Relationships)
§  Processes
§  Functions
© Shakil Akhtar
Internals Exposed
§  URIs are not a one to one match.
§  Separation of concern
© Shakil Akhtar
Best Practices?
§  Many Books published
§  JAX-RS standards
© Shakil Akhtar
Unreliable
§  Remember the HTTP codes
§  Re-send the request
§  Idempotence - GET,PUT,DELETE
© Shakil Akhtar
No Pub/Sub
§  RSS
§  AtomPub
© Shakil Akhtar
No Asynchronous Interaction
§  HTTP Code 202 - Accepted
§  Queue the request / process later
§  POST a response
© Shakil Akhtar
Testing RESTful Services
© Shakil Akhtar
RESTful Testing
§  cURL
§  REST-Client
§  soapUI
§  RESTGate
© Shakil Akhtar
cURL
}  GET
curl -i -H "Accept: application/xml" http://localhost:8080/jaxrs/customerscache/123  
© Shakil Akhtar
REST Client
© Shakil Akhtar
Is REST being used?
© Shakil Akhtar
Summary
v Introduction to REST
v CommonVerbs
v RESTful services Implementation
v Testing RESTful Services
© Shakil Akhtar
© Shakil Akhtar
ThankYou!
© Shakil Akhtar

Restful Services

  • 1.
  • 2.
    About Me.. v Open SourceTechnologies Enthusiastic v TOGAF 9 Certified v TOGAF 9 Foundation Certified v Introduction to Enterprise Architecture Certified v Oracle Certifier Master Java Enterprise Architect (SCEA 5)-All Levels. v SCJDWS certified. v SCWCD certified v SCJP certified v Spring Source Groovy Grails Training Certified. v Gemfire Cloud Training Certified v Independent Architecture &Technology Consultant © Shakil Akhtar
  • 3.
  • 4.
    Agenda v  Introduction toREST v  Designing RESTful Services v  First JAX-RS Service v  HTTP Method and URI Matching v  JAX-RS Injection v  Scaling JAX-RS v  Securing JAX-RS v  RESTful Java Clients v  Developing REST Web Services v  REST Best Practices v  Common Objections to REST © Shakil Akhtar
  • 5.
    What’s the point? IntegrationArchitecture © Shakil Akhtar
  • 6.
    Where have WeBeen ? RPC CORBA POX Big Web Services REST © Shakil Akhtar
  • 7.
    Introduction To REST § Whatis REST § RESTful Architectural Principles © Shakil Akhtar
  • 8.
    Architecture of theweb © Shakil Akhtar
  • 9.
    REST v  REST standsfor REpresentational State Transfer. v  REST is not a toolkit it’s an architectural style v  Lightweight alternative to mechanisms like RPC,CORBA and Big Web Services. v  REST uses HTTP for CRUD operations. © Shakil Akhtar
  • 10.
    Thinking in Resources v Resource= the entity, item or things exposed by the system to outside world. v  Each resources must be uniquely identifiable v  Resources are the heart of REST. v  Resources are just concept v  URI tells that there’s a concept somewhere v  Client can then request a specific representation of the concept from the representations the server makes available © Shakil Akhtar
  • 11.
  • 12.
    Resources v Things §  Order §  Product v Associations § Enrollment §  Membership v Processes §  Onboarding §  Mentoring v Functions §  Driving Directions §  Search © Shakil Akhtar
  • 13.
  • 14.
    RESTful Architectural Principle v Addressability. v UniformConstrained Interface v Representation Oriented v Communicate Statelessly. v HATEOAS(Connectedness) © Shakil Akhtar
  • 15.
    Addressability v  Addressability isthe idea that every object and resource in your system is reachable through a unique identifier. v  In the REST world, addressability is managed through the use of URIs. v  URI format is of type scheme://host:port/path? queryString#fragment © Shakil Akhtar
  • 16.
  • 17.
    Uniform Constrained Interface v Interaction between client and resources uses HTTP methods. v  HTTP methods include GET,POST,PUT and DELETE. © Shakil Akhtar
  • 18.
    Uniform Constrained Interface GETRequest Customer CafeCoffee http://cafecoffee.com/order/1234GET /order/1234 404 Not Found 500 Internal Error 200 OK <order…/> get error © Shakil Akhtar
  • 19.
    Uniform Constrained Interface POSTRequest Customer CafeCoffee http://cafecoffee.com/order POST /order <order …/> 400 Bad Request 500 Internal Error 201 Created Location http:// coffee.com/order/1234 create error http://cafecoffee.com/order/1234 © Shakil Akhtar
  • 20.
    Uniform Constrained Interface PUTRequest Customer CafeCoffee http://cafecoffee.com/order/1234 PUT /order/1234 <order …/> 404 Not Found 500 Internal Error 200 OK or 204 No Content put error 409 Conflict © Shakil Akhtar
  • 21.
    Uniform Constrained Interface DELETERequest Customer CafeCoffee http://cafecoffee.com/order/1234 DELETE /order/1234 404 Not Found 503 Service Unavailable 204  No Content delete error 405 Method Not Allowed © Shakil Akhtar
  • 22.
  • 23.
    Mapping Example getFreeTimeSlots (Person)→GET /people/{id}/timeslots?state=free rejectApplication (Application) →POST /rejections↵ <application>http://...</application>↵ <reason>Unsuitable for us!</reason> performTariffCalculation(Data) →POST /contracts↵ Data ←Location: http://.../contracts/4711 →GET /contracts/4711/tariff ←Result shipOrder (ID) →PUT /orders/0815/status↵ <status>shipped</status> shipOrder(ID) [variation] →POST /shipments↵ Data ←Location: http://.../shipments/4711 © Shakil Akhtar
  • 24.
    Why Uniform InterfaceImportant? v  Familiarity. v  Interoperability. v  Scalability © Shakil Akhtar
  • 25.
    Representation Oriented v  Servicesshould be representation oriented. v  Each service is having URI and representations are exchanged between client and server. v  Representation could be XML,JSON,YAML or any format you can come up. v  Representation is the message body of request and response v Support Content Negotiation §  Accept Header §  GET /customer §  Accept : application/json §  URI based §  GET /customer.json © Shakil Akhtar
  • 26.
    Menu Latte: $5 Espresso: $4 Cookie:$1 <xhtml> <body> <p><b>Menu</b></p> <ul> <li>Latte:$5</li> <li>Espresso:$4</li> <li>Cookie:$1</li> </ul> </body> </xhtml> Menu Latte:$5 Espresso:$4 Cookie:$1 http://caffecoffee.com/menu X H T M L T e x t © Shakil Akhtar
  • 27.
    Communicate Statelessly v  Noclient session data storage on server. v  Server should records and manage resources state it exposes. v  Application state should maintained by client. v  Everything required to process a request contained in the request v  The resource forgets about you while you are not directly interacting with it. © Shakil Akhtar
  • 28.
    HATEOAS: connectedness v  Standsfor Hypermedia As The Engine Of Application State v  Server can guide client from one application state to another by sending links and forms in its representations v  Connectedness of resources v  Resource representations can contain other URIs v  Links acts as state transitions © Shakil Akhtar
  • 29.
  • 30.
    Links v Response contains links v Definelink for resource self description <order self="http://example.com/orders/101230"> <customer ref="http://example.com/customers/bar"> <product ref="http://example.com/products/21034"/> <amount value="1"/> </order> © Shakil Akhtar
  • 31.
    Link state transitionUse Case v  Possible state transitions for a coffee order © Shakil Akhtar
  • 32.
    Designing REST webservices © Shakil Akhtar v The Object Model v Model the URIs v Defining the data format v Assigning HTTP Methods
  • 33.
    First REST Service v Developinga JAX-RS RESTful service v Deploying our service © Shakil Akhtar
  • 34.
    JAX-RS Injection v  TheBasics v  @PathParam v  @MatrixParam v  @QuesryParam v  @FormParam v  @HeaderParam v  @CookieParam v  Common Functionality © Shakil Akhtar
  • 35.
    @PathParam // At classlevel // At method level @Path("/customers") public class CustomerResource { } @GET @Path("{id}") @Produces("application/xml") public StreamingOutput getCustomer(@PathParam("id") int id) { } © Shakil Akhtar
  • 36.
    Request Mapping Application Resource @GET Public Resource getCustomer URI Matching Method Matching Content Type Matching GET /customer/HTTP 1.1 Accept: application/xml HTTP/1.1 200 OK Content-Type: application/xml © Shakil Akhtar
  • 37.
    Scope of PathParameters HTTP Request -> /customers/123/address/456 The addressId parameter in the getAddress() method would Have the 456 value injected @Path("/customers/{id}") public class CustomerResource { @Path("/address/{id}") @Produces("text/plain") @GET public String getAddress(@PathParam("id") String addressId){ } } © Shakil Akhtar
  • 38.
    @MatrixParam GET /mercedes/e55;color=black/2006/interior;color=tan http://www.w3.org/DesignIssues/MatrixURIs.html @Path(“/{make}") public classCarResource { @GET @Path(“/{model}/{year}") @Produces(“image/jpeg") public Jpeg getPicture(@PathParam(“make") String make, @PathParam(“model") String model, @MatrixParam(“color") String color) { } } © Shakil Akhtar
  • 39.
    @QueryParam GET /customers?start=0&limit=10 @Path("/customers") public classCustomerResource { @Produces(“application/xml") @GET public String getCustomers(@QueryParam(“start") int start , @QueryParam(“limit") int limit){ } } © Shakil Akhtar
  • 40.
    Programatic Query Parameter GET/customers?start=0&limit=10 @GET @Produces("application/xml") public String getCustomers(@Context UriInfo info) { String start = info.getQueryParameters().getFirst("start"); String size = info.getQueryParameters().getFirst("limit"); } © Shakil Akhtar
  • 41.
    @FormParam <FORM action="http://mycomp.com/customers" method="post"> <P> Firstname: <INPUT type="text" name="firstname"><BR> Last name: <INPUT type="text" name="lastname"><BR> <INPUT type="submit" value="Send"> </P> </FORM> @Path("/customers") public class CustomerResource { @POST public void createCustomer(@FormParam("firstname") String fname, @FormParam("lastname") String lname) { } } © Shakil Akhtar
  • 42.
    @HeaderParam Raw Header canbe accessed as follows- @Path("/customerService") public class CustomerService { @Produces (“text/html") public String get(@HeaderParam(“Referer") String referer) { } } @GET @Produces("text/html") public String get(@Context HttpHeaders headers) { String referer = headers.getRequestHeader("Referer").get(0); for (String header : headers.getRequestHeaders().keySet()) { System.out.println("This header was set: " + header); } } © Shakil Akhtar
  • 43.
    @CookieParam Raw Header canbe accessed as follows- @Path("/customerService") public class CustomerService { @GET @Produces (“text/html") public String get(@CookieParam(“customerId") int custId) { } } © Shakil Akhtar
  • 44.
    JAX-RS Content Handler § Built-in Content Marshaling §  JAXB §  Custom Marshaling © Shakil Akhtar
  • 45.
    Streaming Output §  Built-inContent Marshaling @Path("/customerservice") public class CustomerService { @GET @Produces("text/plain") StreamingOutput get() { return new StreamingOutput() { public void write(OutputStream output) throws IOException, WebApplicationException {output.write(“Welcome!".getBytes()); } }; } © Shakil Akhtar
  • 46.
    JAXB §  An annotationframework that maps java classes to XML and XML Schemas §  Built-in support by JAX-RS @XmlRootElement(name="customer") @XmlAccessorType(XmlAccessType.FIELD) public class Customer { @XmlAttribute private int id; @XmlElement private String fullName; @XmlElement private Address address; //getter setter } © Shakil Akhtar
  • 47.
    Scaling JAX-RS v  Caching v Concurrency © Shakil Akhtar
  • 48.
    Caching v  Expires Headers GET/customer/123 HTTP/1.1 200 OK Content-Type: application/xml Expires:Tue, 15 May 2010 16:00 GMT <customer id="123">...</customers> © Shakil Akhtar
  • 49.
    Caching v  Cache-Controls §  ExpiresHeader deprecated in HTTP 1.1 §  Cache-controls added in HTTP 1.1 §  Comma delimited set of directives ü  private ü  public ü  no-cache ü  no-store ü  no-transform ü  max-age © Shakil Akhtar
  • 50.
    Revalidation and ConditionalGETs v  Last-Modified •  Represent timestamp of the data sent by the server •  Do conditional get call using If-Modified-Since HTTP/1.1 200 OK Content-Type: application/xml Cache-Control: max-age=1000 Last-Modified:Tue, 15 May 2009 09:56 EST <customer id="123">...</customer> GET /customers/123 HTTP/1.1 If-Modified-Since:Tue, 15 May 2009 09:56 EST © Shakil Akhtar
  • 51.
    cont… v  ETag •  Apesudounique identifier header that represents the version of data sent back •  Do conditional get call using If-None-Match HTTP/1.1 200 OK Content-Type: application/xml Cache-Control: max-age=1000 ETag:“3141271342554322343200” <customer id="123">...</customer> GET /customers/123 HTTP/1.1 If-None-Match:” 3141271342554322343200” © Shakil Akhtar
  • 52.
    Concurrency v  When manyclients try to update a resource v  Conditional PUT or POST A conditional PUT request – PUT /customers/123 HTTP/1.1 If-Match: "3141271342554322343200" If-Unmodified-Since:Tue, 15 May 2009 09:56 EST Content-Type: application/xml <customer id="123">...</customer> © Shakil Akhtar
  • 53.
    Web Security Concepts v Confidentiality §  Keep information private while in transit or storage v  Integrity §  Prevent information from being changed undetectably v  Identity §  Authenticate parties involved in interaction v  Trust §  Authorizing a party to interact with a system in prescribed manner © Shakil Akhtar
  • 54.
    Securing JAX-RS v  Authentication v Authorization v  Authentication and Authorization in JAX-RS © Shakil Akhtar
  • 55.
    Authentication §  Basic §  Digest § Client Certificate © Shakil Akhtar
  • 56.
  • 57.
    Authentication: Configure web.xml § login-config •  Defines how the HTTP requests should be authenticated §  auth-method •  BASIC, DIGEST, or CLIENT_CERT. corresponds to Basic, Digest, and Client Certificate authentication, respectively §  relam-name •  Name for database of users and groups that identify valid users of a web application <login-config> <auth-method>BASIC</auth-method> <realm-name>admin</realm-name> </login-config> © Shakil Akhtar
  • 58.
    Authentication: Configure web.xml § security-constraints •  Defines access privileges to a collection of resource §  url-pattern •  URL pattern you want to secure §  http-method •  Methods to be protected <security-constraint> <web-resource-collection> <url-pattern>/secure/*</url-pattern> <http-method>POST</http-method> </web-resource-collection> ... © Shakil Akhtar
  • 59.
    Authentication: Configure web.xml § auth-constraints •  Names the roles authorized to access the URL patterns and HTTP methods declared by this security constraint <security-constraint> ... <auth-constraint> <description>only let admin login </description> <role-name>admin</role-name> </auth-constraint> © Shakil Akhtar
  • 60.
    Authentication: Configure web.xml § User-data-constraints •  How data will be transported between client and server •  NONE,INTEGRAL or CONFIDENTIAL §  url-pattern •  URL pattern you want to secure §  http-method •  Methods to be protected <security-constraint> ... <user-data-constraint> <description>SSL</description> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> © Shakil Akhtar
  • 61.
    Authentication: Configure web.xml § security-role •  lists all of the security roles used in the application •  For every <role-name> used in <auth-constraints> must define a corresponding <security-role> <security-role> <role-name>admin</role-name> </security-role> © Shakil Akhtar
  • 62.
    Authentication: Configure web.xml § security-role-mapping •  Assigns security role to a group or user in Application Server realm •  For every <role-name> used in <auth-constraints> must define a corresponding <security-role> <sun-web-app> <security-role-mapping> <role-name>admin</role-name> <principal-name>admin</principal-name> </security-role-mapping> </sun-web-app> LDAP realm © Shakil Akhtar
  • 63.
    Authorization §  Authorization isthe domain of the server and application §  Application permission constrains §  Role base access for resources © Shakil Akhtar
  • 64.
    RESTful Java Clients § java.net.URL §  Apache HTTPClient §  RESTEasy Client framework §  Spring RestTemplate §  Jersey © Shakil Akhtar
  • 65.
    java.net.URL §  Two importantclasses java.net.URL and java.net.HTTPUrlConnection §  Supports standard HTTP method calls §  caching support using setUseCaches(boolean) §  HTTPUrlConnection supports Basic, Digest and Client Certificate authentication © Shakil Akhtar
  • 66.
    GET Method call publicclass GetCall { public static void main(String[] args) throws Exception { URL url = new URL("http://caffecoffee.com/order/1"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/xml"); if (connection.getResponseCode() != 200) { throw new RuntimeException("Operation failed: " + connection.getResponseCode()); } System.out.println("Content-Type: " + connection.getContentType()); BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream())); String line = reader.readLine(); while (line != null) { System.out.println(line); line = reader.readLine(); } connection.disconnect(); } } © Shakil Akhtar
  • 67.
    Authentication with Authenticator publicvoid authenticateUser(final String username, final String password){ Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(username, password.toCharArray()); } }); } © Shakil Akhtar
  • 68.
    Apache HttpClient public StringcallRestService(String uri) throws IOException { HttpClient client = new HttpClient(); GetMethod method = new GetMethod(uri); // Provide custom retry handler is necessary method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false)); // Send GET request int statusCode = client.executeMethod(method); if (statusCode != HttpStatus.SC_OK) { System.err.println("Method failed: " +method.getStatusLine()); } byte[] responseBody = method.getResponseBody(); return new String(responseBody); } © Shakil Akhtar
  • 69.
    HTTP Status Codes-By HTTP Verb © Shakil Akhtar
  • 70.
    HTTP Status Codes-Other © Shakil Akhtar
  • 71.
    REST Platforms Jersey RESTEasyRestlet ApacheCXF Rails Grails Django © Shakil Akhtar
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
    REST Best Practices § Provide a URI for each resource that you want (or will want) expose. §  Prefer URIs that are logical over URIs that are physical. For example •  Prefer : http://www.caffecoffee.com/orders/747 •  Over : http://www.caffecoffee.com/orders/747.html © Shakil Akhtar
  • 80.
    REST Best Practices § Use nouns in the URI not verbs. Resources are “things” not “actions” §  Make all HTTP GETs side effect free. Doing so make the request “safe” §  Use links in your responses to requests! Doing so connects your response to other data. It enables client applications to be “self-propelled”. §  Minimize the use of query strings •  Prefer : http://www.caffecoffee.com/orders/1234 •  Over : http://www.caffecoffee.com/orders?orderid=1234 © Shakil Akhtar
  • 81.
    REST Best Practices § Use the “/” in a URI to represent a parent child, whole-part relationship. §  Use a “gradual unfolding methodology” for exposing data to clients.This is, a resource representation should provide links to obtain more details. §  Always implement a service using HTTP GET when the purpose of the service is to allow a client to retrieve a resource representation. © Shakil Akhtar
  • 82.
    Common Objections toREST Data Services 4 Verbs and CRUD No formal definition language Internals exposed HTTP only Best Practices? No Transactions Unreliable No pub/sub No Asynchronous Interactions Lack of tools Security © Shakil Akhtar
  • 83.
    Data Service -4Verbs+CRUD §  Misunderstanding of Resources. §  Associations(Relationships) §  Processes §  Functions © Shakil Akhtar
  • 84.
    Internals Exposed §  URIsare not a one to one match. §  Separation of concern © Shakil Akhtar
  • 85.
    Best Practices? §  ManyBooks published §  JAX-RS standards © Shakil Akhtar
  • 86.
    Unreliable §  Remember theHTTP codes §  Re-send the request §  Idempotence - GET,PUT,DELETE © Shakil Akhtar
  • 87.
    No Pub/Sub §  RSS § AtomPub © Shakil Akhtar
  • 88.
    No Asynchronous Interaction § HTTP Code 202 - Accepted §  Queue the request / process later §  POST a response © Shakil Akhtar
  • 89.
  • 90.
    RESTful Testing §  cURL § REST-Client §  soapUI §  RESTGate © Shakil Akhtar
  • 91.
  • 92.
  • 93.
    Is REST beingused? © Shakil Akhtar
  • 94.
    Summary v Introduction to REST v CommonVerbs v RESTfulservices Implementation v Testing RESTful Services © Shakil Akhtar
  • 95.
  • 96.