SlideShare a Scribd company logo
1 of 56
Download to read offline
How to do RESTful
web services right
   Kerry Buckley & Paul Moser

         BT DevCon2

         9 March 2010
w ay
 ne
O How to do RESTful
   web services right
w ay
 ne
O How to do RESTful
   web services right
     (for some value of ‘right’)
What is REST?



REST is an architectural style, not a protocol or a standard. Hence many values of “right” (and
much disagreement).
‘A style of software
              architecture for
          distributed hypermedia
            systems such as the
             World Wide Web’

Not necessarily HTTP, although in practice it generally is.
Not SOAP



Seems to be a common (but wrong) definition.
Constraints
• Client-server
• Stateless
• Cacheable
• Layered system
• Uniform interface
Principles
• Identification of resources
• Manipulation of resources through these
  representations

• Self-descriptive messages
• Hypermedia as the engine of application
  state
Goals
• Scalability of component interactions
• Generality of interfaces
• Independent deployment of components
• Intermediary components to reduce
  latency, enforce security and encapsulate
  legacy systems
Shop example
• List products
• View a product
• Create an order for a number of products
• Cancel order
• Pay for order
XML-RPC
(URI-tunnelling)
GET /api?action=list_products

      GET /api?action=view_product&product_id=123

      GET /api?action=create_order&product_id=123&product_id=456…

      GET/api?action=pay_order&order_id=42&card_number=1234…




Sometimes only a single ‘endpoint’ URI
GET /list_products

     GET /view_product?product_id=123

     GET /create_order?product_id=123&product_id=456…

     GET/pay_order?order_id=42&card_number=1234…




Or one endpoint per method
GET /list_products

      GET /view_product?product_id=123

      POST /create_order?product_id=123&product_id=456…

      POST /pay_order?order_id=42&card_number=1234…




Marginally better without unsafe GETs
POST /pay_order?order_id=42&card_number=1234…

      def pay_order(order_id, card_number) {
        …
      }




Request maps onto method call.
✓Easy to understand
✓Works well for simple procedure calls
✓Simple to implement
✓Interoperable
✗ Brittle
          ✗ Tightly coupled
          ✗ Failure cases require manual handling
          ✗ No metadata


Need to know all the URIs, methods and parameters in advance (out-of-band documentation)
But is it REST?
✗ Identification of resources
✗ Manipulation of resources through these
   representations
✗ Self-descriptive messages
✗ Hypermedia as the engine of application
   state
POX
(plain old XML)
Request

     POST /create_order

     <create_order_request>
      <line>
        <product_id>123</product_line>
        <quantity>1</quantity>
      </line>
      …
     </create_order_request>

     Response

     200 OK

     <create_order_response>
      <status>OK</status>
      <order_id>42</order_id>
     </create_order_response>

Both request and response have XML bodies.
✓Simple to implement
✓Interoperable
✓Allows complex data structures
✗ Tightly coupled
✗ No metadata
✗ Doesn’t use web for robustness
✗ Doesn’t use SOAP for robustness either
But is it REST?
✗ Identification of resources
✗ Manipulation of resources through these
   representations
✗ Self-descriptive messages
✗ Hypermedia as the engine of application
   state
CRUD
GET /products

GET /products/123

POST /orders

PUT /orders/42

DELETE /orders/42

POST /orders/42/payment
Representations
•   Hypermedia              •   Non-hypermedia

    -   XHTML                   -   Generic XML

    -   Atom                    -   YAML

    -   Custom XML schema       -   JSON

                                -   CSV

                                -   etc
✓Makes good use of HTTP
          ✓Uniform interface
          ✓Good for database-style applications


Because each resource has a URI you can use caching etc. Uniform interface: verbs are GET,
POST, PUT and DELETE.
✗ Ignores hypermedia
✗ Tight coupling through URI templates
✗ Not self-describing
But is it REST?
✓ Identification of resources
✓ Manipulation of resources through these
   representations
✗ Self-descriptive messages
✗ Hypermedia as the engine of application
   state
REST
API root
Request

GET /
API root
            Response

            200 OK
            Content-Type: application/vnd.rest-example.store+xml

            <store>
             <link method="get" rel="products" href="http://rest-demo.local/products"/>
             <link method="get" rel="orders" href="http://rest-demo.local/orders"/>
            </store>




Links contain information on what we can do.
View products
             Request

             Get /products




