Demystifying the REST API

Post on 17-Jul-2015

266 views 6 download

Transcript of Demystifying the REST API

Demystifying the REST API

Samantha Quiñones (@ieatkillerbees)

@ieatkillerbees http://samanthaquinones.com

Engineer A person who designs, builds, or

maintains things.

Pattern A model or design used to guide the

building of things.

REST (Representational State Transfer)

An architectural pattern for distributed hypermedia systems.

REST[ful] API A resource-oriented API built to conform

with the REST architectural pattern.

Hypermedia A non-linear medium of many disparate types of information, including text, images, video, audio

and hypertext.

I’m not here to tell you…

How to Build an API

-Roy Fielding, REST Discussion Mailing List

“[T]he goal of my dissertation is to teach people how to think about the problem in terms of trade-offs, not

in terms of rigid repetition…”

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.

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.

NASA/JPL-Caltech

The REST Architectural Style

© Henry Story, 2007 (CC BY-NC 2.0)

Architectural Styles and the Design of Network-based Software Architectures

Roy T. Fielding (http://www.ics.uci.edu/~fielding/pubs/dissertation/faq.htm)

MySQL

PHP 5.6

NGINX

Symfony 2 RabbitMQ

WWW

Null Style

Client-Server Architecture

ServerClient

Statelessness

ServerClient

Client

Client

Cache

ServerClient

Client

Client

Uniform Interface

Server

Client

Client

Client

ServerRRSH

RRSH

Layered System

Server

Client

Client

Client

ServerRRSH

RRSH

Gatew

ay

Proxy

Code On Demand

Server

Client

Client

Client

ServerRRSH

RRSH

Gatew

ay

Proxy

The Uniform Interface

Resource A thing, or a collection of things that…

May be concrete, or abstract… May be static, or vary over time… Has a name that is unique…

Uniform Interface

Uniform Interface

Resource Identifier A unique name which is…

A conceptual mapping to a resource… Or a collection of resources…

Uniform Interface

http://galaxies.tembies.com/groups/local/galaxies/ngc4258.json

“The most recent 10 tweets containing the hashtag ‘#MWPHP’”

Uniform Interface

Representation A sequence of bytes that…

Contains the state of a resource… Consists of data… Metadata about the data… Metadata about the metadata…

Uniform Interface

{ "name": "Messier 106", "ngc_id": 4258, "type": "SAB(s)bc", "size": 135000 }

Uniform Interface

Content-Type: application/json

{ "name": "Messier 106", "ngc_id": 4258, "type": "SAB(s)bc", "size": 135000 }

Uniform Interface

Content-Type: application/json Cache-Control: max-age=3600 public

{ "name": "Messier 106", "ngc_id": 4258, "type": "SAB(s)bc", "size": 135000 }

Uniform Interface

Self-Contained Messages Contains all information necessary to…

Process the request… Return an appropriate representation…

Uniform Interface

Hypermedia As The Engine Of Application State

<galaxy> <ngc_id>4258</ngc_id> <name/>Messier 106</name> <type>SAB(s)bc</type> <size>135000</size> <link rel="group" href="/groups/local" /> <link rel="self" href="/groups/local/galaxies/ngc4258" /> </galaxy>

Hypermedia Formats

HTML XML

CSS Atom

JSON is not a Hypermedia Format

JSON Hypermedia

Collection+JSON JSON-LD

JSON:API UBER

JSON+HAL

Hypertext Application Language A proposed (2012) standard that…

Expresses relationships between resources… Supports JSON (JSON+HAL)… Supports XML (XML+HAL)…

{ "name": "Messier 106", "ngc_id": 4258, "type": "SAB(s)bc", "size": 135000, "_links": { "self": { "href": "/groups/local/galaxies/ngc4258" } }, "group": { "href": "/groups/local" } } } }

HTTP (Hyper Text Transport Protocol)

Version 0.9 (1991)

Version 1.0 (1996)

Version 1.1 (1999)

GET

POST

OPTIONS

HEAD

DELETE

TRACE

PUT

PATCH

CONNECT

IdempotentUnsafeSafe

GET POST

OPTIONS

HEAD

DELETE

TRACE

PUT PATCH

CONNECT

Idempotence

A property of an operation that can be applied multiple time without changing the result, such that ƒ(ƒ(𝑥)) = ƒ(𝑥)

GET

Request the representation of a resource with a given identifier

SafeIdempotent

GET /groups/local/galaxies/ncg4258 HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

HTTP/1.1 200 OK Content-Length: 207 Content-Type: application/json; charset=UTF-8

