RESTful Web Services
Michał Wojciechowski
May 30, 2015
Slide 2
Slide 2 text
What REST Means
REpresentational
State
Transfer
Slide 3
Slide 3 text
What REST Means
REpresentational
State
Transfer
We are transferring a representation of the
current state of a resource/application
Slide 4
Slide 4 text
REST and HTTP
● REST was developed in parallel with
HTTP 1.1
● Can be used with other transfer protocols
● In practice, used almost exclusively with
HTTP web APIs
● RESTful APIs use HTTP to the fullest:
methods, headers, error codes, hypermedia
Architectural Constraints
Client-server
● Separation of concerns
● Servers store data
● Clients provide user interface
● Uniform interface between servers and
clients
Slide 7
Slide 7 text
Architectural Constraints
Stateless
● Each request is processed independently
● No client context is stored on the server
● The client is responsible for keeping
application state
Slide 8
Slide 8 text
Architectural Constraints
Stateful design:
Client Server
GET /next-page
Result 1, 2, 3, ...
$page = 1
Client Server
GET /next-page
Result 4, 5, 6, ...
$page = $page + 1
Slide 9
Slide 9 text
Architectural Constraints
Stateless design:
Client Server
GET /results/?page=1
Result 1, 2, 3, ...
$page = UrlParam('page')
Client Server
$page = UrlParam('page')
GET /results/?page=2
Result 4, 5, 6, ...
Slide 10
Slide 10 text
Architectural Constraints
Cacheable
● Clients or intermediary servers may cache
responses
● Resources must be labeled as cacheable or
non-cacheable (explicitly or implicitly)
Slide 11
Slide 11 text
Architectural Constraints
Layered system
● The client only “sees” the immediate layer
with which they are communicating
● Intermediary servers can be added to
provide load balancing or caching
Slide 12
Slide 12 text
Architectural Constraints
Uniform interface
● Identification/addressability of resources
● Manipulation of resources through
representations
● Self-descriptive messages
Slide 13
Slide 13 text
Architectural Constraints
● Stateless
● Cacheable
● Layered system
Slide 14
Slide 14 text
Architectural Constraints
● Stateless
● Cacheable
● Layered system
Scalability
It's fairly easy to just “throw more servers at it”
Slide 15
Slide 15 text
Resources
● Objects of specific type
● With data, relationships to other resources,
and defined operations
● Similar in principle to object instances in
object-oriented programming
● Must be uniquely identifiable (to be
addressable)
Slide 16
Slide 16 text
Resources
Addressability through the use of URIs:
● Single resource
e.g.: /invoices/2015-05-123
● Collections of resources
e.g.: /invoices/
Slide 17
Slide 17 text
Resource Representations
● Conceptually separate from the resources
themselves
● The same resource may be represented in a
number of ways (e.g.: XML, JSON)
● The client can request the desired
representation format (e.g., using the Accept
HTTP header)
Slide 18
Slide 18 text
Resource Representations
Accept:
text/xml
XML representation:
Accept:
application/json
JSON representation:
Bob
25
{
name: “Bob”,
age: 25
}
Slide 19
Slide 19 text
HTTP Methods
● POST
Create a new resource
● GET
Retrieve a resource
● PUT
Create or replace a resource
● DELETE
Remove a resource
Slide 20
Slide 20 text
HTTP Methods
● POST Create
Create a new resource
● GET Read
Retrieve a resource
● PUT Update
Create or replace a resource
● DELETE Delete
Remove a resource
Slide 21
Slide 21 text
HTTP Methods
● PATCH
Partially replace a resource (partial PUT)
● HEAD
Retrieve response headers (GET sans body)
● OPTIONS
Determine the options associated with a
resource (“what we can do”)
Slide 22
Slide 22 text
HTTP Methods
● Idempotent
Produces the same result, no matter how
many times it is repeated.
● Nullipotent (a.k.a. safe)
Does not modify any resources (has no side-
effects).
Slide 23
Slide 23 text
HTTP Methods
● GET
Retrieve a resource – nullipotent
● POST
Create a new resource
● PUT
Create or replace a resource – idempotent
● DELETE
Remove a resource – idempotent
Slide 24
Slide 24 text
HTTP Methods
● PATCH
Partially replace a resource – can be
idempotent
● HEAD, OPTIONS – obviously nullipotent
Slide 25
Slide 25 text
HTTP Methods – Examples
●
GET /invoices/2015-05-123
Retrieve the invoice numbered “2015-05-123”
●
PUT /invoices/2015-05-124
Create (or replace) invoice no. “2015-05-124”
●
DELETE /invoices/2015-05-124
Delete invoice no. “2015-05-124”
Slide 26
Slide 26 text
HTTP Methods – Examples
●
GET /invoices/2015-05-123
Retrieve the invoice numbered “2015-05-123”
●
PUT /invoices/2015-05-124
Create (or replace) invoice no. “2015-05-124”
●
DELETE /invoices/2015-05-124
Delete invoice no. “2015-05-124”
● POST?
Slide 27
Slide 27 text
HTTP Methods – Examples
●
POST /invoices
Create a new invoice (auto-numbered?)
●
GET /invoices
Retrieve all invoices
●
PUT /invoices
Replace all invoices
●
DELETE /invoices
Delete all invoices
Slide 28
Slide 28 text
HTTP Headers
● Headers should be used for metadata
● Contain information about resources and
about the HTTP transaction
● Especially important for content negotiation
and conditional requests
● The “X-” prefix used to be recommended for
non-standard headers – not anymore
Slide 29
Slide 29 text
HTTP Headers
A few common HTTP headers:
●
Date
Date/time when the message was sent
●
Last-Modified
Date/time when the resource was modified
●
Location
URI related to the resource
Slide 30
Slide 30 text
HTTP Headers – Content Negotiation
●
Accept
Which representation formats are accepted
●
Accept-Encoding
Which compression schemes are accepted
●
Content-Type
The representation format of the content
●
Content-Encoding
The compression scheme of the content
Slide 31
Slide 31 text
HTTP Headers – Conditional Requests
●
ETag
Identifier for a specific version of a resource
● If-Match / If-None-Match
Process request if version identifier
matches/doesn't match
● If-Modified-Since / If-Unmodified-Since
Process request if resource has/hasn't been
modified since the specified date/time
Slide 32
Slide 32 text
HTTP Headers – Examples
Request headers:
● Ask for JSON representation of a resource:
Accept: application/json
● Retrieve the resource only if it was modified:
If-Modified-Since: Sat, 30 May 2015...
● Send basic HTTP authentication data:
Authorization: Basic QWxhZGRpbjpv...
Slide 33
Slide 33 text
HTTP Headers – Examples
Response headers:
● Return the URI of a newly POSTed resource:
Location: .../invoices/2015-05-125
● Return the date/time of last modification:
Last-Modified: Sat, 30 May 2015...
● Tell the client to authenticate:
WWW-Authenticate: Basic realm="...”
Slide 34
Slide 34 text
HTTP Status Codes
● RESTful APIs return sensible HTTP status
codes
● The meanings are not strictly defined – it's
up to the API designer to choose what fits
● It's not OK to always return “200 OK”
HTTP Status Codes
Success codes often used in RESTful APIs:
●
304 Not Modified
●
200 OK
●
201 Created
●
202 Accepted
●
204 No Content
Slide 37
Slide 37 text
HTTP Status Codes
Error codes often used in RESTful APIs:
●
500 Internal
Server Error
●
503 Service
Unavailable
●
400 Bad Request
●
401 Unauthorized
●
403 Forbidden
●
404 Not Found
●
405 Method Not
Allowed
●
409 Conflict
Slide 38
Slide 38 text
HTTP Status Codes – Examples
● POSTing or PUTting a new resource:
201 Created
● POST or PUT with invalid data:
400 Bad Req. / 422 Unprocessable Entity
● PUT on a read-only resource:
405 Method Not Allowed
● Resource DELETEd:
204 No Content
Slide 39
Slide 39 text
HTTP Status Codes
418 – I'm a teapot
Slide 40
Slide 40 text
Real-life Example: GitHub API
Creating a repository:
POST /user/repos
Response status code: 201 Created
Location: .../repos/bob/Cool-Project
{
”name”: ”Cool-Project”,
”description”: ”A very cool project.”,
”has_wiki”: true
}
Slide 41
Slide 41 text
Real-life Example: GitHub API
[
{
”sha”: ”f61aebed695e2e4...”, ...
},
...
]
Listing commits on a pull request:
GET /repos/bob/project/pulls/123/commits
Response:
Slide 42
Slide 42 text
Real-life Example: GitHub API
{
"message": "Branch not found",
"documentation_url": "https://..."
}
Trying to get a non-existing branch:
GET /repos/bob/project/branches/bogus
Response:
404 Not Found
Slide 43
Slide 43 text
Anti-example: Flickr API
Party photos ...
...
Listing user's photo galleries:
GET .../rest/?method=f.galleries.getList
Response:
Slide 44
Slide 44 text
Anti-example: Flickr API
Party photos ...
...
Listing user's photo galleries:
GET .../rest/?method=f.galleries.getList
Response: Nope
Slide 45
Slide 45 text
Anti-example: Twitter “REST” API
● Adding a new tweet:
POST /statuses/update.json
● Retrieving user information:
GET /users/show.json?screen_name=alice
● Deleting a tweet:
POST /statuses/destroy/789123456.json
Slide 46
Slide 46 text
Anti-example: Twitter “REST” API
● Adding a new tweet:
POST /statuses/update.json
● Retrieving user information:
GET /users/show.json?screen_name=alice
● Deleting a tweet:
POST /statuses/destroy/789123456.json
Pffft!
Slide 47
Slide 47 text
Authentication
Statelessness makes authentication a
challenge:
● No client context on the server means
there's no concept of an authenticated client
● Authentication state must be maintained
elsewhere
● Effectively, authentication data must be sent
by the client with every request
Slide 48
Slide 48 text
Authentication
● As a compromise, some APIs turn to a
stateful solution
● Examples: access tokens (OAuth), session
cookies
● Shared token/session storage is required
● Trade-off in scalability
Authentication
Basic HTTP Authentication
● Username and password are sent with each
request
● Not encrypted/hashed (Base64-encoded)
● Completely insecure unless used with
HTTPS
Slide 51
Slide 51 text
Authentication
Hash-based Message Authentication Code
● Client and server use a shared secret (e.g.
client's private API key)
● Client uses the secret key to sign requests
● Server verifies if the provided signature
matches the contents of the request
● Can be timestamped to avoid replay attacks
Slide 52
Slide 52 text
HATEOAS
● Hypermedia as the Engine of Application
State
● Server uses hypermedia to provide
information on possible operations
● Client can gradually discover the API
Slide 53
Slide 53 text
HATEOAS
● Hypermedia as the Engine of Application
State
● Server uses hypermedia to provide
information on possible operations
● Client can gradually discover the API
● Worst acronym ever
Slide 54
Slide 54 text
HATEOAS – Example
Hello, World!
...
GET /posts/2015-05-30
Response:
Richardson Maturity Model
A way to grade an API according to the
constraints of REST.
● Level 0: The Swamp of POX (Plain Old XML)
● Level 1: Resources
● Level 2: HTTP Verbs
● Level 3: Hypermedia Controls
Slide 57
Slide 57 text
Richardson Maturity Model
A way to grade an API according to the
constraints of REST.
● Level 0: The Swamp of POX (Plain Old XML)
● Level 1: Resources
● Level 2: HTTP Verbs
● Level 3: Hypermedia Controls
Truly RESTful™