Following the link with a relation of ‘products’ (link rel="products").
View products
             Response

             200 OK
             Content-Type: application/vnd.rest-example.products+xml

             <products>
              <link method="get" rel="latest" href="http://rest-demo.local/products"/>
              <product>
               <link method="get" rel="view" href="http://rest-demo.local/products/1"/>
               <code>A-001</code>
               <description>Tartan Paint</description>
               <price>4.95</price>
              </product>
              …
             </products>




Note link to retrieve the latest version of this resource (eg if you had it cached).
View orders
Request

Get /orders
View orders
            Response

            200 OK
            Content-Type: application/vnd.rest-example.orders+xml

            <orders>
             <link method="get" rel="latest" href="http://rest-demo.local/orders"/>
             <link type="application/vnd.rest-example.order+xml" method="post"
              rel="new" href="http://rest-demo.local/orders"/>
            </orders>




No orders yet, but note link to create a new one.
Place order
            Request

            POST /orders
            Content-Type: application/vnd.rest-example.order+xml

            <order>
             <line>
              <product>http://rest-demo.local/products/1</product>
              <quantity>2</quantity>
             </line>
            </order>




Again following a link, this time posting data of the specified type.
Place order
            Response

            201 Created
            Content-Type: application/vnd.rest-example.order+xml

            <order>
             <link method="get" rel="latest" href="http://rest-demo.local/orders/9"/>
             <link method="delete" rel="cancel" href="http://rest-demo.local/orders/9"/>
             <link type="application/vnd.rest-example.payment-details+xml"
              method="post" rel="pay" href="http://rest-demo.local/orders/9/pay"/>
             <line>
              <product>http://rest-demo.local/products/1</product>
              <quantity>2</quantity>
              <cost>9.90</cost>
             </line>
             <total>9.90</total>
            </order>



Note links to cancel or pay for the order – HATEOAS! The links included would depend on the
allowable state transitions (eg no cancel link for a despatched order).
Clients only need know

• The root URI (‘home page’) of the API
• Definitions for the media types used
 - eg schemas or example documents
• Everything else is just HTTP and links
✓Makes full use of HTTP
           ✓Self-describing
           ✓Loosely coupled


Only need to know entry URI and media types – API can be explored using links. If link URIs
change, well-behaved clients should not break.
✗ More complex to implement
          ✗ Transition links can lead back to RPC-style



Frameworks help. Tempting to just add a bunch of actions as links, using overloaded post.
But is it REST?
✓ Identification of resources
✓ Manipulation of resources through these
   representations
✓ Self-descriptive messages
✓ Hypermedia as the engine of application
   state
This is not the One
                    True Way


As mentioned before, REST is just an architectural style. There are other approaches to
creating RESTful APIs.
An alternative:
‘Web site is your API’
• No separation between web site and API
• Representations are HTML
• Data submitted using HTML forms
• Semantics via microformats
Using HTTP features
Response codes
•   200 OK                  •   400 Bad request

•   201 Created             •   403 Forbidden

•   202 Accepted            •   404 Not found

•   204 No content          •   405 Method not allowed

•   301 Moved permanently   •   409 Conflict

                            •   410 Gone

                            •   etc
Restricting transitions
      Request                 Response


OPTIONS /orders/123             200 OK
   (an open order)      Allow: GET, PUT, DELETE

OPTIONS /orders/42             200 OK
 (a despatched order)         Allow: GET
Restricting transitions
      Request                Response


DELETE /orders/123
                           100 Continue
Expect: 100-Continue

 DELETE /orders/42
                       417 Expectation Failed
Expect: 100-Continue
Prevent race conditions
 Request
 PUT /orders/123
 If-Unmodified-Since: Tue, 9 Mar 2010 11:00:00 GMT
 Response
 200 OK
 or
 412 Precondition Failed
Prevent race conditions
 Request
 GET /orders/123
 Response (partial)
 200 OK
 ETag: 686897696a7c876b7e
 Request
 PUT /orders/123
 If-Match: 686897696a7c876b7e
Security

• HTTP basic
• HTTP digest
• Shared secret (OAuth etc)
• SSL
• Selective encryption
More

• Jim Webber tutorial
      http://tinyurl.com/rest-tutorial
• Restfulie framework (Rails & Java):
      http://tinyurl.com/restfulie

More Related Content

What's hot

AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터
AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터
AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터Amazon Web Services Korea
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding RESTNitin Pande
 
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017AWSKRUG - AWS한국사용자모임
 
