1 of 39

REST�RESTful Web Services

Jakub Klímek, Martin Nečaský

2 of 39

What is REST?

  • REST = REpresentational State Transfer
    • Roy Fielding dissertation, 2000
  • software architectural style for building distributed hypermedia (hypertext) systems
  • set of following architectural principles
    • resource orientation
    • unique resource identification
    • stateless client/server interaction
    • uniform interface
  • e.g. Web architecture is based on the same principles as REST
    • but REST principles were derived from the architecture of the Web

2

A truly RESTful API looks like hypertext.

3 of 39

Principle 1: Resource Orientation

  • resource = concrete or abstract thing/action we want to publish
    • everything is resource in REST
  • resource representation ~ state of the resource
    • document that can be sent between communicating peers
    • representation format needs to be established
      • different (meta-)formats may be used
        • HTML, XML, JSON, RDF, AtomPub, …
      • each resource can have more representations, in different formats
      • data formats == media types
    • representation contains links to related resources
      • representation format must support links
      • applications which consume resources navigate instead of calling
      • navigation = transition to next state

3

Most commonly forgotten

4 of 39

Principle 2: Unique Resource Identification

  • each resource has unique ID (name)
    • universal syntax for resource IDs is necessary, e.g. URI
    • ID serves not just as a name but also as a means of accessing resource representation, URL
    • parametrized IDs�http://www.company.org/customer?name=John
  • need to distinguish resource ID from resource representation ID�e.g. HTML, XML, JSON, RDF documents
    • if resource = document then resource ID = resource representation ID
    • otherwise we need strategy to allow clients to request specific resource representation

4

5 of 39

Principle 3: Stateless Client/Server Communication

  • request/response message exchange pattern
  • separation of concerns principle
    • clients separated from servers by interface
    • clients are not concerned with data storage and (most) application logic
    • servers are not concerned with user interface or state
      • server simplicity and scalability
    • independent evolution of clients and server

5

6 of 39

Principle 3: Stateless Client/Server Communication

  • stateless communication
    • no state in server-side applications
    • state in clients and/or resources
  • resource state is the same for every client
    • client changes to resource state affect all other clients
  • client state is specific for each particular client
    • communication state
  • cacheable responses
    • reponses labeled as cacheable and non-cacheable

6

7 of 39

Principle 4: Resource Manipulation

  • uniform interface for resource manipulation
    • small set of operations which apply for everything
      • e.g. CRUD operations (Create, Retrieve, Update, Delete)
    • small set of verbs which apply to large set of nouns
      • if many applications need new verb, uniform interface can be extended
  • do not encode verbs into resource identifiers

http://www.company.org/addCustomer?name=John

7

8 of 39

REST != HTTP

  • REST specification does not include implementation directives
    • It does not say to use HTTP
  • Any implementation honoring the principles is RESTful
    • Everything is a resource, identified and accessed using URI
    • Simple, well-defined operations on resources (CRUD)
    • Client and server exchange representations of resources using standardized interface and protocol
    • Resources decoupled from their representation
      • to allow clients accessing it in variety of formats = media types
    • Every interaction is stateless

8

9 of 39

REST using HTTP: Resource ID - direct dereferencing

  • direct dereferencing
    • resource ID is not dereferencable
    • client has to know particular resource representation IDs
  • e.g.

9

https://api.twitter.com/1.1/statuses/user_timeline.json

https://api.twitter.com/1.1/statuses/user_timeline.xml

10 of 39

REST using HTTP: Resource ID - content negotiation

dereferencing using HTTP 303 See Other response code

  • resource ID is dereferencable
  • two requests
    1. client requests resource ID and specified preferred resource representation format
      • server sends resource representation ID in 303 response
    2. client requests resource representation ID

10

11 of 39

REST using HTTP: Resource ID

11

Server

client

GET /customer?name=John

Host: www.company.org

Accept: text/xml

Server

client

HTTP/1.1 303 See Other

Location: http://www.company.org/customer.xml?name=John

