building rest and hypermedia apis with php

39
Building REST and Hypermedia APIs with PHP International PHP Conference 2012 Tbilisi, Georgia Wednesday, December 12, 12

Upload: azry-llc-caucasus-school-of-technology

Post on 20-May-2015

13.874 views

Category:

Documents


3 download

DESCRIPTION

Adapted version for students

TRANSCRIPT

Building REST and Hypermedia APIs with PHP

International PHP Conference 2012 Tbilisi, GeorgiaWednesday, December 12, 12

About me

‣ Ioseb Dzmanashvili

‣ Software Architect at AzRy LLC

‣ Teacher at Caucasus School of Technology

‣ V8 JavaScript engine contributor

‣ Author of uri_template PHP extension

‣ Author of Create-Form and Edit-Form link relation types (being RFCed now).

Wednesday, December 12, 12

RESTRepresentational State Transfer

Wednesday, December 12, 12

What is REST?

‣ It’s not a specification

‣ It’s not a design pattern

‣ It’s not... bla bla bla...

‣ It’s an architectural style

Wednesday, December 12, 12

An architectural style is a coordinated set of architectural constraints that restricts the roles/features of architectural elements and the allowed relationships

among those elements within any architecture that conforms to that style.

Roy T. Fielding 2000 (quote from dissertation)

Architectural StyleDefinition

Wednesday, December 12, 12

An architectural style is a named collection of architectural design

decisions that: 1) are applicable in a given development context; 2)

constrain architectural decision that are specific to a particular system within that context; and 3) elicit

beneficial qualities in each resulting system.

Richard N. Taylor et al.

DefinitionArchitectural Style

Wednesday, December 12, 12

Gothic ArchitectureAnalogy

Wednesday, December 12, 12

Georgian Church ArchitectureAnalogy

Wednesday, December 12, 12

Industrial ArchitectureAnalogy

Wednesday, December 12, 12

• Client Server: Separation of concerns is the principle behind the client-server constraints. ...Perhaps most significant to the Web, however, is that the separation allows the components to evolve independently.

• Stateless: ...communication must be stateless in nature, ...such that each request from client to server must contain all of the information necessary to understand the request, and cannot take advantage of any stored context on the server

• Cache: The advantage of adding cache constraints is that they have the potential to partially or completely eliminate some interactions, improving efficiency, scalability, and user-perceived performance by reducing the average latency of a series of interactions.

• Layered System: The layered system style allows an architecture to be composed of hierarchical layers by constraining component behavior such that each component cannot "see" beyond the immediate layer with which they are interacting.

• Code-On-Demand: (Optional constraint)

• Uniform Interface: (To be continued)

REST Constraints

Wednesday, December 12, 12

Uniform InterfaceBy applying the software engineering principle of generality to the component interface, the overall system architecture is simplified and the visibility of interactions is improved. Implementations are decoupled from the services they provide, which encourages independent evolvability.

In order to obtain a uniform interface, multiple architectural constraints are needed to guide the behavior of components. REST is defined by four interface constraints:

• identification of resources; • manipulation of resources through

representations; • self-descriptive messages; and, • hypermedia as the engine of application state.

Wednesday, December 12, 12

Hypermedia

Wednesday, December 12, 12

The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative,

hypertext information systems.

Hypertext Transfer Protocol RFC, HTTPbis

HTTP

Wednesday, December 12, 12

By "hypertext", I mean non-sequential writing - text that branches and allows choices to the reader, best read at an interactive screen. As popularity conceived, this is a series of text chunks connected by links which offer the reader different pathways.

Theodor Nelson 1960s

Hypertext

Wednesday, December 12, 12

An intriguing possibility, given a large hypertext database with

typed links, is that it allows some degree of automatic analysis.

Tim Berners-Lee 1989, CERN(Initial WWW proposal)

Hypertext

Wednesday, December 12, 12

Hypermedia simply extends the notion of the text in hypertext by

including visual information, sound, animation, and other forms of data.

George P. Landow

Hypermedia

Wednesday, December 12, 12

Hypermedia system, contains various types of relationships

between elements of information.

Hypermedia allows these relationships to be instantiated as

links which connect the various information elements, so that these links can be used to navigate within the

information space.

David Lowe, Wendy Hau 1999

Hypermedia

Wednesday, December 12, 12

Hypermedia: An application which uses associative relationships

among information contained within multiple media data for the purpose of

facilitating access to, and manipulation of, information

encapsulated by the data

David Lowe, Wendy Hau 1999

Hypermedia

Wednesday, December 12, 12

When I say hypertext, I mean the simultaneous presentation of information and controls such

that the information becomes the affordance through which the user (or

automaton) obtains choices and selects actions

Roy T. Fielding 2008

Hypertext

Wednesday, December 12, 12

Examples of controls?

<!-- non visible link --><link rel="stylesheet" type="text/css" href="styles.css">

<!-- outgoing link --><a href="/post/1/author" rel="author">John Doe</a>

<!-- embed link(transclusion) --><img src="/logo.jpg" alt="IBM Logo">

<!-- templated link. produces: /search?q=term --><form method="get" action="/search"> <label>Search: </label><input name="q"></form>

<!-- action link --><form method="post" action="/posts" type="text/plain"> <textarea>Representational State Transfer</textarea></form>