RESTful services
RESTful servicesRESTful services
RESTful servicesgouthamrv
 
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개if kakao
 
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018Amazon Web Services Korea
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensJonathan LeBlanc
 
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021AWSKRUG - AWS한국사용자모임
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesVMware Tanzu
 
효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...
효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...
효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...Amazon Web Services Korea
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaEdureka!
 
AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017
AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017
AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017AWSKRUG - AWS한국사용자모임
 
쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료Opennaru, inc.
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSunghyouk Bae
 
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐Terry Cho
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web ServicesAngelin R
 

What's hot (20)

AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터
AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터
AWS Builders - Industry Edition: DevSecOps on AWS - 시작은 IAM 부터
 
Domain Driven Design
Domain Driven Design Domain Driven Design
Domain Driven Design
 
Understanding REST
Understanding RESTUnderstanding REST
Understanding REST
 
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
AWS 기반 대규모 트래픽 견디기 - 장준엽 (구로디지털 모임) :: AWS Community Day 2017
 
RESTful services
RESTful servicesRESTful services
RESTful services
 
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
카카오 광고 플랫폼 MSA 적용 사례 및 API Gateway와 인증 구현에 대한 소개
 
React hooks
React hooksReact hooks
React hooks
 
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
Amazon EKS 그리고 Service Mesh (김세호 솔루션즈 아키텍트, AWS) :: Gaming on AWS 2018
 
REST API
REST APIREST API
REST API
 
Modern API Security with JSON Web Tokens
Modern API Security with JSON Web TokensModern API Security with JSON Web Tokens
Modern API Security with JSON Web Tokens
 
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
Amazon EKS로 간단한 웹 애플리케이션 구축하기 - 김주영 (AWS) :: AWS Community Day Online 2021
 
Architecture: Microservices
Architecture: MicroservicesArchitecture: Microservices
Architecture: Microservices
 
Spring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutesSpring Data JPA from 0-100 in 60 minutes
Spring Data JPA from 0-100 in 60 minutes
 
효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...
효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...
효과적인 NoSQL (Elasticahe / DynamoDB) 디자인 및 활용 방안 (최유정 & 최홍식, AWS 솔루션즈 아키텍트) :: ...
 
What is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | EdurekaWhat is REST API? REST API Concepts and Examples | Edureka
What is REST API? REST API Concepts and Examples | Edureka
 
AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017
AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017
AWS 기반 5천만 모바일 앱서비스 확장하기 - 이영진 (강남SE 모임) :: AWS Community Day 2017
 
쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료쿠버네티스 ( Kubernetes ) 소개 자료
쿠버네티스 ( Kubernetes ) 소개 자료
 
SpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSLSpringBoot with MyBatis, Flyway, QueryDSL
SpringBoot with MyBatis, Flyway, QueryDSL
 
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
대용량 분산 아키텍쳐 설계 #4. soa 아키텍쳐
 
Restful Web Services
Restful Web ServicesRestful Web Services
Restful Web Services
 

Similar to Doing REST Right

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
 
distributing over the web
distributing over the webdistributing over the web
distributing over the webNicola Baldi
 
Restful webservice
Restful webserviceRestful webservice
Restful webserviceDong Ngoc
 
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 ServicesAnuchit Chalothorn
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiTiago Knoch
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座Li Yi
 
JAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with JavaJAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with JavaJerry Kurian
 
OpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML ResourcesOpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML ResourcesOpenTravel Alliance
 
Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...Woodruff Solutions LLC
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011Shreedhar Ganapathy
 
RESTful for opentravel.org by HP
RESTful for opentravel.org by HPRESTful for opentravel.org by HP
RESTful for opentravel.org by HPRoni Schuetz
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Mario Cardinal
 

Similar to Doing REST Right (20)

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
 
distributing over the web
distributing over the webdistributing over the web
distributing over the web
 
Restful webservice
Restful webserviceRestful webservice
Restful webservice
 
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
 
Woa. Reloaded
Woa. ReloadedWoa. Reloaded
Woa. Reloaded
 
ReST
ReSTReST
ReST
 
ASP.NET Mvc 4 web api
ASP.NET Mvc 4 web apiASP.NET Mvc 4 web api
ASP.NET Mvc 4 web api
 
RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座RESTful SOA - 中科院暑期讲座
RESTful SOA - 中科院暑期讲座
 