Server

client

GET /customer.xml?name=John

Host: www.company.org

Accept: text/xml

12 of 39

REST using HTTP: Resource ID

  • how to set-up 303 URIs?
  • e.g. Apache HTTPD (.htaccess file)

12

RewriteCond %{HTTP_ACCEPT} application/rdf\+xml

RewriteRule ^customer customer.rdf [R=303]

http://www.company.org/

customer?name=John

http://www.company.org/

customer.rdf?name=John

13 of 39

REST using HTTP: Resource ID - Clean URLs

  • avoid parameterized resource ID
  • i.e. use

http://www.company.org/customer/John

  • instead of

http://www.company.org/customer?name=John

13

RewriteCond %{HTTP_ACCEPT} application/rdf\+xml

RewriteRule ^customer/([a-zA-Z]+)$ customer.rdf?name=$1

14 of 39

REST using HTTP: HTTP Verbs

when HTTP is used, the following four operations are usually considered:

  • GET = requests representation of the specified resource
    • read-only operation, should be safe = should not cause any side-effects
  • PUT = uploads representation of the specified resource
    • write operation, should be idempotent
    • being idempotent means being simple = identical request causes the same state change independently of how many times it has been called
  • DELETE = deletes the specified resource
    • write operation, should be idempotent
  • POST = submits data to be processed to the specified resource
    • it can update the resource
    • generally not safe and not idempotent

14

15 of 39

Richardson Maturity Model - RMM

15

Hypermedia

HTTP

URI

16 of 39

Richardson Maturity Model - RMM

16

17 of 39

Richardson Maturity Model - RMM

17

18 of 39

RMM - Level 0 WS

  • Single URI - like WS-* endpoint
  • Single verb - like WS-* POST to send SOAP
  • e.g. XML-RPC
    • Plain Old XML (POX)
    • 1 URI
    • 1 verb - POST
  • Use HTTP as a tunneling �mechanism (like RPC)

18

19 of 39

RMM - Level 0 WS - example - 1/3

See free slots to see a doctor

19

POST /appointmentService HTTP/1.1

[various other headers]

<openSlotRequest date="2010-01-04" doctor="mjones"/>

HTTP/1.1 200 OK

[various headers]

<openSlotList>

<slot start="1400" end="1450">

<doctor id="mjones"/>

</slot>

<slot start="1600" end="1650">

<doctor id="mjones"/>

</slot>

</openSlotList>

20 of 39

RMM - Level 0 WS - example - 2/3

Book the appointment - success

20

POST /appointmentService HTTP/1.1

[various other headers]

<appointmentRequest>

<slot doctor="mjones" start="1400" end="1450"/>

<patient id="jsmith"/>

</appointmentRequest>

HTTP/1.1 200 OK

[various headers]

<appointment>

<slot doctor="mjones" start="1400" end="1450"/>

<patient id="jsmith"/>

</appointment>

21 of 39

RMM - Level 0 WS - example - 3/3

Book the appointment - failure

21

POST /appointmentService HTTP/1.1

[various other headers]

<appointmentRequest>

<slot doctor="mjones" start="1400" end="1450"/>

<patient id="jsmith"/>

</appointmentRequest>

HTTP/1.1 200 OK

[various headers]

<appointmentRequestFailure>

<slot doctor="mjones" start="1400" end="1450"/>

<patient id="jsmith"/>

<reason>Slot not available</reason>

</appointmentRequestFailure>

22 of 39

RMM - Level 1 WS

  • Makes use of URIs
    • Each resource has a URI
  • Single verb
    • like W3C-style WS-* POST to send SOAP

22

23 of 39

RMM - Level 1 WS - example - 1/2

See free slots to see a doctor

23

POST /doctors/mjones HTTP/1.1

[various other headers]

<openSlotRequest date = "2010-01-04"/>

HTTP/1.1 200 OK

[various headers]

<openSlotList>

<slot id="1234" doctor="mjones" start="1400" end="1450"/>

