SlideShare a Scribd company logo
1 of 96
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

More Related Content

What's hot

ADF Anti-Patterns: Dangerous Tutorials
ADF Anti-Patterns: Dangerous TutorialsADF Anti-Patterns: Dangerous Tutorials
ADF Anti-Patterns: Dangerous Tutorialsandrejusb
 
Finally, EE Security API JSR 375
Finally, EE Security API JSR 375Finally, EE Security API JSR 375
Finally, EE Security API JSR 375Alex Kosowski
 
ADF Development Survival Kit
ADF Development Survival KitADF Development Survival Kit
ADF Development Survival Kitandrejusb
 
CloudComputing
CloudComputingCloudComputing
CloudComputingAdi Challa
 
ADF Mythbusters UKOUG'14
ADF Mythbusters UKOUG'14ADF Mythbusters UKOUG'14
ADF Mythbusters UKOUG'14andrejusb
 
Down-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EEDown-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EEReza Rahman
 
Testing Java EE Applications Using Arquillian
Testing Java EE Applications Using ArquillianTesting Java EE Applications Using Arquillian
Testing Java EE Applications Using ArquillianReza Rahman
 
Data Caching Strategies for Oracle Mobile Application Framework
Data Caching Strategies for Oracle Mobile Application FrameworkData Caching Strategies for Oracle Mobile Application Framework
Data Caching Strategies for Oracle Mobile Application Frameworkandrejusb
 
Restful api design
Restful api designRestful api design
Restful api designMizan Riqzia
 
Enable Domino Data Access Services (DAS)
Enable Domino Data Access Services (DAS)Enable Domino Data Access Services (DAS)
Enable Domino Data Access Services (DAS)Slobodan Lohja
 
Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Edward Burns
 
REST: So What's It All About? (SAP TechEd 2011, MOB107)
REST: So What's It All About? (SAP TechEd 2011, MOB107)REST: So What's It All About? (SAP TechEd 2011, MOB107)
REST: So What's It All About? (SAP TechEd 2011, MOB107)Sascha Wenninger
 
Access External Data in Real-time with Lightning Connect
Access External Data in Real-time with Lightning ConnectAccess External Data in Real-time with Lightning Connect
Access External Data in Real-time with Lightning ConnectSalesforce Developers
 

What's hot (17)

Apex REST
Apex RESTApex REST
Apex REST
 
ADF Anti-Patterns: Dangerous Tutorials
ADF Anti-Patterns: Dangerous TutorialsADF Anti-Patterns: Dangerous Tutorials
ADF Anti-Patterns: Dangerous Tutorials
 
Finally, EE Security API JSR 375
Finally, EE Security API JSR 375Finally, EE Security API JSR 375
Finally, EE Security API JSR 375
 
RESTful APIs
RESTful APIsRESTful APIs
RESTful APIs
 
OAuth
OAuthOAuth
OAuth
 
ADF Development Survival Kit
ADF Development Survival KitADF Development Survival Kit
ADF Development Survival Kit
 
API Basics
API BasicsAPI Basics
API Basics
 
CloudComputing
CloudComputingCloudComputing
CloudComputing
 
ADF Mythbusters UKOUG'14
ADF Mythbusters UKOUG'14ADF Mythbusters UKOUG'14
ADF Mythbusters UKOUG'14
 
Down-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EEDown-to-Earth Microservices with Java EE
Down-to-Earth Microservices with Java EE
 
Testing Java EE Applications Using Arquillian
Testing Java EE Applications Using ArquillianTesting Java EE Applications Using Arquillian
Testing Java EE Applications Using Arquillian
 
Data Caching Strategies for Oracle Mobile Application Framework
Data Caching Strategies for Oracle Mobile Application FrameworkData Caching Strategies for Oracle Mobile Application Framework
Data Caching Strategies for Oracle Mobile Application Framework
 
Restful api design
Restful api designRestful api design
Restful api design
 