{ "name": "Messier 106", "ngc_id": 4258, "type": "SAB(s)bc", "size": 135000, "_links": { "self": { "href": "/groups/local/galaxies/ngc4258" } }, "group": { "href": "/groups/local" } } } }

HEAD

Request the representation metadata and control data for a resource with a given identifier

SafeIdempotent

GET /groups/local/galaxies/ncg4258 HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

HTTP/1.1 200 OK Content-Length: 207 Content-Type: application/json; charset=UTF-8

TRACE

Request the server respond by echoing the request.

SafeIdempotent

TRACE /groups/local/galaxies/ncg4258 HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

HTTP/1.1 200 OK Content-Type: message/http Content-Length: 39

TRACE /groups/local/galaxies/ncg4258 HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

OPTIONS

Request the server respond with information about what methods are allowed for a resource.

SafeIdempotent

OPTIONS /groups/local/galaxies/ncg4258 HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

HTTP/1.1 200 OK Content-Type: message/http Content-Length: 39 Allow: GET,HEAD,DELETE,POST,OPTIONS,TRACE

DELETE

Request the server delete the resource.

UnsafeIdempotent

DELETE /groups/local/galaxies/ncg4258 HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

HTTP/1.1 204 No Content

PUT

Request the server store a provided representation of a resource at the specified name, replacing the existing resource if it exists.

UnsafeIdempotent

PUT /groups/local/galaxies/ncg4258 HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

{ "name": "Messier 106", "ngc_id": 4258, "type": "SAB(s)bc", "size": 135000, “example_type": "contrived", "_links": { "self": { "href": "/groups/local/galaxies/ngc4258" } }, "group": { "href": "/groups/local" } } } }

HTTP/1.1 204 No Content

POST

Request the server store a provided representation of a resource as a new member of the collection identified by the resource name

UnsafeNot Idempotent

POST /groups/local/galaxies HTTP/1.1 Host: galaxies.tembies.com Content-Type: application/json; charset=UTF-8

{ "name": "Messier 51a", "ngc_id": 5194, "type": “SA(s)bc pec", "size": 60000, }

HTTP/1.1 201 Created Location: /groups/local/galaxies/ngc4258 { "_links": {

"self": { "href": "/groups/local/galaxies/ngc4258" } } } }

PUT vs POST

or How Yelling Loudly Can Make a

Difference

PUT

Create or replace… a Resource or collection

Can be repeated… safely

POST

Append to a collection

Can not be repeated… safely

Idempotency

ServerClient

PUTPUTPUT

Idempotency

ServerClient

POSTPOSTPOST

Antipattern

A common solution to an engineering problem that is, at best ineffective, and at worst, potentially destructive.

Overloading GET (or POST)

GET /things/42?action=delete GET /widgets/42/delete GET /widgets/delete?id=42

Antipattern

Abusing Status Codes

HTTP/1.1 200 OK { "success": false, "code": "ID10T", "message": "Tweet @jakeasmith for lols" }

Antipattern

Abusing Status Codes

Antipattern

1xx - Informational

2xx - Success

3xx - Redirection

4xx - Client Error

5xx - Server Error

Relying on Session

REST APIs are Stateless

Antipattern

Not Supporting Caching

Learn to use cache headers

Antipattern

Your Humble Speaker’s Loud and Oft-Repeated Advice

Sanitize Assumptions

Patterns like REST make assumptions safer.

The further you are from the consumers of your API, the closer you should adhere to

the pattern.

Advice

Avoid Side-Effects

GET is a safe method. GET should never, never, cause side effects.

Advice

Document your APIs

REST APIs are self-documenting.

That’s a feature, not an excuse.

Advice

Understand When REST Works

Resource (noun) oriented CRUD

Open consumption Open formats

Advice

And When It Doesn’t

Action (verb) oriented RPC

Closed consumption Closed formats

Advice

After the Conference

Give Me Some Feedback!

https://joind.in/13067

Read the Dissertation

http://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm

Read the RFC

https://www.ietf.org/rfc/rfc2616.txt

Learn about Caching

http://www.mobify.com/blog/beginners-guide-to-http-cache-headers/

Check Out Some Documentation Frameworks

RAML - http://raml.org API Blueprint - http://apiblueprint.org Swagger - http://swagger.io

Consider Some Further Reading

Build APIs You Won't Hate by Phil Sturgeon RESTful Web Services by Leonard Richardson & Sam Ruby

Build an Awesome API

Easy to maintain Meets your needs Solves a problem

Tell Your Community how you built it

at a user group or a conference

Other 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)

• 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/)