<slot id="5678" doctor="mjones" start="1600" end="1650"/>

</openSlotList>

24 of 39

RMM - Level 1 WS - example - 2/2

Book the appointment

24

POST /slots/1234 HTTP/1.1

[various other headers]

<appointmentRequest>

<patient id="jsmith"/>

</appointmentRequest>

HTTP/1.1 200 OK

[various headers]

<appointment>

<slot id="1234" doctor="mjones" start="1400" end="1450"/>

<patient id="jsmith"/>

</appointment>

25 of 39

RMM - Level 2 WS

  • Makes use of URIs
    • Each resource has a URI
  • HTTP verbs used for CRUD
    • Create
    • Read
    • Update
    • Delete

25

26 of 39

RMM - Level 2 WS - example - 1/3

See free slots to see a doctor

26

GET /doctors/mjones/slots?date=20100104&status=open HTTP/1.1

Host: royalhope.nhs.uk

HTTP/1.1 200 OK

[various headers]

<openSlotList>

<slot id="1234" doctor="mjones" start="1400" end="1450"/>

<slot id="5678" doctor="mjones" start="1600" end="1650"/>

</openSlotList>

27 of 39

RMM - Level 2 WS - example - 2/3

Book the appointment - success

27

POST /slots/1234 HTTP/1.1

[various other headers]

<appointmentRequest>

<patient id="jsmith"/>

</appointmentRequest>

HTTP/1.1 201 Created

Location: slots/1234/appointment

[various headers]

<appointment>

<slot id="1234" doctor="mjones" start="1400" end="1450"/>

<patient id="jsmith"/>

</appointment>

http://royalhope.nhs.uk/slots/1234/appointment

28 of 39

RMM - Level 2 WS - example - 3/3

Book the appointment - failure

28

POST /slots/1234 HTTP/1.1

[various other headers]

<appointmentRequest>

<patient id="jsmith"/>

</appointmentRequest>

HTTP/1.1 409 Conflict

[various headers]

<openSlotList>

<slot id="5678" doctor="mjones" start="1600" end="1650"/>

</openSlotList>

29 of 39

RMM - Level 3 WS

  • Makes use of URIs
  • HTTP verbs used for CRUD
  • HATEOAS
    • Hypertext As The Engine Of Application State
    • Hypermedia controls

29

Some people pronounce it as "hate-ee-os," similar to "hideous," or as "hate O-A-S".

People also refer to it as a hypermedia-driven system.

30 of 39

RMM - Level 3 WS - example - 1/2

See free slots to see a doctor

30

GET /doctors/mjones/slots?date=20100104&status=open HTTP/1.1

Host: royalhope.nhs.uk

HTTP/1.1 200 OK

[various headers]

<openSlotList>

<slot id="1234" doctor="mjones" start="1400" end="1450">

<link rel= "/linkrels/slot/book"

type="POST"

href="/slots/1234"/>

</slot>

<slot id="5678" doctor="mjones" start="1600" end="1650">

<link rel= "/linkrels/slot/book"

type="POST"

href="/slots/5678"/>

</slot>

</openSlotList>

31 of 39

RMM - Level 3 WS - example - 2/2

Book the appointment

31

POST /slots/1234 HTTP/1.1

[various other headers]

<appointmentRequest>

<patient id="jsmith"/>

</appointmentRequest>

HTTP/1.1 201 Created

Location: http://royalhope.nhs.uk/slots/1234/appointment

[various headers]

<appointment>

<slot id="1234" doctor="mjones" start="1400" end="1450"/>

<patient id="jsmith"/>

<link rel="/linkrels/appointment/cancel"

href="/slots/1234/appointment"/>

<link rel= "/linkrels/appointment/addTest"

href="/slots/1234/appointment/tests"/>

</appointment>

32 of 39