Enable Domino Data Access Services (DAS)
Enable Domino Data Access Services (DAS)Enable Domino Data Access Services (DAS)
Enable Domino Data Access Services (DAS)
 
Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015Servlet 4.0 at GeekOut 2015
Servlet 4.0 at GeekOut 2015
 
REST: So What's It All About? (SAP TechEd 2011, MOB107)
REST: So What's It All About? (SAP TechEd 2011, MOB107)REST: So What's It All About? (SAP TechEd 2011, MOB107)
REST: So What's It All About? (SAP TechEd 2011, MOB107)
 
Access External Data in Real-time with Lightning Connect
Access External Data in Real-time with Lightning ConnectAccess External Data in Real-time with Lightning Connect
Access External Data in Real-time with Lightning Connect
 

Similar to Restful Services

Architecting &Building Scalable Secure Web API
Architecting &Building Scalable Secure Web APIArchitecting &Building Scalable Secure Web API
Architecting &Building Scalable Secure Web APISHAKIL AKHTAR
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introductionDaniel Toader
 
SSO With APEX and ADFS the weblogic way
SSO With APEX and ADFS the weblogic waySSO With APEX and ADFS the weblogic way
SSO With APEX and ADFS the weblogic waymakker_nl
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_daviddTakashi Ito
 
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...Revelation Technologies
 
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)Carles Farré
 
REST API 20.2 - Appworks Gateway Integration.pptx
REST API 20.2 - Appworks Gateway Integration.pptxREST API 20.2 - Appworks Gateway Integration.pptx
REST API 20.2 - Appworks Gateway Integration.pptxJason452803
 
Enterprise Single Sign On
Enterprise Single Sign On Enterprise Single Sign On
Enterprise Single Sign On WSO2
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureFrank Greco
 
RefCard RESTful API Design
RefCard RESTful API DesignRefCard RESTful API Design
RefCard RESTful API DesignOCTO Technology
 
Entity Linking and REST Patterns in SOA
Entity Linking and REST Patterns in SOA Entity Linking and REST Patterns in SOA
Entity Linking and REST Patterns in SOA WSO2
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB
 
Summit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan Wright
Summit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan WrightSummit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan Wright
Summit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan WrightAndrew Ly
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta jaxconf
 
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun GuptaGetting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun GuptaCodemotion
 

Similar to Restful Services (20)

Architecting &Building Scalable Secure Web API
Architecting &Building Scalable Secure Web APIArchitecting &Building Scalable Secure Web API
Architecting &Building Scalable Secure Web API
 
A RESTful introduction
A RESTful introductionA RESTful introduction
A RESTful introduction
 
SSO With APEX and ADFS the weblogic way
SSO With APEX and ADFS the weblogic waySSO With APEX and ADFS the weblogic way
SSO With APEX and ADFS the weblogic way
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
112815 java ee8_davidd
112815 java ee8_davidd112815 java ee8_davidd
112815 java ee8_davidd
 
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...Automating Cloud Operations - Everything you wanted to know about cURL and RE...
Automating Cloud Operations - Everything you wanted to know about cURL and RE...
 
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
[DSBW Spring 2009] Unit 02: Web Technologies (2/2)
 
REST API 20.2 - Appworks Gateway Integration.pptx
REST API 20.2 - Appworks Gateway Integration.pptxREST API 20.2 - Appworks Gateway Integration.pptx
REST API 20.2 - Appworks Gateway Integration.pptx
 
Enterprise Single Sign On
Enterprise Single Sign On Enterprise Single Sign On
Enterprise Single Sign On
 
WebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the FutureWebSocket Perspectives and Vision for the Future
WebSocket Perspectives and Vision for the Future
 
RefCard RESTful API Design
RefCard RESTful API DesignRefCard RESTful API Design
RefCard RESTful API Design
 
Entity Linking and REST Patterns in SOA
Entity Linking and REST Patterns in SOA Entity Linking and REST Patterns in SOA
Entity Linking and REST Patterns in SOA
 
JAX-RS.next
JAX-RS.nextJAX-RS.next
JAX-RS.next
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless World
 
