SlideShare ist ein Scribd-Unternehmen logo
1 von 57
RESTful WebServices GouthamV Sr.Software Engineer InfoGroup
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Introduction REST is based on Ph.D thesis by a computer scientist (Roy Fieldings, year 2000) Principal author of HTTP Specification Co-founder of the Apache HTTP Server
Introduction Acronym for  Re presentational  S tate  T ransfer Alternative to SOAP style webservices Architecture of World Wide Web(HTTP)
Introduction Major players: S3, EC2…. Search, Maps Search, Del.icio.us, Flickr….
Introduction Usage statistics of Amazon webservices (EC2, S3, SimpleDB…) Source: Jeff Barr, Amazon chief architect of webservices
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How REST is Different From SOAP? Client Server Easy to handle by client and server Less bandwidth SOAP request REST request SOAP(Simple Object Access Protocol), all our current services are based on this.
How REST is Different From SOAP? SOAP request REST request <?xml version=&quot;1.0&quot;?> <soap:Envelope xmlns:soap=&quot;http://www.w3.org/2001/12/soap-envelope&quot; soap:encodingStyle=&quot;http://www.w3.org/2001/12/soap-encoding&quot;> <soap:Body ord=&quot;http://www.igroup.com/order&quot;> <ord:GetOrderDetails> <ord:OrderNum>1111</ord:OrderNum> </ord:GetOrderDetails> </soap:Body> </soap:Envelope> http://www.igroup.com/order?ordernum=1111
Why REST? Characteristics of a webservice:  Performance should be good  Scalable Easy to build and maintain (simplicity) Monitoring should be easy Reliable(handling failure, failover…)  Easy to use and test REST imposes certain  constraints  to achieve above characteristics  Uniform Interface Addressable Connectedness Stateless Cacheable
How RESTful services works? ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
How RESTful services works? REST says use HTTP to covey what service should do using predefined  HTTP protocol methods:   1. Replace create…. methods with  POST 2. Replace return….methods with  GET 3 .  Replace update…. Methods with  PUT 4. Replace delete… methods with  DELETE And also use HTTP protocol for everything else…
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Core Concepts Resource Everything that service provides is a resource Example Resources: Order info Invoice info Set of rows in a database Collection of search results
Core Concepts Resource Every Resource will have its own URI (A unique id) Example URIs: … /invoices?name=John Doe … /order?ordernum=1111 URI
Core Concepts A resource can be represented in many ways Example Representations: XML XHTML JSON CSV Resource Representation Representation URI
Core Concepts Each representation will have its own URL Example URLs: http://igroup.com/services/invoice? cname=John Doe http://igroup.com/services/order ?ordernum=1234 Resource Representation Representation URI URL URL
Core Concepts Clients interact via HTTP protocol defined methods Example: GET  http://igroup.com/services/order?cname=John Doe POST  http://igroup.com/services/order PUT http://igroup.com/services/order?ordernum=1234 DELETE  http://igroup.com/services/order? ordernum= 1234 Resource Representation Representation URI URL URL GET POST PUT DELETE
Core Concepts Representational State Transfer  (REST) Representation:  XML, XHTML, JSON, CSV.. State:  Application state (client side) and Resource state (server side)  Client Server POST GET PUT
Core Concepts All nouns only four verbs POST    http://service/order GET   http://service /invoice?num=1111 PUT    http://service /customer?osr=10000123 DELETE  http://service /address?osr=12345
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Resource Oriented Architecture(ROA) Restful webservices implement ROA Architecture and applies following  constraints : ,[object Object],[object Object],[object Object],[object Object]
Resource Oriented Architecture(ROA) Addressability Constraint: Every resource should be addressable Examples: GET  ../invoice?num=1234 GET  ../invoice?num=1234&output=xml GET  ../invoice?num=1234&output=json Benefits: Bookmark Email Link to it from your home page Monitoring East to test
Resource Oriented Architecture(ROA) Connectedness Constraint : Human web is well connected Programmable web is  not  well connected (Before REST!) RESTful services should guide clients from one state to  another by sending links in representation
Resource Oriented Architecture(ROA) Connectedness Constraint : Request: GET  ../invoice?name=John Doe Response: … .. <invoice> <num>1111</num> <url>../invoice?num=1111</url>   </invoice>  <invoice> <num>2222</num> <url>../invoice?num=2222</url>   </invoice>  … .. Example:
Resource Oriented Architecture(ROA) Statelessness Constraint : Every HTTP request should happen in complete isolation Service should never relay on information  from previous request Examples: GET  ../invoices?name=John Doe GET  ../invoices?name=John Doe & start=5&end=10 Benefits: Scalable (Load balancing) Simplicity Reliable
Resource Oriented Architecture(ROA) Cachable Constraint : Resources should be cachable whenever possible (with an expiration date/time) The HTTP  cache-control  headers are used for this purpose Benefits: Better response and loading time  Decreased load on the server  Better user experience
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
HTTP Recap HTTP status codes: RESTful services uses these codes to convey service response to clients  1xx indicates an  informational  message only  2xx indicates  success  of some kind  3xx r edirects  the client to another URL  4xx indicates an error on the  client's part  5xx indicates an error on the  server's part
HTTP Recap 2xx indicates  success  of some kind  Examples: 200 OK  Standard response for successful HTTP requests.  201 Created  The request has been fulfilled and resulted in a new resource being created. HTTP status codes:
HTTP Recap 4xx indicates an error on the  client's part  Examples: 400 Bad Request  401 Unauthorized HTTP status codes:
HTTP Recap 5xx indicates an error on the  server's part  Examples: 500 Internal Server Error  503 Service Unavailable  HTTP status codes:
HTTP Recap HTTP methods GET  POST  PUT  DELETE  HEAD  OPTIONS  CONNECT
HTTP Recap HTTP request headers Host :  www.google.com User-Agent:  Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 Accept:  text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language:  en-us,en;q=0.5 Accept-Encoding:  gzip,deflate Accept-Charset:  ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive:  300 Connection:  keep-alive
HTTP Recap HTTP response headers Cache-Control :  private, max-age=0 Date:  Wed, 17 Dec 2008 16:13:50 GMT Expires :  -1 Content-Type :  text/html; charset=UTF-8 Content-Encoding :  gzip Server :  gws Content-Length :  2251
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
REST features (Advanced HTTP)  Security: Basic authentication Digest authentication WSSE Username Token
REST features (Advanced HTTP) Security (Basic authentication) Uses HTTP  Authorization  and  WWW-Authenticate  headers Yahoo’s Del.icio.us service security is based on this authentication (https://api.del.icio.us/v1/posts/get) WWW-Authenticate  is to show what authentication type and realm Example:  401 Unauthorized www-Authenticate :   Basic   realm=“private data” Authorization  is to pass user name and password details in encoded form Example:  GET /posts/get Host:  api.del.icio.us  Authorization:  Basic dmdyZWRkeTQzOnZncjQzNDM=
REST features (Advanced HTTP) Security (Digest authentication) It also uses HTTP  Authorization  and  WWW-Authenticate  headers But, is sends hash(MD5)  of user name, pass word, nonce (number used only once) etc… to the server
REST features (Advanced HTTP) Security (Digest authentication) WWW-Authenticate  is to show what authentication type and realm Example:  401 Unauthorized www-Authenticate :  Digest   realm=“private data” qop=“auth” //qop= Quality of protection nonce=“0asdf0dsfdsf8sadf9sad0f9ds8f” Authorization  is to pass user name and password details in encoded form Example:  GET /posts/get Host:  api.del.icio.us  Authorization:   Digest   response= Ha3 Ha1=MD5.hexdigest(username, password, realm) Ha2=MD5.hexdigest(method, path) Ha3= MD5.hexdigest(ha1, nonce, qop, ha2.. )
REST features (Advanced HTTP) Transactions No specific HTTP headers are available for this purpose  Many options available but recommended approach sending multiple POST, PUT requests. This can be implemented in the same way as online  shopping cart implemented
REST features (Advanced HTTP) Transactions For example: Money transfer from account A to B POST  http://service/transaction  // returns {id} PUT  http://service/bankaccount/A/{id} //send amount to deduct PUT  http://service/bankaccount/B/{id} //send amount to add PUT  http://service/transaction /{id} //send commit=true
REST features (Advanced HTTP) Features Conditional GET Used for saving bandwidth  Implemented by using following HTTP headers: Request    Response If-Modified-Since    Last-Modified If-None-Match    E-Tag (entity tag)
REST features (Advanced HTTP) Conditional GET Example for:  If-Modified-Since  Last-Modified  GET ../invoice/1111 200 OK Last-Modified : Mon, 1 Dec 2008 09:00 CST Representation size: 40KB GET ../invoice/1111 If-Modified-Since:  Mon, 1 Dec 2008 09:00 CST 304 “Not Modified” Representation size: 0KB Request Response
REST features (Advanced HTTP) Conditional GET Example for:  If-None-Match    E-Tag  GET ../invoice/1111 200 OK E-Tag : “75sdf5454dcd-sd4fsd8-sdf ” Representation size: 40KB GET ../invoice/1111 If-None-Match  :  “75sdf5454dcd-sd4fsd8-sdf ” 304 “Not Modified” Representation size: 0KB Request Response More reliable than previous approach. Uses MD5 hash of representation(Apache calculates MD5 hash using size and last modified time of representation)
REST features (Advanced HTTP) Caching Expires:  Mon, 1, Jan 2010 Cache-Control:  max-age=3600 Cache-Control:  no-cache
HTTP REST features (Advanced HTTP) Look Before You Leap Requests Another way to save bandwidth //Request to service PUT /filestore/myfile.txt Host: somehost.com Content-length:  500MB Expect:  100-continue 417 (Expectation Failed) //If service rejects request 100 (Continue) //If service accepts  request
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
WADL WADL ( W eb  A pplication  D escription Language) Not as widely used as WSDL Since only 4 types of methods available for a service, it is an over kill Most REST services are documented by no more than a textual description  WADL2JAVA  tool available at:  http://wadl.dev.java.net
REST frameworks Restlet (Java)  Rest-open-uri (Ruby on Rails) System.web.HTTPWebRequest (.net) Django (Python)
RESTful WebServices ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
SOAP Vs REST SOAP SOAP has mature tool support Transport Independence:  The headers are inside the message that means they are independent of  the protocol used to transport message You can send SOAP envelope over SMTP, FTP, JMS….. Security, reliability etc.. are industry standards (WS-*) WS-Security WS-ReliableMessaging WS-AtomicTransaction  WS-BusinessActivity
SOAP Vs REST SOAP WS-Security: Standards for sending passwords, Kerberos tokens. X.509 tokens These standard are well suited for banking and financial services WS-ReliableMessaging:  Defines new headers for that track sequence identifiers, message  numbers and some retry logic. WS-AtomicTransaction  Transactions based on two phase commit
SOAP Vs REST REST Simplicity (easy to use, maintain and test) Many options for representations(JSON, CSV, XHTML, XML..) Human Readable Results Performance: Scalable architecture Lightweight requests and responses Easier response parsing Saves bandwidth(Caching, Conditional GET..) Well suited for AJAX clients(using JSON representations)
More info on REST Purely academic: the notion of REST was created in the PhD dissertation of Roy T. Fielding. Mostly academic: the Wikipedia article about REST. JSR 311 is the Java Specification Request for &quot;JAX-RS: The Java API for RESTful Web Services&quot;. Restlet is suggesting an easier way to develop REST applications in Java: restlet.org. WADL: find the specification and tools in the Web Application Description Language's homepage. Articles are a dime a dozen; here are a few interesting ones: Second Generation Web Services by Paul Prescod. The Beauty of REST, by Jon Udell. Building Web Services the REST Way by Roger L. Costello REST vs. SOAP, by Pete Freitag. Basic SOA using REST, by Mark Hansen.
More info on REST Books:: RESTful Web Services by Leonard Richardson –  Ajax and REST Recipes: A Problem-Solution Approach, by Christian Gross

Weitere ähnliche Inhalte

Was ist angesagt?

Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service Design
Lorna Mitchell
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
srividhyau
 

Was ist angesagt? (20)

Understanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple StepsUnderstanding REST APIs in 5 Simple Steps
Understanding REST APIs in 5 Simple Steps
 
REST & RESTful Web Services
REST & RESTful Web ServicesREST & RESTful Web Services
REST & RESTful Web Services
 
REST-API overview / concepts
REST-API overview / conceptsREST-API overview / concepts
REST-API overview / concepts
 
Best Practices in Web Service Design
Best Practices in Web Service DesignBest Practices in Web Service Design
Best Practices in Web Service Design
 
Learn REST in 18 Slides
Learn REST in 18 SlidesLearn REST in 18 Slides
Learn REST in 18 Slides
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 
Rest API
Rest APIRest API
Rest API
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Design Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIsDesign Beautiful REST + JSON APIs
Design Beautiful REST + JSON APIs
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 
Best practices for RESTful web service design
Best practices for RESTful web service designBest practices for RESTful web service design
Best practices for RESTful web service design
 
RESTful API - Best Practices
RESTful API - Best PracticesRESTful API - Best Practices
RESTful API - Best Practices
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Rest presentation
Rest  presentationRest  presentation
Rest presentation
 
Rest api standards and best practices
Rest api standards and best practicesRest api standards and best practices
Rest api standards and best practices
 
Simple object access protocol(soap )
Simple object access protocol(soap )Simple object access protocol(soap )
Simple object access protocol(soap )
 
Web services SOAP
Web services SOAPWeb services SOAP
Web services SOAP
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
 
REST - Representational State Transfer
REST - Representational State TransferREST - Representational State Transfer
REST - Representational State Transfer
 

Ähnlich wie RESTful services

RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
Li Yi
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web Services
Anuchit Chalothorn
 
Json-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webJson-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the web
kriszyp
 
A Conversation About REST - Extended Version
A Conversation About REST - Extended VersionA Conversation About REST - Extended Version
A Conversation About REST - Extended Version
Jeremy Brown
 
Hypertext Transfer Protocol
Hypertext Transfer ProtocolHypertext Transfer Protocol
Hypertext Transfer Protocol
Rajan Pandey
 

Ähnlich wie RESTful services (20)

RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
 
01. http basics v27
01. http basics v2701. http basics v27
01. http basics v27
 
Under the Covers with the Web
Under the Covers with the WebUnder the Covers with the Web
Under the Covers with the Web
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web Services
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
Unerstanding and Using RESTful APIs
Unerstanding and Using RESTful APIsUnerstanding and Using RESTful APIs
Unerstanding and Using RESTful APIs
 
KaTe RESTful adapter for SAP Process Integration: Introduction
KaTe RESTful adapter for SAP Process Integration: IntroductionKaTe RESTful adapter for SAP Process Integration: Introduction
KaTe RESTful adapter for SAP Process Integration: Introduction
 
Json-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the webJson-based Service Oriented Architecture for the web
Json-based Service Oriented Architecture for the web
 
Representational State Transfer (REST) and HATEOAS
Representational State Transfer (REST) and HATEOASRepresentational State Transfer (REST) and HATEOAS
Representational State Transfer (REST) and HATEOAS
 
ReST
ReSTReST
ReST
 
A Conversation About REST - Extended Version
A Conversation About REST - Extended VersionA Conversation About REST - Extended Version
A Conversation About REST - Extended Version
 
WebApp #3 : API
WebApp #3 : APIWebApp #3 : API
WebApp #3 : API
 
Hypertext Transfer Protocol
Hypertext Transfer ProtocolHypertext Transfer Protocol
Hypertext Transfer Protocol
 
HTTP Request and Response Structure
HTTP Request and Response StructureHTTP Request and Response Structure
HTTP Request and Response Structure
 
A2 from soap to rest
A2 from soap to restA2 from soap to rest
A2 from soap to rest
 
HTTP fundamentals for developers
HTTP fundamentals for developersHTTP fundamentals for developers
HTTP fundamentals for developers
 
Introduction To REST
Introduction To RESTIntroduction To REST
Introduction To REST
 
Understanding and Using Rest APIs (SocialDevCamp Chicago 2009)
Understanding and Using Rest APIs (SocialDevCamp Chicago 2009)Understanding and Using Rest APIs (SocialDevCamp Chicago 2009)
Understanding and Using Rest APIs (SocialDevCamp Chicago 2009)
 
ASP.NET WEB API Training
ASP.NET WEB API TrainingASP.NET WEB API Training
ASP.NET WEB API Training
 
REST APIs in the context of single-page applications
REST APIs in the context of single-page applicationsREST APIs in the context of single-page applications
REST APIs in the context of single-page applications
 

Kürzlich hochgeladen

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
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...
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
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?
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
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...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
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...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 

RESTful services

  • 1. RESTful WebServices GouthamV Sr.Software Engineer InfoGroup
  • 2.
  • 3. Introduction REST is based on Ph.D thesis by a computer scientist (Roy Fieldings, year 2000) Principal author of HTTP Specification Co-founder of the Apache HTTP Server
  • 4. Introduction Acronym for Re presentational S tate T ransfer Alternative to SOAP style webservices Architecture of World Wide Web(HTTP)
  • 5. Introduction Major players: S3, EC2…. Search, Maps Search, Del.icio.us, Flickr….
  • 6. Introduction Usage statistics of Amazon webservices (EC2, S3, SimpleDB…) Source: Jeff Barr, Amazon chief architect of webservices
  • 7.
  • 8. How REST is Different From SOAP? Client Server Easy to handle by client and server Less bandwidth SOAP request REST request SOAP(Simple Object Access Protocol), all our current services are based on this.
  • 9. How REST is Different From SOAP? SOAP request REST request <?xml version=&quot;1.0&quot;?> <soap:Envelope xmlns:soap=&quot;http://www.w3.org/2001/12/soap-envelope&quot; soap:encodingStyle=&quot;http://www.w3.org/2001/12/soap-encoding&quot;> <soap:Body ord=&quot;http://www.igroup.com/order&quot;> <ord:GetOrderDetails> <ord:OrderNum>1111</ord:OrderNum> </ord:GetOrderDetails> </soap:Body> </soap:Envelope> http://www.igroup.com/order?ordernum=1111
  • 10. Why REST? Characteristics of a webservice: Performance should be good Scalable Easy to build and maintain (simplicity) Monitoring should be easy Reliable(handling failure, failover…) Easy to use and test REST imposes certain constraints to achieve above characteristics Uniform Interface Addressable Connectedness Stateless Cacheable
  • 11.
  • 12. How RESTful services works? REST says use HTTP to covey what service should do using predefined HTTP protocol methods: 1. Replace create…. methods with POST 2. Replace return….methods with GET 3 . Replace update…. Methods with PUT 4. Replace delete… methods with DELETE And also use HTTP protocol for everything else…
  • 13.
  • 14. Core Concepts Resource Everything that service provides is a resource Example Resources: Order info Invoice info Set of rows in a database Collection of search results
  • 15. Core Concepts Resource Every Resource will have its own URI (A unique id) Example URIs: … /invoices?name=John Doe … /order?ordernum=1111 URI
  • 16. Core Concepts A resource can be represented in many ways Example Representations: XML XHTML JSON CSV Resource Representation Representation URI
  • 17. Core Concepts Each representation will have its own URL Example URLs: http://igroup.com/services/invoice? cname=John Doe http://igroup.com/services/order ?ordernum=1234 Resource Representation Representation URI URL URL
  • 18. Core Concepts Clients interact via HTTP protocol defined methods Example: GET http://igroup.com/services/order?cname=John Doe POST http://igroup.com/services/order PUT http://igroup.com/services/order?ordernum=1234 DELETE http://igroup.com/services/order? ordernum= 1234 Resource Representation Representation URI URL URL GET POST PUT DELETE
  • 19. Core Concepts Representational State Transfer (REST) Representation: XML, XHTML, JSON, CSV.. State: Application state (client side) and Resource state (server side) Client Server POST GET PUT
  • 20. Core Concepts All nouns only four verbs POST http://service/order GET http://service /invoice?num=1111 PUT http://service /customer?osr=10000123 DELETE http://service /address?osr=12345
  • 21.
  • 22.
  • 23. Resource Oriented Architecture(ROA) Addressability Constraint: Every resource should be addressable Examples: GET ../invoice?num=1234 GET ../invoice?num=1234&output=xml GET ../invoice?num=1234&output=json Benefits: Bookmark Email Link to it from your home page Monitoring East to test
  • 24. Resource Oriented Architecture(ROA) Connectedness Constraint : Human web is well connected Programmable web is not well connected (Before REST!) RESTful services should guide clients from one state to another by sending links in representation
  • 25. Resource Oriented Architecture(ROA) Connectedness Constraint : Request: GET ../invoice?name=John Doe Response: … .. <invoice> <num>1111</num> <url>../invoice?num=1111</url> </invoice> <invoice> <num>2222</num> <url>../invoice?num=2222</url> </invoice> … .. Example:
  • 26. Resource Oriented Architecture(ROA) Statelessness Constraint : Every HTTP request should happen in complete isolation Service should never relay on information from previous request Examples: GET ../invoices?name=John Doe GET ../invoices?name=John Doe & start=5&end=10 Benefits: Scalable (Load balancing) Simplicity Reliable
  • 27. Resource Oriented Architecture(ROA) Cachable Constraint : Resources should be cachable whenever possible (with an expiration date/time) The HTTP cache-control headers are used for this purpose Benefits: Better response and loading time Decreased load on the server Better user experience
  • 28.
  • 29. HTTP Recap HTTP status codes: RESTful services uses these codes to convey service response to clients 1xx indicates an informational message only 2xx indicates success of some kind 3xx r edirects the client to another URL 4xx indicates an error on the client's part 5xx indicates an error on the server's part
  • 30. HTTP Recap 2xx indicates success of some kind Examples: 200 OK Standard response for successful HTTP requests. 201 Created The request has been fulfilled and resulted in a new resource being created. HTTP status codes:
  • 31. HTTP Recap 4xx indicates an error on the client's part Examples: 400 Bad Request 401 Unauthorized HTTP status codes:
  • 32. HTTP Recap 5xx indicates an error on the server's part Examples: 500 Internal Server Error 503 Service Unavailable HTTP status codes:
  • 33. HTTP Recap HTTP methods GET POST PUT DELETE HEAD OPTIONS CONNECT
  • 34. HTTP Recap HTTP request headers Host : www.google.com User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.4) Gecko/2008102920 Firefox/3.0.4 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive
  • 35. HTTP Recap HTTP response headers Cache-Control : private, max-age=0 Date: Wed, 17 Dec 2008 16:13:50 GMT Expires : -1 Content-Type : text/html; charset=UTF-8 Content-Encoding : gzip Server : gws Content-Length : 2251
  • 36.
  • 37.
  • 38. REST features (Advanced HTTP) Security: Basic authentication Digest authentication WSSE Username Token
  • 39. REST features (Advanced HTTP) Security (Basic authentication) Uses HTTP Authorization and WWW-Authenticate headers Yahoo’s Del.icio.us service security is based on this authentication (https://api.del.icio.us/v1/posts/get) WWW-Authenticate is to show what authentication type and realm Example: 401 Unauthorized www-Authenticate : Basic realm=“private data” Authorization is to pass user name and password details in encoded form Example: GET /posts/get Host: api.del.icio.us Authorization: Basic dmdyZWRkeTQzOnZncjQzNDM=
  • 40. REST features (Advanced HTTP) Security (Digest authentication) It also uses HTTP Authorization and WWW-Authenticate headers But, is sends hash(MD5) of user name, pass word, nonce (number used only once) etc… to the server
  • 41. REST features (Advanced HTTP) Security (Digest authentication) WWW-Authenticate is to show what authentication type and realm Example: 401 Unauthorized www-Authenticate : Digest realm=“private data” qop=“auth” //qop= Quality of protection nonce=“0asdf0dsfdsf8sadf9sad0f9ds8f” Authorization is to pass user name and password details in encoded form Example: GET /posts/get Host: api.del.icio.us Authorization: Digest response= Ha3 Ha1=MD5.hexdigest(username, password, realm) Ha2=MD5.hexdigest(method, path) Ha3= MD5.hexdigest(ha1, nonce, qop, ha2.. )
  • 42. REST features (Advanced HTTP) Transactions No specific HTTP headers are available for this purpose Many options available but recommended approach sending multiple POST, PUT requests. This can be implemented in the same way as online shopping cart implemented
  • 43. REST features (Advanced HTTP) Transactions For example: Money transfer from account A to B POST http://service/transaction // returns {id} PUT http://service/bankaccount/A/{id} //send amount to deduct PUT http://service/bankaccount/B/{id} //send amount to add PUT http://service/transaction /{id} //send commit=true
  • 44. REST features (Advanced HTTP) Features Conditional GET Used for saving bandwidth Implemented by using following HTTP headers: Request Response If-Modified-Since Last-Modified If-None-Match E-Tag (entity tag)
  • 45. REST features (Advanced HTTP) Conditional GET Example for: If-Modified-Since Last-Modified GET ../invoice/1111 200 OK Last-Modified : Mon, 1 Dec 2008 09:00 CST Representation size: 40KB GET ../invoice/1111 If-Modified-Since: Mon, 1 Dec 2008 09:00 CST 304 “Not Modified” Representation size: 0KB Request Response
  • 46. REST features (Advanced HTTP) Conditional GET Example for: If-None-Match E-Tag GET ../invoice/1111 200 OK E-Tag : “75sdf5454dcd-sd4fsd8-sdf ” Representation size: 40KB GET ../invoice/1111 If-None-Match : “75sdf5454dcd-sd4fsd8-sdf ” 304 “Not Modified” Representation size: 0KB Request Response More reliable than previous approach. Uses MD5 hash of representation(Apache calculates MD5 hash using size and last modified time of representation)
  • 47. REST features (Advanced HTTP) Caching Expires: Mon, 1, Jan 2010 Cache-Control: max-age=3600 Cache-Control: no-cache
  • 48. HTTP REST features (Advanced HTTP) Look Before You Leap Requests Another way to save bandwidth //Request to service PUT /filestore/myfile.txt Host: somehost.com Content-length: 500MB Expect: 100-continue 417 (Expectation Failed) //If service rejects request 100 (Continue) //If service accepts request
  • 49.
  • 50. WADL WADL ( W eb A pplication D escription Language) Not as widely used as WSDL Since only 4 types of methods available for a service, it is an over kill Most REST services are documented by no more than a textual description WADL2JAVA tool available at: http://wadl.dev.java.net
  • 51. REST frameworks Restlet (Java) Rest-open-uri (Ruby on Rails) System.web.HTTPWebRequest (.net) Django (Python)
  • 52.
  • 53. SOAP Vs REST SOAP SOAP has mature tool support Transport Independence: The headers are inside the message that means they are independent of the protocol used to transport message You can send SOAP envelope over SMTP, FTP, JMS….. Security, reliability etc.. are industry standards (WS-*) WS-Security WS-ReliableMessaging WS-AtomicTransaction WS-BusinessActivity
  • 54. SOAP Vs REST SOAP WS-Security: Standards for sending passwords, Kerberos tokens. X.509 tokens These standard are well suited for banking and financial services WS-ReliableMessaging: Defines new headers for that track sequence identifiers, message numbers and some retry logic. WS-AtomicTransaction Transactions based on two phase commit
  • 55. SOAP Vs REST REST Simplicity (easy to use, maintain and test) Many options for representations(JSON, CSV, XHTML, XML..) Human Readable Results Performance: Scalable architecture Lightweight requests and responses Easier response parsing Saves bandwidth(Caching, Conditional GET..) Well suited for AJAX clients(using JSON representations)
  • 56. More info on REST Purely academic: the notion of REST was created in the PhD dissertation of Roy T. Fielding. Mostly academic: the Wikipedia article about REST. JSR 311 is the Java Specification Request for &quot;JAX-RS: The Java API for RESTful Web Services&quot;. Restlet is suggesting an easier way to develop REST applications in Java: restlet.org. WADL: find the specification and tools in the Web Application Description Language's homepage. Articles are a dime a dozen; here are a few interesting ones: Second Generation Web Services by Paul Prescod. The Beauty of REST, by Jon Udell. Building Web Services the REST Way by Roger L. Costello REST vs. SOAP, by Pete Freitag. Basic SOA using REST, by Mark Hansen.
  • 57. More info on REST Books:: RESTful Web Services by Leonard Richardson – Ajax and REST Recipes: A Problem-Solution Approach, by Christian Gross