REST API

  • Must be hypertext driven
  • 3rd level RMM is only a prerequisite for REST
    • Any URI has to be usable for resource identification
    • No fixed URI patterns
    • REST API cannot change communication protocols
    • For resource representation, REST API should
      • define media type(s)
      • define extended relation names
      • define extended markup for existing standard media types
  • RESTful API should be usable with only
    • initial URI
    • set of standardized media types

32

33 of 39

RESTful Web Services

  • RESTful Web Service
    • enables manipulation with set of resources
    • typically uses XML, JSON or RDF for resource representation
    • uses URLs as resource identifiers
    • stateless
    • HTTP methods GET/PUT/DELETE/POST for resource manipulation
  • like Web application but for machines instead of humans

33

34 of 39

RESTful Web Services: typical HTTP verb meanings

34

Operation

Resource representing collection of individuals

Resource representing individual

GET

List members in collection

  • e.g. weekly list of public contracts

Retrieve individual

  • e.g. retrieve public contract

PUT

Update collection with another one

  • e.g. replace weekly list of public contracts at the beginning of new week

Update individual

  • e.g. update public contract representation with new representation

DELETE

Delete entire collection

  • e.g. delete weekly list of public contracts

Delete individual

  • e.g. delete public contract

POST

Create member of collection with auto-ID

  • e.g. add new public contract to the collection and generate its ID

Create part of individual

  • e.g. create public contract tender

35 of 39

REST vs. SOAP - The letter analogy

  • mailing a letter with SOAP (W3C-style WS)
    • you're using an envelope
  • with REST
    • it's a postcard
    • postcards are easier to handle
      • by the receiver
    • waste less paper
      • i.e., consume less bandwidth
    • have a short content
      • of course, REST requests aren't really limited in length
      • esp. if they use POST rather than GET

35

36 of 39

REST vs. SOAP

SOAP and REST – both provide support for building SOA based applications

36

Dimension

REST

SOAP (W3C-style WS)

Underlying Protocol

REST is an architecture style

  • Almost synonymous to HTTP
  • Not enforced by specification

SOAP itself is a protocol

  • Mainly over HTTP
  • But also over SMTP, …

Data Format

Any format: JSON, CSV, RSS, XML, …

XML

Statefulness

Stateless

Stateless

Caching

Using infrastructure already in place

  • Uses caching related HTTP headers for GET, PUT, DELETE
  • ETags

HTTP Verbs

GET, POST, PUT, DELETE, PATCH

POST

Security

TLS (HTTPS) (point to point)

WS-Security (end to end)

Asynchronous Processing

HTTP 202 Accepted response�+ Location of queue

WS-Reliable Messaging

37 of 39

WADL

  • Web Application Description Language
    • W3C Member Submission, 2009
  • XML-based description of HTTP-based web applications

37

38 of 39

WADL - example

38

<application xmlns="http://wadl.dev.java.net/2009/02">� <resources base="http://example.com/api">� <resource path="books">� <method name="GET"/>� <resource path="{bookId}">� <param required="true" style="template" name="bookId"/>� <method name="GET"/>� <method name="DELETE"/>� <resource path="reviews">� <method name="GET">� <request>� <param name="page" required="false" default="1" style="query"/>� <param name="size" required="false" default="20" style="query"/>� </request>� <response status="200"> <representation mediaType="application/xml"/> <representation mediaType="application/json"/> </response>� </method>� </resource>� </resource>� </resource>� <resource path="readers">� <method name="GET"/>� </resource>� </resources>�</application>

@base - base URI for child resource identifiers

@path - relative URI template

methods available on the resource

response types

query parameters

39 of 39

WADL - parameter styles

<resource path="reviews">� <method name="GET">� <request>� <param name="page" required="false" default="1" style="query"/>� <param name="size" required="false" default="20" style="query"/>� </request>� </method>�</resource>

39

  • query - go into request URI after "?"

http://example.com/api/books/1234/reviews?page=1&size=20

  • header - go into HTTP header
  • template - go in resource paths

{bookID}

  • matrix - go into request URI before query, separated by ";"

http://example.com/api/books/1234/reviews;page=1;size=20