Introduction about Alfresco webscript
Introduction about Alfresco webscriptIntroduction about Alfresco webscript
Introduction about Alfresco webscript
 
Summit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan Wright
Summit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan WrightSummit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan Wright
Summit Australia 2019 - PowerApp Portals - Andrew Ly & Lachlan Wright
 
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta Getting started with Websocket and Server-sent Events using Java - Arun Gupta
Getting started with Websocket and Server-sent Events using Java - Arun Gupta
 
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun GuptaGetting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
Getting Started with WebSocket and Server-Sent Events using Java by Arun Gupta
 

Recently uploaded

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
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
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
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
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
 
[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
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 
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
 

Recently uploaded (20)

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?
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
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...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
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
 
[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
 
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)
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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...
 

Restful Services

  • 2. 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
  • 4. 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
  • 5. What’s the point? Integration Architecture © Shakil Akhtar
  • 6. Where have We Been ? RPC CORBA POX Big Web Services REST © Shakil Akhtar
  • 7. Introduction To REST § What is REST § RESTful Architectural Principles © Shakil Akhtar
  • 8. Architecture of the web © Shakil Akhtar
  • 9. 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
  • 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
  • 12. Resources v Things §  Order §  Product v Associations §  Enrollment §  Membership v Processes §  Onboarding §  Mentoring v Functions §  Driving Directions §  Search © Shakil Akhtar
  • 14. RESTful Architectural Principle v Addressability. v Uniform Constrained Interface v Representation Oriented v Communicate Statelessly. v HATEOAS(Connectedness) © Shakil Akhtar
  • 15. 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
  • 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 GET Request 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 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
  • 20. 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
  • 21. 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
  • 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 Interface Important? v  Familiarity. v  Interoperability. v  Scalability © Shakil Akhtar
  • 25. 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
  • 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  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
  • 28. 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
  • 30. 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
  • 31. Link state transition Use Case v  Possible state transitions for a coffee order © Shakil Akhtar
  • 32. Designing REST web services © Shakil Akhtar v The Object Model v Model the URIs v Defining the data format v Assigning HTTP Methods
  • 33. First REST Service v Developing a JAX-RS RESTful service v Deploying our service © Shakil Akhtar
  • 34. JAX-RS Injection v  The Basics v  @PathParam v  @MatrixParam v  @QuesryParam v  @FormParam v  @HeaderParam v  @CookieParam v  Common Functionality © Shakil Akhtar
  • 35. @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
  • 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 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
  • 38. @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
  • 39. @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
  • 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> 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
  • 42. @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
  • 43. @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
  • 44. JAX-RS Content Handler §  Built-in Content Marshaling §  JAXB §  Custom Marshaling © Shakil Akhtar
  • 45. 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
  • 46. 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
  • 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 §  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
  • 50. 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
  • 51. 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
  • 52. 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
  • 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
  • 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 is the 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 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
  • 66. 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
  • 67. 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
  • 68. 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
  • 69. HTTP Status Codes- By HTTP Verb © Shakil Akhtar
  • 70. HTTP Status Codes- Other © Shakil Akhtar
  • 71. REST Platforms Jersey RESTEasy Restlet ApacheCXF Rails Grails Django © Shakil Akhtar
  • 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 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
  • 83. Data Service -4 Verbs+CRUD §  Misunderstanding of Resources. §  Associations(Relationships) §  Processes §  Functions © Shakil Akhtar
  • 84. Internals Exposed §  URIs are not a one to one match. §  Separation of concern © Shakil Akhtar
  • 85. Best Practices? §  Many Books published §  JAX-RS standards © Shakil Akhtar
  • 86. Unreliable §  Remember the HTTP 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
  • 90. RESTful Testing §  cURL §  REST-Client §  soapUI §  RESTGate © Shakil Akhtar
  • 93. Is REST being used? © Shakil Akhtar
  • 94. Summary v Introduction to REST v CommonVerbs v RESTful services Implementation v Testing RESTful Services © Shakil Akhtar