45
REST Essentials Sergey Podolsky [email protected]

Rest Essentials

Embed Size (px)

Citation preview

Page 1: Rest Essentials

REST EssentialsSergey Podolsky

[email protected]

Page 2: Rest Essentials
Page 3: Rest Essentials

WorldWideWeb ProjectTim Berners-Lee, CERN, 1990• URI syntax• HTTP• HTML• Web server• Web browser (“Nexus”)• HTML editor (“WYSIWYG”)

Page 4: Rest Essentials

Representational State TransferRoy Fielding, Ph.D. dissertation, 2000REST is not:• Protocol• RPC (e.g. SOAP, WSDL)• HTTP• URIs

REST is Web’s architectural style

Page 5: Rest Essentials

Richardson Maturity Model

Page 6: Rest Essentials

Resource state• HTML• JSON• HTML• CSV• …

Page 7: Rest Essentials

REST Constraints1. Client-server2. Uniform interface3. Layered system4. Cache5. Stateless6. Code-on-demand

Page 8: Rest Essentials

Client-server• Implemented independently• Deployed independently• Evolve independently

Page 9: Rest Essentials

Uniform Interface1. Identification of resources

• http://example.org/resources/1234

2. Manipulation of resources through representations• HTML• XML• JSON• …

3. Self-descriptive messages• Accept: text/plain• Content-Type: text/plain

4. Hypermedia as the engine of application state (HATEOAS)• <link rel = "self" uri = "/resources/1234"/>• <link rel = "/linkrels/resource/delete" uri = "/resources/1234/delete"/>

Page 10: Rest Essentials

Layered SystemEnables intermediaries (proxies, gateways) for:1. Enforcement of security2. Response caching3. Load balancing

Page 11: Rest Essentials

Cache• Reduce latency• Increase availability• Increase reliability• Reduce server load

Page 12: Rest Essentials

Stateless• No server state• No server session• Client must include all of the contextual information

Page 13: Rest Essentials

Code-On-Demand• Java applets• JavaScript• Flash• Silverlight• …

Page 14: Rest Essentials

“/” to indicate a hierarchical relationshiphttp://api.canvas.restapi.org/shapes/polygons/quadrilaterals/squares

Page 15: Rest Essentials

“-” to improve the readability of URIs• http://api.example.org/dummy-resources/dummy-resource

“_” should not be used in URIs• http://api.example.org/dummy_resources/dummy_resource

Page 18: Rest Essentials

Consistent subdomain names should be used for your APIs• http://api.soccer.restapi.org

Consistent subdomain names should be used for your client developer portal• http://developer.soccer.restapi.org

Page 19: Rest Essentials

Resource Archetypes• Document• Collection• Store• Controller

Page 22: Rest Essentials

Store – client-managed resource repository• PUT /users/1234/favorites/alonso

Page 23: Rest Essentials

Controller – models a procedural concept• POST /alerts/245743/resend

Page 26: Rest Essentials

CRUD function names should not be used in URIs• DELETE /users/1234• GET /deleteUser?id=1234• GET /deleteUser/1234• DELETE /deleteUser/1234• POST /users/1234/delete

Page 27: Rest Essentials

The query component of a URI may be used to filter collections or stores• GET /users• GET /users?role=admin

Page 28: Rest Essentials

The query component of a URI should be used to paginate collection or store results

• GET /users?pageSize=10&pageStartIndex=50

Page 29: Rest Essentials

GET to retrieve a representation of a resourceGET /greeting HTTP/1.1User-Agent: curl/7.20.1Host: api.example.restapi.orgAccept: */*

HTTP/1.1 200 OKDate: Sat, 20 Aug 2011 16:02:40 GMTServer: ApacheExpires: Sat, 20 Aug 2011 16:03:40 GMTCache-Control: max-age=60, must-revalidateETag: text/html:hello worldContent-Length: 130Last-Modified: Sat, 20 Aug 2011 16:02:17 GMTVary: Accept-EncodingContent-Type: text/html<html> <head><meta charset="utf-8"><title>Greeting</title></head> <body><div id="greeting">Hello World!</div></body></html>

Page 30: Rest Essentials

HEAD to retrieve response headersHEAD/greeting HTTP/1.1User-Agent: curl/7.20.1Host: api.example.restapi.orgAccept: */*

HTTP/1.1 200 OKDate: Sat, 20 Aug 2011 16:02:40 GMTServer: ApacheExpires: Sat, 20 Aug 2011 16:03:40 GMTCache-Control: max-age=60, must-revalidateETag: text/html:hello worldContent-Length: 130Last-Modified: Sat, 20 Aug 2011 16:02:17 GMTVary: Accept-EncodingContent-Type: text/html

Page 31: Rest Essentials

PUT to insert and update a stored resource• PUT /accounts/4ef2d5d0-cb7e-11e0-9572-0800200c9a66/buckets/objects/4321

POST to create a new resource in a collection• POST /leagues/seattle/teams/trebuchet/players