APITalkMeetupSharable
APITalkMeetupSharableAPITalkMeetupSharable
APITalkMeetupSharable
 
RESTful Web Services
RESTful Web ServicesRESTful Web Services
RESTful Web Services
 
JAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with JavaJAX-RS. Developing RESTful APIs with Java
JAX-RS. Developing RESTful APIs with Java
 
OpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML ResourcesOpenTravel Advisory Forum 2012 REST XML Resources
OpenTravel Advisory Forum 2012 REST XML Resources
 
Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...Learning How to Shape and Configure an OData Service for High Performing Web ...
Learning How to Shape and Configure an OData Service for High Performing Web ...
 
Web Scraping with PHP
Web Scraping with PHPWeb Scraping with PHP
Web Scraping with PHP
 
JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011JAX-RS JavaOne Hyderabad, India 2011
JAX-RS JavaOne Hyderabad, India 2011
 
RESTful for opentravel.org by HP
RESTful for opentravel.org by HPRESTful for opentravel.org by HP
RESTful for opentravel.org by HP
 
Ws rest
Ws restWs rest
Ws rest
 
Overview of java web services
Overview of java web servicesOverview of java web services
Overview of java web services
 
Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.Best Practices for Architecting a Pragmatic Web API.
Best Practices for Architecting a Pragmatic Web API.
 

More from Kerry Buckley

Testing http calls with Webmock and VCR
Testing http calls with Webmock and VCRTesting http calls with Webmock and VCR
Testing http calls with Webmock and VCRKerry Buckley
 
Ruby nooks & crannies
Ruby nooks & cranniesRuby nooks & crannies
Ruby nooks & cranniesKerry Buckley
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworksKerry Buckley
 
Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test communityKerry Buckley
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)Kerry Buckley
 
Adastral Park code retreat introduction
Adastral Park code retreat introductionAdastral Park code retreat introduction
Adastral Park code retreat introductionKerry Buckley
 
MongoMapper lightning talk
MongoMapper lightning talkMongoMapper lightning talk
MongoMapper lightning talkKerry Buckley
 
The secret life of bees
The secret life of beesThe secret life of bees
The secret life of beesKerry Buckley
 
Background processing
Background processingBackground processing
Background processingKerry Buckley
 
Katas, Contests and Coding Dojos
Katas, Contests and Coding DojosKatas, Contests and Coding Dojos
Katas, Contests and Coding DojosKerry Buckley
 
Kanban and Iterationless Working
Kanban and Iterationless WorkingKanban and Iterationless Working
Kanban and Iterationless WorkingKerry Buckley
 
Software Development Trends
Software Development TrendsSoftware Development Trends
Software Development TrendsKerry Buckley
 

More from Kerry Buckley (20)

Jasmine
JasmineJasmine
Jasmine
 
Testing http calls with Webmock and VCR
Testing http calls with Webmock and VCRTesting http calls with Webmock and VCR
Testing http calls with Webmock and VCR
 
BDD with cucumber
BDD with cucumberBDD with cucumber
BDD with cucumber
 
Ruby nooks & crannies
Ruby nooks & cranniesRuby nooks & crannies
Ruby nooks & crannies
 
TDD refresher
TDD refresherTDD refresher
TDD refresher
 
Javasccript MV* frameworks
Javasccript MV* frameworksJavasccript MV* frameworks
Javasccript MV* frameworks
 
Tdd for BT E2E test community
Tdd for BT E2E test communityTdd for BT E2E test community
Tdd for BT E2E test community
 
7li7w devcon5
7li7w devcon57li7w devcon5
7li7w devcon5
 
What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)What I learned from Seven Languages in Seven Weeks (IPRUG)
What I learned from Seven Languages in Seven Weeks (IPRUG)
 
Functional ruby
Functional rubyFunctional ruby
Functional ruby
 
Adastral Park code retreat introduction
Adastral Park code retreat introductionAdastral Park code retreat introduction
Adastral Park code retreat introduction
 
MongoMapper lightning talk
MongoMapper lightning talkMongoMapper lightning talk
MongoMapper lightning talk
 
Ruby
RubyRuby
Ruby
 
Cloud
CloudCloud
Cloud
 
The secret life of bees
The secret life of beesThe secret life of bees
The secret life of bees
 
Background processing
Background processingBackground processing
Background processing
 
