Share
Embed
Transcript
59 slides
-
What REST Means REpresentational State Transfer We are transferring a
representation of the current state of a resource/application -
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 • Stateless • Cacheable • Layered
system • Uniform interface -
Architectural Constraints Client-server • Separation of concerns • Servers store
data • Clients provide user interface • Uniform interface between servers and clients -
Architectural Constraints Stateless • Each request is processed independently •
No client context is stored on the server • The client is responsible for keeping application state -
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 -
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, ... -
Architectural Constraints Cacheable • Clients or intermediary servers may cache
responses • Resources must be labeled as cacheable or non-cacheable (explicitly or implicitly) -
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 -
Architectural Constraints Uniform interface • Identification/addressability of resources • Manipulation
of resources through representations • Self-descriptive messages -
Architectural Constraints • Stateless • Cacheable • Layered system Scalability
It's fairly easy to just “throw more servers at it” -
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) -
Resources Addressability through the use of URIs: • Single resource
e.g.: /invoices/2015-05-123 • Collections of resources e.g.: /invoices/ -
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) -
Resource Representations Accept: text/xml XML representation: Accept: application/json JSON representation:
<person> <name>Bob</name> <age>25</age> </person> { name: “Bob”, age: 25 } -
HTTP Methods • POST Create a new resource • GET
Retrieve a resource • PUT Create or replace a resource • DELETE Remove a resource -
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 -
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”) -
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). -
HTTP Methods • GET Retrieve a resource – nullipotent •
POST Create a new resource • PUT Create or replace a resource – idempotent • DELETE Remove a resource – idempotent -
HTTP Methods • PATCH Partially replace a resource – can
be idempotent • HEAD, OPTIONS – obviously nullipotent -
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” -
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? -
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 -
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 -
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 -
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 -
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 -
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... -
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="...” -
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 • 1xx – Informational • 2xx –
Success • 3xx – Redirection • 4xx – Client error • 5xx – Server error -
HTTP Status Codes Success codes often used in RESTful APIs:
• 304 Not Modified • 200 OK • 201 Created • 202 Accepted • 204 No Content -
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 -
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 -
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 } -
Real-life Example: GitHub API [ { ”sha”: ”f61aebed695e2e4...”, ... },
... ] Listing commits on a pull request: GET /repos/bob/project/pulls/123/commits Response: -
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 -
Anti-example: Flickr API <galleries total=”3” page=”1” ...> <gallery id=”123-45678” url=”...”>
<title>Party photos</title> ... </gallery> ... </galleries> Listing user's photo galleries: GET .../rest/?method=f.galleries.getList Response: -
Anti-example: Flickr API <galleries total=”3” page=”1” ...> <gallery id=”123-45678” url=”...”>
<title>Party photos</title> ... </gallery> ... </galleries> Listing user's photo galleries: GET .../rest/?method=f.galleries.getList Response: Nope -
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 -
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! -
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 -
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 Stateless solutions: • Basic HTTP Authentication (oh no) •
Hash-based Message Authentication Code (HMAC) -
Authentication Basic HTTP Authentication • Username and password are sent
with each request • Not encrypted/hashed (Base64-encoded) • Completely insecure unless used with HTTPS -
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 -
HATEOAS • Hypermedia as the Engine of Application State •
Server uses hypermedia to provide information on possible operations • Client can gradually discover the API -
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 -
HATEOAS – Example <post> <title>Hello, World!</title> <content>...</content> <link rel=”author” href=”/users/123”>
<link rel=”comments” href=”/posts/2015-05-30/comments”> </post> GET /posts/2015-05-30 Response: -
HATEOAS – Real-life Example: GitHub Link: <...users?q=waldo&page=2>; rel=”next”, <...users?q=waldo&page=7>; rel=”last”
... { “items”: [ ... ] } Find users: GET /search/users?q=waldo 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 -
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™