Page 32: Rest Essentials

POST to execute controllers• POST /alerts/245743/resend

DELETE to remove a resource from its parent• DELETE /accounts/4ef2d5d0-cb7e-11e0-9572-0800200c9a66/buckets/objects/4321

Page 33: Rest Essentials

OPTIONS to retrieve a resource’s available interactions• Allow: GET, PUT, DELETE

Page 34: Rest Essentials

Metadata Design• Content-Type• Content-Length• Last-Modified• Etag• Stores must support conditional PUT requests• If-Unmodified-Since• If-Match <ETag>

• Location - to specify the URI of a newly created resource

Page 35: Rest Essentials

Metadata Design• Cache-Control, Expires, and Date to encourage caching• Cache-Control: max-age=60, must-revalidate• Date: Tue, 15 Nov 1994 08:12:31 GMT• Expires: Thu, 01 Dec 1994 16:00:00 GMT

• Cache-Control, Expires, and Pragma to discourage caching• Cache-Control: no-cache• Pragma: no-cache (HTTP 1.0)• Expires: 0 (HTTP 1.0)

• Caching should be encouraged• Use small max-age instead of no-cache

Page 36: Rest Essentials

Custom HTTP headers must not be usedUse:• Request body• Response body• URI

Page 37: Rest Essentials

Media TypesSyntax:

type "/" subtype ( ";" parameter )*

Page 38: Rest Essentials

Media type negotiation should be supported when multiple representations are available• Accept: application/json

Media type selection using a query parameter may be supported• GET /bookmarks/podolsks?accept=application/xml

Page 39: Rest Essentials

JSON should be supported for resource representation

JSON must be well-formed

{"firstName" : "Osvaldo","lastName" : "Alonso","firstNamePronunciation" : "ahs-VAHL-doe","number" : 6,"birthDate" : "1985-11-11"

}

Page 40: Rest Essentials

OAuth may be used to protect resources

http://oauth.net

Page 41: Rest Essentials

The query component of a URI should be used to support partial responses# RequestGET /students/morgan?fields=(firstName,birthDate) HTTP/1.1Host: api.college.restapi.org

# ResponseHTTP/1.1 200 OKContent-Type: application/wrml;

format="http://api.formats.wrml.org/application/json";schema="http://api.schemas.wrml.org/college/Student";fields="(birthDate,firstName)"

{"firstName" : "Morgan","birthDate" : "1992-07-31"

}

Page 42: Rest Essentials

The query component of a URI should be used to embed linked resources# RequestGET /students/morgan?embed=(favoriteClass) HTTP/1.1Host: api.college.restapi.org

# ResponseHTTP/1.1 200 OKContent-Type: application/wrml;

format="http://api.formats.wrml.org/application/json";schema="http://api.schemas.wrml.org/college/Student";embed="(favoriteClass)"

{"firstName" : "Morgan","birthDate" : "1992-07-31","favoriteClass" : {

"id" : "japn-301","name" : "Third-Year Japanese","links" : {

"self" : {"href" : "http://api.college.restapi.org/classes/japn-301","rel" : "http://api.relations.wrml.org/common/self"

}}

}...

}

Page 43: Rest Essentials

Same-origin policyorigin = scheme + host + port

Compared URL Outcome Reason

http://www.example.com/dir/page2.html Success Same protocol, host and port

http://www.example.com/dir2/other.html Success Same protocol, host and port

http://username:[email protected]/dir2/other.html Success Same protocol, host and port

http://www.example.com:81/dir/other.html Failure Same protocol and host but different port

https://www.example.com/dir/other.html Failure Different protocol

http://en.example.com/dir/other.html Failure Different host

http://example.com/dir/other.html Failure Different host (exact match required)

http://v2.www.example.com/dir/other.html Failure Different host (exact match required)

http://www.example.com:80/dir/other.html Depends Port explicit. Depends on implementation in browser

Page 44: Rest Essentials

JSONP should be supported to provide multi-origin read access from JavaScript# RequestGET /players/1421?callback=showPlayerFullName HTTP/1.1Host: api.soccer.restapi.org

# ResponseHTTP/1.1 200 OKContent-Type: application/javascriptshowPlayerFullName(

{"firstName" : "Kasey","lastName" : "Keller","number" : 18,"birthDate" : "1969-11-29","links" : {"self" : {"href" : "http://api.soccer.restapi.org/players/1421","rel" : "http://api.relations.wrml.org/common/self"}}}

);

Page 45: Rest Essentials

CORS should be supported to provide multi-origin read/write access from JavaScriptCORS = Cross-origin resource sharing

Request headers:• Origin• Access-Control-Request-Method• Access-Control-Request-Headers

Response headers:• Access-Control-Allow-Origin• Access-Control-Allow-Credentials• Access-Control-Expose-Headers• Access-Control-Max-Age• Access-Control-Allow-Methods• Access-Control-Allow-Headers