Upgrade to Pro — share decks privately, control downloads, hide ads and more …

RESTful Web Services

Sidnet
May 30, 2015

RESTful Web Services

An overview of RESTful Web Services.

Sidnet

May 30, 2015
Tweet

More Decks by Sidnet

Other Decks in Programming

Transcript

  1. What REST Means REpresentational State Transfer We are transferring a

    representation of the current state of a resource/application
  2. 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
  3. Architectural Constraints Client-server • Separation of concerns • Servers store

    data • Clients provide user interface • Uniform interface between servers and clients
  4. Architectural Constraints Stateless • Each request is processed independently •

    No client context is stored on the server • The client is responsible for keeping application state
  5. 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
  6. 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, ...
  7. Architectural Constraints Cacheable • Clients or intermediary servers may cache

    responses • Resources must be labeled as cacheable or non-cacheable (explicitly or implicitly)
  8. 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
  9. Architectural Constraints • Stateless • Cacheable • Layered system Scalability

    It's fairly easy to just “throw more servers at it”
  10. 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)
  11. Resources Addressability through the use of URIs: • Single resource

    e.g.: /invoices/2015-05-123 • Collections of resources e.g.: /invoices/
  12. 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)
  13. Resource Representations Accept: text/xml XML representation: Accept: application/json JSON representation:

    <person> <name>Bob</name> <age>25</age> </person> { name: “Bob”, age: 25 }
  14. HTTP Methods • POST Create a new resource • GET

    Retrieve a resource • PUT Create or replace a resource • DELETE Remove a resource
  15. 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
  16. 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”)
  17. 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).
  18. HTTP Methods • GET Retrieve a resource – nullipotent •

    POST Create a new resource • PUT Create or replace a resource – idempotent • DELETE Remove a resource – idempotent
  19. HTTP Methods • PATCH Partially replace a resource – can

    be idempotent • HEAD, OPTIONS – obviously nullipotent
  20. 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”
  21. 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?
  22. 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
  23. 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
  24. 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
  25. 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
  26. 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
  27. 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...
  28. 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="...”
  29. 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”
  30. HTTP Status Codes • 1xx – Informational • 2xx –

    Success • 3xx – Redirection • 4xx – Client error • 5xx – Server error
  31. HTTP Status Codes Success codes often used in RESTful APIs:

    • 304 Not Modified • 200 OK • 201 Created • 202 Accepted • 204 No Content
  32. 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
  33. 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
  34. 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 }
  35. Real-life Example: GitHub API [ { ”sha”: ”f61aebed695e2e4...”, ... },

    ... ] Listing commits on a pull request: GET /repos/bob/project/pulls/123/commits Response:
  36. 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
  37. 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:
  38. 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
  39. 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
  40. 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!
  41. 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
  42. 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
  43. Authentication Basic HTTP Authentication • Username and password are sent

    with each request • Not encrypted/hashed (Base64-encoded) • Completely insecure unless used with HTTPS
  44. 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
  45. HATEOAS • Hypermedia as the Engine of Application State •

    Server uses hypermedia to provide information on possible operations • Client can gradually discover the API
  46. 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
  47. 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:
  48. 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
  49. 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™