Slide 1

Slide 1 text

DEMYSTIFYING THE REST API SAMANTHA QUIÑONES

Slide 2

Slide 2 text

About Me Samantha Quiñones SW Architect & Lead Developer at POLITICO.com Follow me: @ieatkillerbees

Slide 3

Slide 3 text

No content

Slide 4

Slide 4 text

No content

Slide 5

Slide 5 text

No content

Slide 6

Slide 6 text

No content

Slide 7

Slide 7 text

What is REST? (and why am I talking about it?) REpresentational State Transfer An architectural style that describes a set of rules for delivering content over an open network

Slide 8

Slide 8 text

ROY FIELDING DESCRIBED THE REST PATTERN IN HIS 2000 DOCTORAL DISSERTATION

Slide 9

Slide 9 text

Nothing is more easy than to reduce this mass to one quarter of its bulk. You know that curious cellular matter which constitutes the elementary tissues of vegetable? This substance is found quite pure in many bodies, especially in cotton, which is nothing more than the down of the seeds of the cotton plant. Now cotton, combined with cold nitric acid, become transformed into a substance eminently insoluble, combustible, and explosive. It was first discovered in 1832, by Braconnot, a French chemist, who called it xyloidine. In 1838 another Frenchman, Pelouze, investigated its different properties, and finally, in 1846, Schonbein, professor of chemistry at Bale, proposed its employment for purposes of war. This powder, now called pyroxyle, or fulminating cotton, is prepared with great facility by simply plunging cotton for fifteen minutes in nitric acid, then washing it in water, then drying it, and it is ready for use.

Slide 10

Slide 10 text

Nothing is more easy than to reduce this mass to one quarter of its bulk. You know that curious cellular matter which constitutes the elementary tissues of vegetable? This substance is found quite pure in many bodies, especially in cotton, which is nothing more than the down of the seeds of the cotton plant. Now cotton, combined with cold nitric acid, become transformed into a substance eminently insoluble, combustible, and explosive. It was first discovered in 1832, by Braconnot, a French chemist, who called it xyloidine. In 1838 another Frenchman, Pelouze, investigated its different properties, and finally, in 1846, Schonbein, professor of chemistry at Bale, proposed its employment for purposes of war. This powder, now called pyroxyle, or fulminating cotton, is prepared with great facility by simply plunging cotton for fifteen minutes in nitric acid, then washing it in water, then drying it, and it is ready for use.

Slide 11

Slide 11 text

No content

Slide 12

Slide 12 text

Apache PHP 5.4 MariaDB Typical Application Design

Slide 13

Slide 13 text

Hopefully… Requirements are met Users are happy Invoices are paid

Slide 14

Slide 14 text