Wednesday, December 12, 12

Photo Service Example

Wednesday, December 12, 12

The Story

Hey folks, we’ve created amazing photo sharing service and we have an API! check it out:

http://service.org/photos

Wednesday, December 12, 12

Response

Request

GET /photos HTTP/1.1Host: service.org

Let’s try itList of Photos

HTTP/1.1 200 OKLink: </photos/1>; rel="enclosure"; type="image/jpg"; title= "Egypt", </photos/2>; rel="enclosure"; type="image/jpg"; title="Paris", </photos/3>; rel="enclosure"; type="image/jpg"; title="Tbilisi", </photos/upload-form>; rel="create-form"; title="Upload photo"

1

2

Wednesday, December 12, 12

What’s this Link Header?

• Link is a typed connection between two resources that are identified by Internationalised Resource Identifiers (IRIs)

• Links between resources need not be format specific; it can be useful to have typed links that are independent of their serialization.

• The relation type of a link is conveyed in the "rel" parameter's value.

• The "type" parameter, when present, is a hint indicating what the media type of the result of dereferencing the link should be.

Quotes from Web Linking spec(RFC5988)

Wednesday, December 12, 12

Meaning of Relations

• The value "enclosure" signifies a related resource that is potentially large and might require special handling.

• The value "create-form" signifies a related resource where a submission form can be obtained.

Quotes from specs

Wednesday, December 12, 12

Response

Response

Request

RequestGET /photos/1 HTTP/1.1Host: service.org

HTTP/1.1 200 OKContent-Type: image/jpegContent-Length: 1000Cache-Control: private, max-age=0ETag: a32lasdf

[PHOTO HERE]

GET /photos/1 HTTP/1.1Host: service.orgIf-None-Match: a32lasdf

HTTP/1.1 304 Not Modified

1

2

3

4

Fetching Photo (Client A)

Wednesday, December 12, 12

Response

Response

Request

RequestDELETE /photos/1 HTTP/1.1Host: service.org

HTTP/1.1 204 No Content

GET /photos/1 HTTP/1.1Host: service.orgIf-None-Match: a32lasdf

HTTP/1.1 404 Not FoundContent-Type: ...Content-Length: …Link: </photos>; rel="index"; title="Photos", </photos/upload-form>; rel="create-form";

1

2

3

4

Client B Deletes Photo

Client A Fetches it Again

Wednesday, December 12, 12

Uploading Photo (Step 1)

Response

RequestGET /photos/upload-form HTTP/1.1Host: service.org

HTTP/1.1 200 OKContent-Type: application/vnd.forms+jsonContent-Length: …

{ "method": "POST", "action": "/photos", "content-type": [ "image/jpeg", "image/png", "image/gif", ]}

1

2

Wednesday, December 12, 12

Response

Request

Uploading Photo (Step 2)

Response

RequestPOST /photos HTTP/1.1Host: service.orgContent-Type: image/jpegContent-Length: 3000

[PHOTO HERE]

HTTP/1.1 202 AcceptedLink: </photos/queue/e3ba8>; rel="monitor"Retry-After: 10

1

2

3

4

GET /photos/queue/e3ba8 HTTP/1.1Host: service.org

HTTP/1.1 303 See OtherLocation: /photos/1234

Wednesday, December 12, 12

Quick advices

Wednesday, December 12, 12

Do not use these:

‣ application/xml

‣ application/json

Do not use xml or json directly

Instead try:

‣ application/atom+xml

‣ application/vnd.collection+json

‣ application/vnd.hal+json

‣ or design your own.

Wednesday, December 12, 12

Never encode action in URI

Wrong:

‣ /some/resource/delete

‣ /some/resource/update

Correct:

‣ DELETE /some/resource HTTP/1.1

‣ POST /some/resource

Wednesday, December 12, 12

HTTP/1.1 200 OKContent-Type: application/jsonContent-Length: …

{"error": { "code": 1234, "message": "Page not found"}}

Wrong:

HTTP/1.1 404 Not FoundContent-Type: application/jsonContent-Length: …

Correct:

Do not Abuse Protocol

Wednesday, December 12, 12

Do not Use URIs Directly

HTTP/1.1 404 Not FoundContent-Type: ...Content-Length: …Link: </photos>; rel="index"; title="Photos", </photos/upload-form>; rel="create-form";

HTTP/1.1 404 Not FoundContent-Type: ...Content-Length: …Link: </photos>; rel="index"; title="Photos", </photos/upload-form>; rel="create-form";

Wednesday, December 12, 12

Do not hardcode control information in your code

HTTP/1.1 200 OKContent-Type: application/vnd.forms+jsonContent-Length: …

{ "method": "POST", "action": "/photos", "content-type": [ "image/jpeg", ]}

HTTP/1.1 200 OKContent-Type: application/vnd.forms+jsonContent-Length: …

{ "method": "POST", "action": "/photos", "content-type": [ "image/jpeg", ]}

Wednesday, December 12, 12

Links in JSON

Wednesday, December 12, 12

And where is PHP?

sorry... i lied :(

Wednesday, December 12, 12

Questions?

Wednesday, December 12, 12

Thank You!

Wednesday, December 12, 12