Katas, Contests and Coding Dojos
Katas, Contests and Coding DojosKatas, Contests and Coding Dojos
Katas, Contests and Coding Dojos
 
Rack
RackRack
Rack
 
Kanban and Iterationless Working
Kanban and Iterationless WorkingKanban and Iterationless Working
Kanban and Iterationless Working
 
Software Development Trends
Software Development TrendsSoftware Development Trends
Software Development Trends
 

Recently uploaded

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditSkynet Technologies
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 

Recently uploaded (20)

Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Manual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance AuditManual 508 Accessibility Compliance Audit
Manual 508 Accessibility Compliance Audit
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyesAssure Ecommerce and Retail Operations Uptime with ThousandEyes
Assure Ecommerce and Retail Operations Uptime with ThousandEyes
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 

Doing REST Right

  • 1. How to do RESTful web services right Kerry Buckley & Paul Moser BT DevCon2 9 March 2010
  • 2. w ay ne O How to do RESTful web services right
  • 3. w ay ne O How to do RESTful web services right (for some value of ‘right’)
  • 4. What is REST? REST is an architectural style, not a protocol or a standard. Hence many values of “right” (and much disagreement).
  • 5. ‘A style of software architecture for distributed hypermedia systems such as the World Wide Web’ Not necessarily HTTP, although in practice it generally is.
  • 6. Not SOAP Seems to be a common (but wrong) definition.
  • 8. • Client-server • Stateless • Cacheable • Layered system • Uniform interface
  • 10. • Identification of resources • Manipulation of resources through these representations • Self-descriptive messages • Hypermedia as the engine of application state
  • 11. Goals
  • 12. • Scalability of component interactions • Generality of interfaces • Independent deployment of components • Intermediary components to reduce latency, enforce security and encapsulate legacy systems
  • 14. • List products • View a product • Create an order for a number of products • Cancel order • Pay for order
  • 16. GET /api?action=list_products GET /api?action=view_product&product_id=123 GET /api?action=create_order&product_id=123&product_id=456… GET/api?action=pay_order&order_id=42&card_number=1234… Sometimes only a single ‘endpoint’ URI
  • 17. GET /list_products GET /view_product?product_id=123 GET /create_order?product_id=123&product_id=456… GET/pay_order?order_id=42&card_number=1234… Or one endpoint per method
  • 18. GET /list_products GET /view_product?product_id=123 POST /create_order?product_id=123&product_id=456… POST /pay_order?order_id=42&card_number=1234… Marginally better without unsafe GETs
  • 19. POST /pay_order?order_id=42&card_number=1234… def pay_order(order_id, card_number) { … } Request maps onto method call.
  • 20. ✓Easy to understand ✓Works well for simple procedure calls ✓Simple to implement ✓Interoperable
  • 21. ✗ Brittle ✗ Tightly coupled ✗ Failure cases require manual handling ✗ No metadata Need to know all the URIs, methods and parameters in advance (out-of-band documentation)
  • 22. But is it REST? ✗ Identification of resources ✗ Manipulation of resources through these representations ✗ Self-descriptive messages ✗ Hypermedia as the engine of application state
  • 24. Request POST /create_order <create_order_request> <line> <product_id>123</product_line> <quantity>1</quantity> </line> … </create_order_request> Response 200 OK <create_order_response> <status>OK</status> <order_id>42</order_id> </create_order_response> Both request and response have XML bodies.
  • 26. ✗ Tightly coupled ✗ No metadata ✗ Doesn’t use web for robustness ✗ Doesn’t use SOAP for robustness either
  • 27. But is it REST? ✗ Identification of resources ✗ Manipulation of resources through these representations ✗ Self-descriptive messages ✗ Hypermedia as the engine of application state
  • 28. CRUD
  • 29. GET /products GET /products/123 POST /orders PUT /orders/42 DELETE /orders/42 POST /orders/42/payment
  • 30. Representations • Hypermedia • Non-hypermedia - XHTML - Generic XML - Atom - YAML - Custom XML schema - JSON - CSV - etc
  • 31. ✓Makes good use of HTTP ✓Uniform interface ✓Good for database-style applications Because each resource has a URI you can use caching etc. Uniform interface: verbs are GET, POST, PUT and DELETE.
  • 32. ✗ Ignores hypermedia ✗ Tight coupling through URI templates ✗ Not self-describing
  • 33. But is it REST? ✓ Identification of resources ✓ Manipulation of resources through these representations ✗ Self-descriptive messages ✗ Hypermedia as the engine of application state
  • 34. REST
  • 36. API root Response 200 OK Content-Type: application/vnd.rest-example.store+xml <store> <link method="get" rel="products" href="http://rest-demo.local/products"/> <link method="get" rel="orders" href="http://rest-demo.local/orders"/> </store> Links contain information on what we can do.
  • 37. View products Request Get /products Following the link with a relation of ‘products’ (link rel="products").
  • 38. View products Response 200 OK Content-Type: application/vnd.rest-example.products+xml <products> <link method="get" rel="latest" href="http://rest-demo.local/products"/> <product> <link method="get" rel="view" href="http://rest-demo.local/products/1"/> <code>A-001</code> <description>Tartan Paint</description> <price>4.95</price> </product> … </products> Note link to retrieve the latest version of this resource (eg if you had it cached).
  • 40. View orders Response 200 OK Content-Type: application/vnd.rest-example.orders+xml <orders> <link method="get" rel="latest" href="http://rest-demo.local/orders"/> <link type="application/vnd.rest-example.order+xml" method="post" rel="new" href="http://rest-demo.local/orders"/> </orders> No orders yet, but note link to create a new one.
  • 41. Place order Request POST /orders Content-Type: application/vnd.rest-example.order+xml <order> <line> <product>http://rest-demo.local/products/1</product> <quantity>2</quantity> </line> </order> Again following a link, this time posting data of the specified type.
  • 42. Place order Response 201 Created Content-Type: application/vnd.rest-example.order+xml <order> <link method="get" rel="latest" href="http://rest-demo.local/orders/9"/> <link method="delete" rel="cancel" href="http://rest-demo.local/orders/9"/> <link type="application/vnd.rest-example.payment-details+xml" method="post" rel="pay" href="http://rest-demo.local/orders/9/pay"/> <line> <product>http://rest-demo.local/products/1</product> <quantity>2</quantity> <cost>9.90</cost> </line> <total>9.90</total> </order> Note links to cancel or pay for the order – HATEOAS! The links included would depend on the allowable state transitions (eg no cancel link for a despatched order).
  • 43. Clients only need know • The root URI (‘home page’) of the API • Definitions for the media types used - eg schemas or example documents • Everything else is just HTTP and links
  • 44. ✓Makes full use of HTTP ✓Self-describing ✓Loosely coupled Only need to know entry URI and media types – API can be explored using links. If link URIs change, well-behaved clients should not break.
  • 45. ✗ More complex to implement ✗ Transition links can lead back to RPC-style Frameworks help. Tempting to just add a bunch of actions as links, using overloaded post.
  • 46. But is it REST? ✓ Identification of resources ✓ Manipulation of resources through these representations ✓ Self-descriptive messages ✓ Hypermedia as the engine of application state
  • 47. This is not the One True Way As mentioned before, REST is just an architectural style. There are other approaches to creating RESTful APIs.
  • 48. An alternative: ‘Web site is your API’ • No separation between web site and API • Representations are HTML • Data submitted using HTML forms • Semantics via microformats
  • 50. Response codes • 200 OK • 400 Bad request • 201 Created • 403 Forbidden • 202 Accepted • 404 Not found • 204 No content • 405 Method not allowed • 301 Moved permanently • 409 Conflict • 410 Gone • etc
  • 51. Restricting transitions Request Response OPTIONS /orders/123 200 OK (an open order) Allow: GET, PUT, DELETE OPTIONS /orders/42 200 OK (a despatched order) Allow: GET
  • 52. Restricting transitions Request Response DELETE /orders/123 100 Continue Expect: 100-Continue DELETE /orders/42 417 Expectation Failed Expect: 100-Continue
  • 53. Prevent race conditions Request PUT /orders/123 If-Unmodified-Since: Tue, 9 Mar 2010 11:00:00 GMT Response 200 OK or 412 Precondition Failed
  • 54. Prevent race conditions Request GET /orders/123 Response (partial) 200 OK ETag: 686897696a7c876b7e Request PUT /orders/123 If-Match: 686897696a7c876b7e
  • 55. Security • HTTP basic • HTTP digest • Shared secret (OAuth etc) • SSL • Selective encryption
  • 56. More • Jim Webber tutorial http://tinyurl.com/rest-tutorial • Restfulie framework (Rails & Java): http://tinyurl.com/restfulie