MO’ ENDPOINTS, MO’ PROBLEMS `

Slide 15

Slide 15 text

No content

Slide 16

Slide 16 text

Ordo ab chao REST is a set of constraints designed to bring order of the chaos of free-form hypermedia The young web was extremely disordered Fielding envisioned the web as a system that could be moulded by carefully applying constraints

Slide 17

Slide 17 text

The Early Web Hypertext Data Flash Media Java Applets Cat Pictures

Slide 18

Slide 18 text

The Early Web GIEF CAT PIX PL0X!!1!

Slide 19

Slide 19 text

Null Style The Null Style describes an empty set of constraints There are no boundaries and no structure

Slide 20

Slide 20 text

CLIENT-SERVER ARCHITECTURE CONSTRAINT #1

Slide 21

Slide 21 text

Client-Server Architecture The system is divided in to clients and servers Servers store hypermedia resources Clients manage the display and caching of resources

Slide 22

Slide 22 text

PORTABILITY PREMIUM INFINITE DIVERSITY IN INFINITE CLIENTS

Slide 23

Slide 23 text

STATELESSNESS CONSTRAINT #2

Slide 24

Slide 24 text

Implicit State Requesting the “next” resource in a collection requires the server to know what you asked for last This information may need to be shared among many servers in a cluster This information may be lost due to server errors Gief next cat pic pls!

Slide 25

Slide 25 text

Explicit State The client is better suited to choose what state is important Server failures do not cause loss of state Improved performance and reliability Load-balancing becomes trivial Gief cat pic #3427 pls!

Slide 26

Slide 26 text

Debugging State Stinks All requests contain all the context needed to execute them Simplifies debugging Makes traffic “replayable”

Slide 27

Slide 27 text

CACHE-ABILITY CONSTRAINT #3

Slide 28

Slide 28 text

Cacheable Requests Transmitting state with each request increases overhead Allowing clients to cache responses can drastically reduce the number required requests

Slide 29

Slide 29 text

Best Parsed By… Resources can carry an expiration time Clients can wait until a resource expires before requesting it again

Slide 30

Slide 30 text

UNIFORM INTERFACE CONSTRAINT #4

Slide 31

Slide 31 text

Resources Resources are abstractions of data with a globally unique identifier http://i.imgur.com/eqTIb.jpg

Slide 32

Slide 32 text

Representations {      name:  “Kitty  McAwesome”,      awesome:  true,      cute:  “very”,      image_uri:  “http://i.imgur.com/eqTIb.jpg”   }

Slide 33

Slide 33 text

Self-Contained Requests GET  /eqTIb.jpg  HTTP/1.1   Host:  i.imgur.com   If-­‐Modified-­‐Since:  Fri,  02  Dec  2011  19:47:21  GMT

Slide 34

Slide 34 text

HATEOAS Hypermedia As The Engine Of Application State

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

HATEOAS GET  /events/201   ! 200  OK        201      Summer  Bridge  Party                David  Wildstein          [email protected]                              

Slide 37

Slide 37 text

Hypermedia Types HTML XML CSS XHTML Atom

Slide 38

Slide 38 text

JSON IS NOT A HYPERMEDIA TYPE

Slide 39

Slide 39 text

No content

Slide 40

Slide 40 text

JSON & Hypermedia GET  /events/201   ! 200  OK   {      id:  201,      name:  “Summer  Bridge  Party”,      organizer:  {          name:  “David  Wildstein”,          email:  “[email protected]”      }   }  

Slide 41

Slide 41 text

JSON Hyper-Schema Extension of json-schema that allows for hypermedia descriptions http://json-schema.org

Slide 42

Slide 42 text

Hypertext Application Language (HAL) Proposed standard that extends the JSON type with hypermedia data application/json+hal Small but growing acceptance

Slide 43

Slide 43 text

HAL GET  /events/201   ! 200  OK   {      “id”:  201,      “name”:  “Summer  Bridge  Party”,      “_links”:  {          “self”:  {  “href”:  “/events/201”  },      },      “_embedded”:  {          “organizer”:  {                “_links”:  {                    “self”:  {  “href”:  “/organizers/42”  }              }      }   }

Slide 44

Slide 44 text

CONSTRAINT LAYERING CONSTRAINT #5

Slide 45

Slide 45 text

Layered System Any two layers can only see one another Client > Proxy > Load Balancer > Server

Slide 46

Slide 46 text

CODE-ON- DEMAND CONSTRAINT #6

Slide 47

Slide 47 text

Batteries Included Representations can include executable code Allows clients to have extended functionality without updating multiple code bases JavaScript, Flash, Java Applets

Slide 48

Slide 48 text

REPRESENTATIONS & RESOURCES UNDERSTANDING THE PARTS

Slide 49

Slide 49 text

Elements of Rest Resources Representations Meta Data Control Data

Slide 50

Slide 50 text

“A resource (R) is a temporally varying membership function MR(t), which for time t maps to a set of entities, or values, which are equivalent.” –Roy Fielding Resources

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

Resources An abstraction of some entity, or a collection of entities, that we can identify by name. http://i.imgur.com/eqTIb.jpg “all accounts created on October 12th” “the most recent 100 tweets containing the string ‘#redwedding’”

Slide 53

Slide 53 text

Resources On the web, we use Uniform Resource Identifiers http://i.imgur.com/eqTIb.jpg Resource named eqTIb.jpg available via HTTP from i.imgur.com

Slide 54

Slide 54 text

Representations In order to interact with a resource, we use a representation Representations contain data and metadata

Slide 55

Slide 55 text

Representations GET  /accounts/42   ! 200  OK   Content-­‐Type:  application/json+hal   ! {      account_id:  42,      account_name:  “Samantha  Quiñones”,      account_status:  “awesome”      _links:  {  self:  {  href:  “/accounts/42”  }  }         }

Slide 56

Slide 56 text

Representations Resources are abstract, representations are concrete Representations are the actual bytes that are transferred between clients and servers, including metadata Often called a “file,” “document,” or “entity”

Slide 57

Slide 57 text

Control Data Control data is extra information used by the client and server to coordinate Cache control information Parameters Content-type negotiation

Slide 58

Slide 58 text

What is REST? Resource-oriented DRY Cache-ready Stateless

Slide 59

Slide 59 text

HTTP HYPERTEXT TRANSFER PROTOCOL

Slide 60

Slide 60 text

HyperText Transfer Protocol Version 0.9 (1991), Version 1.0 (1996) Current Version 1.1 defined by RFC 2616 Nine methods, ~40 response codes

Slide 61

Slide 61 text

Request-Response Cycle Client opens a connection to a server Client sends a request containing a method, a resource, and optionally meta/control data Server responds with a status code and a representation of the requested resource, along with meta/control data

Slide 62

Slide 62 text

Methods “Safe” methods: GET, HEAD, TRACE, OPTIONS “Unsafe” methods: PUT, POST, DELETE, PATCH “Control” method: CONNECT

Slide 63

Slide 63 text

GET Requests a representation of a resource Safe method without side effects

Slide 64

Slide 64 text

! $app-­‐>get("/foo/{id}",  function  (Request  $request,  Application  $app,  $id)  {          if  (  !  $app['db']-­‐>has($id))  {                  throw  new  HttpNotFoundException();          }   !        return  new  Response($app['db']-­‐>get($id));   });   GET

Slide 65

Slide 65 text

HEAD, OPTIONS, and TRACE HEAD requests the headers that would have been sent with the equivalent GET request OPTIONS requests the HTTP methods that the server supports for a given resource TRACE requests the server echo back the request. This is useful for determining if an intermediate server is altering a requests in flight.

Slide 66

Slide 66 text

DELETE Delete a resource

Slide 67

Slide 67 text

DELETE $app-­‐>delete("/foo/{id}",  function  (Request  $request,  Application  $app,  $id)  {          if  (  !  $app['db']-­‐>has($id))  {                  throw  new  HttpNotFoundException();          }   !        $app['db']-­‐>delete($id);   !        return  new  Response("",  Response::HTTP_NO_CONTENT);   });

Slide 68

Slide 68 text

PUT Asks the server to store a resource at a specific URI, overwriting it if it already exists

Slide 69

Slide 69 text

PUT $app-­‐>put("/foo/{id}",  function  (Request  $request,  Application  $app,  $id)  {          if  ($app['db']-­‐>has($id))  {                  $app['db']-­‐>update($id,  $request-­‐>getBody());                  return  new  Response("",  Response::HTTP_OK)          }   !        $app['db']-­‐>insertWithId($id,  $request-­‐>getBody());          return  new  Response("",  Response::HTTP_CREATED);   });

Slide 70

Slide 70 text

POST Asks the server to store a resource as a sub- resource of a specified resource or collection

Slide 71

Slide 71 text

POST $app-­‐>post("/foo",  function  (Request  $request,  Application  $app)  {          $newId  =  $app['db']-­‐>insert($request-­‐>getBody());          $responseData  =  array(                  "_links"  =>  array(                          "self"  =>  array(                                  "href"  =>  "/foo/$newId"                          )                  )          );          return  new  Response($responseData,  Response::HTTP_CREATED);   });  

Slide 72

Slide 72 text

POST is Versatile Annotate existing resources Posting to a message board, mailing list, etc Providing a block of data to a data-handling process Appending to a database

Slide 73

Slide 73 text

PUT vs POST PUT creates or replaces a resources with a known identifier POST creates a sub-resource of an existing resource or collection

Slide 74

Slide 74 text

Idempotence When the result of an operation remains the same no matter how many times the operation is performed, the operation is “idempotent”

Slide 75

Slide 75 text

Idempotence Safe & Idempotent • GET • TRACE • HEAD • OPTIONS Unsafe & Idempotent • PUT • DELETE ! Unsafe & Non-Idempotent • POST • PATCH

Slide 76

Slide 76 text

DELETE is Idempotent Deleting a resource causes the server to return a status code of 204 (NO CONTENT) Subsequent DELETE requests will cause the server to return a status code of 404 (NOT FOUND) How is that idempotent?

Slide 77

Slide 77 text

Idempotence Refers to Resource State Even though the first DELETE request returns a different status code than subsequent requests, the state of that resource (that is, it’s lack of existence) remains the same!

Slide 78

Slide 78 text

PUT vs POST Redux PUT is idempotent POST is not always idempotent, though it can be Use PUT to create or replace resources whose name you already know Use POST to create sub-resources and to append to a collection

Slide 79

Slide 79 text

PUT vs POST Example PUT  /talks/demystifying-­‐the-­‐rest-­‐api   ! {      talk_name:  “Demystifying  the  REST  API”,      speaker:  “Samantha  Quiñones”,      conferences:  []   }  

Slide 80

Slide 80 text

PUT vs POST Example GET  /talks/demystifying-­‐the-­‐rest-­‐api   ! 200  OK   {      talk_name:  “Demystifying  the  REST  API”,      speaker:  “Samantha  Quiñones”,      conferences:  []   }  

Slide 81

Slide 81 text

PUT vs POST Example POST  /talks/demystifying-­‐the-­‐rest-­‐api/conferences   ! {conference_name:  “Northeast  PHP”}  

Slide 82

Slide 82 text

PUT vs POST Example GET  /talks/demystifying-­‐the-­‐rest-­‐api   ! {      talk_name:  “Demystifying  the  REST  API”,      speaker:  “Samantha  Quiñones”,      conferences:  [{conference_name:  “Northeast  PHP”} {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},   {conference_name:  “Northeast  PHP”},  

Slide 83

Slide 83 text

PATCH Asks the server to modify a resource Newest method Not widely supported (yet) Must be used with caution because of potentially high collision risk

Slide 84

Slide 84 text

Why PATCH? PUT requires us to send a complete copy of the resource, which causes a lot of overhead POST is often used to modify resources, but there is no standard methodology Standards (like JSON Patch) are being developed Patching XML is (partially) supported in RFC 5261

Slide 85

Slide 85 text

JSON Patch PATCH  /foo   ! 200  OK   [    {  "op":  "test",  "path":  "/a/b/c",  "value":  "foo"  },    {  "op":  "remove",  "path":  "/a/b/c"  },    {  "op":  "add",  "path":  "/a/b/c",  "value":  [  "foo",  "bar"  ]  },    {  "op":  "replace",  "path":  "/a/b/c",  "value":  42  },    {  "op":  "move",  "from":  "/a/b/c",  "path":  "/a/b/d"  },    {  "op":  "copy",  "from":  "/a/b/d",  "path":  "/a/b/e"  }   ]  

Slide 86

Slide 86 text

CONNECT Used with proxies that allow for tunneling or protocol switching and other things that are both interesting and intensely boring

Slide 87

Slide 87 text

Status Codes 1xx - Informational Messages 2xx - Success 3xx - Redirection 4xx - Client error (“you messed up!”) 5xx - Server error (“I messed up!”)

Slide 88

Slide 88 text

BUILDING GREAT APIS THOUGHTS, TIPS, AND RESOURCES

Slide 89

Slide 89 text

What happens when you assume… REST makes assumptions safe by applying well- established patterns A REST API should be self-documenting so that clients can easily integrate with it

Slide 90

Slide 90 text

Respect safe methods GET should never cause side-effects! GET /events/delete?id=201

Slide 91

Slide 91 text

Use response codes everyone understands It’s easier for a client to respond to “401 Unauthorized” than “500 Your login has timed out”

Slide 92

Slide 92 text

Don’t overload POST “When in doubt, use POST” Reconsider your application design. Does another method fit better? Are you not really working just with objects and interactions? Is REST the right pattern for your application?

Slide 93

Slide 93 text

Resources RFC 2616 “Hypertext Transfer Protocol” (http://bit.ly/ LkW6OW) RFC 5789 “PATCH Method for HTTP” (http://bit.ly/1cFpvtq) JSON HAL Proposal (http://bit.ly/1kJLvgw) RFC 6902 “JSON PATCH” (http://bit.ly/LkWyww) Fielding’s Dissertation (http://bit.ly/1eTY8AI) REST Cookbook (http://restcookbook.com)

Slide 94

Slide 94 text

PHP Resources HATEOAS for PHP: http://hateoas-php.org/ Well-supported, Symfony-ready HATEOAS library REST APIs with Symfony2: The Right Way (http:// williamdurand.fr/2012/08/02/rest-apis-with- symfony2-the-right-way/) Building APIs You Won’t Hate - Phil Sturgeon https://leanpub.com/build-apis-you-wont-hate

Slide 95

Slide 95 text

Feedback & Contact Joind.in https://joind.in/11470 Twitter: @ieatkillerbees Email: [email protected]