nephp '12: create a restful api

49
Creating an Epic RESTful API and Conquering the World Andrew Curioso

Upload: andrew-curioso

Post on 29-Nov-2014

3.336 views

Category:

Health & Medicine


1 download

DESCRIPTION

 

TRANSCRIPT

Page 1: NEPHP '12: Create a RESTful API

Creating an Epic RESTful APIand Conquering the World

Andrew Curioso

Page 2: NEPHP '12: Create a RESTful API

Definitions

Cre·ate [kree-eyt] verb1. to cause to come into being, as

something unique that would not naturally evolve or that is not made by ordinary processes.

2. to evolve from one's own thought or imagination, as a work of art or an invention.

Source: Dictionary.com

Page 3: NEPHP '12: Create a RESTful API

Definitions

Ep·ic [ep-ik] adjective1. noting or pertaining to a long poetic

composition, usually centered upon a hero, in which a series of great achievements or events is narrated in elevated style: Homer's Iliad is an epic poem.

2. resembling or suggesting such poetry: an epic novel on the founding of the country.

3. heroic; majestic; impressively great: the epic events of the war.

4. of unusually great size or extent: a crime wave of epic proportions.

Source: Dictionary.com

Page 4: NEPHP '12: Create a RESTful API

Definitions

Rest [rest] noun1. the refreshing quiet or repose of sleep: a

good night's rest. 2. refreshing ease or inactivity after exertion or

labor: to allow an hour for rest. 3. relief or freedom, especially from anything

that wearies, troubles, or disturbs. 4. a period or interval of inactivity, repose,

solitude, or tranquility: to go away for a rest. 5. mental or spiritual calm; tranquility. 6. Representational State Transfer

Source: Dictionary.com

Page 5: NEPHP '12: Create a RESTful API

Definitions

Rest [rest] noun1. the refreshing quiet or repose of sleep: a

good night's rest. 2. refreshing ease or inactivity after exertion or

labor: to allow an hour for rest. 3. relief or freedom, especially from anything

that wearies, troubles, or disturbs. 4. a period or interval of inactivity, repose,

solitude, or tranquility: to go away for a rest. 5. mental or spiritual calm; tranquility. 6. Representational State Transfer

Source: Common Knowledge

Page 6: NEPHP '12: Create a RESTful API

Definitions

A·P·I [ey-pee-ahy] noun1. Application Programming Interface.

A contract between two applications that allows them to communicate effectively.

Source: Andrew Curioso

Page 7: NEPHP '12: Create a RESTful API

Definitions

Con·quer [kong-ker] verb1. to acquire by force of arms; win in war: to

conquer a foreign land. 2. to overcome by force; subdue: to conquer

an enemy. 3. to gain, win, or obtain by effort, personal

appeal, etc.: conquer the hearts of his audience.

4. to gain a victory over; surmount; master; overcome: to conquer disease and poverty; to conquer one's fear.

Source: Andrew Curioso

Page 8: NEPHP '12: Create a RESTful API

Definitions

World [wurld] noun1. the earth or globe, considered as a planet. 2. ( often initial capital letter ) a particular

division of the earth: the Western world. 3. the earth or a part of it, with its inhabitants,

affairs, etc., during a particular period: the ancient world.

4. humankind; the human race; humanity: The world must eliminate war and poverty.

5. the public generally: The whole world knows it.

Source: Andrew Curioso

Page 9: NEPHP '12: Create a RESTful API
Page 10: NEPHP '12: Create a RESTful API

Definitions

World [wurld] noun1. The ecosystem around your startup

or cause into which you drag your family, friends, investors, and anyone who will listen.

Source: Andrew Curioso

Page 11: NEPHP '12: Create a RESTful API

Become a platform

Internal only (closed) Multiple consumers Scalable

Semi-Private Partner Integration

External (open) Everything + Growth▪ Mash-ups!▪ Innovation▪ Evangelists

“The Platform Play”

Page 12: NEPHP '12: Create a RESTful API

Types of APIs

PATTERNS

Representation State Transfer (REST)

Remote Procedure Calls (RPC)

PROTOCOLS / FORMATS XML JSON YAML AMF Etc...

Page 13: NEPHP '12: Create a RESTful API

RESTful

Representational State Transfer Resource based (nouns) 5 verbs

GET PUT POST DELETE HEAD

Easy in PHP

Page 14: NEPHP '12: Create a RESTful API

REST Constraints

1. Client / Server2. Stateless3. Cacheable4. Layered5. Uniform Interface6. ???

Page 15: NEPHP '12: Create a RESTful API

Today’s Example App

URL shortening website User authentication (simple) Create, read, update, and delete (CRUD)

Page 16: NEPHP '12: Create a RESTful API

Models

id user_id url created modified

users urls

Page 17: NEPHP '12: Create a RESTful API

Making it RESTful

Verb URL Action

GET /urls.json List URLs

GET /urls/123.json Resource for URL with id 123

POST /urls.json Shorten a new URL

PUT /urls/123.json Edit the URL with the ID 123

DELETE /urls/123.json Delete the URL with the ID 123

POST /urls/123.json Also edit the URL with the ID 123

Page 18: NEPHP '12: Create a RESTful API

Handling Request with PHP<?php if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) { ... }?>

Page 19: NEPHP '12: Create a RESTful API

Security Pitfall

Only you can prevent CSRF Only POST and PUT should write data Only POST and DELETE should delete

data Check Referrer Per request tokens

Page 20: NEPHP '12: Create a RESTful API

Content Negotiation

HTTP Accepts Mime Types

Page 21: NEPHP '12: Create a RESTful API

Json

Simple Fast Wide-spread Mime: application/json

<?php echo json_encode( $urlObject );?>

Page 22: NEPHP '12: Create a RESTful API

JsonP

P w/ padding Uses callback Cross domain Mime: application/javascript

if ( array_key_exists('callback’, $_GET) ) $callbackFunc = $_GET['callback'];else $callbackFunc = false;

if ( $callbackFunc !== false ) echo $callbackFunc.'(';

echo json_encode( $urlObject );

if ( $callbackFunc ) echo ')'; ?>

Page 23: NEPHP '12: Create a RESTful API

XML

Strongly Typed Human readable Lots of existing tools Mime: application/xml

<?php ...?>

Page 24: NEPHP '12: Create a RESTful API

Other Formats

HUMAN READABLE

XML Json / JsonP HTML YAML CSV Serialized PHP Etc…

BINARY

AMF Microsoft Excel PDF JPEG / PNG Etc…

Page 25: NEPHP '12: Create a RESTful API

Testing It Out Using cURL

curl –d “url=www.example.com” http://tinyr.me/urls.json

Create

curl http://tinyr.me/urls/123.json

Read

curl –d “url=www.example.com/foo” http://tinyr.me/urls/123.json

Update

curl –X DELETE http://tinyr.me/urls/123.json

Delete

Page 26: NEPHP '12: Create a RESTful API

Done?

WE HAVE

Request handling RESTful Output

Formats XML Json / JsonP

WE’RE MISSING

Error handling Pagination Authentication Authorization Documentation

Page 27: NEPHP '12: Create a RESTful API

Status Codes

Success 200 OK * 201 Created * 303 See Other *

Error 401 Unauthorized * 402 Payment

Required 403 Forbidden * 404 Not Found *

Error (continued) 405 Method Not

Allowed * 409 Conflict 410 Gone 500 Internal Server

Error * 501 Not Implemented 503 Service

Unavailable

Page 28: NEPHP '12: Create a RESTful API

Add

If not a POST request 405 Method Not Allowed

Already existed 303 See Other

Save success 201 Created

Failure 500 Internal Server Error with

explanation

Page 29: NEPHP '12: Create a RESTful API

Edit

If not a POST or PUT request 405 Method Not Allowed

Invalid ID 404 File Not Found

Success 200 OK

Failure 500 Internal Server Error with

explanation

Page 30: NEPHP '12: Create a RESTful API

Delete

If not a POST or DELETE request 405 Method Not Allowed

Invalid ID 404 File Not Found

Success 200 OK

Failure 500 Internal Server Error with

explanation

Page 31: NEPHP '12: Create a RESTful API

Global

User is not allowed to access resource 403 Forbidden

User is not logged in 401 Unauthorized

Page 32: NEPHP '12: Create a RESTful API

Throwing Errors

Same format Descriptive

Human Computer

Comprehensive

Page 33: NEPHP '12: Create a RESTful API

Implementation

{"Error": { "code" : 404, "description" : "File Not Found"}}

Page 34: NEPHP '12: Create a RESTful API

HTTP Headers

Return meta-information Rate limiting Pagination Expiration / cache Etc.

Page 35: NEPHP '12: Create a RESTful API

Pagination

Uses HTTP headers App defined “used to” start with “X-”

header(“X-Current-Page: ”.$currentPage);header(“X-Total: ”.$total);header(“X-Per-Page: ”.$perPage);

Page 36: NEPHP '12: Create a RESTful API

Platform Support

SOME PLATFORMS (LIKE MANY WEB BROWSERS)

Do not support: DELETE PUT

FORTUNATELY…

You can/should do this:

_method=DELETE

Page 37: NEPHP '12: Create a RESTful API

Platform Support

DELETE /urls/123.json HTTP1.1Host: www.example.com

POST /urls/123.json HTTP1.1Host: www.example.com

_method=DELETE

Page 38: NEPHP '12: Create a RESTful API

Authentication

Page 39: NEPHP '12: Create a RESTful API

Authorization

There are no shortcuts One or more:

All Users (public) Owner Shared User Moderator Administrator

Page 40: NEPHP '12: Create a RESTful API

Documentation

Vocabularies / Schemas DTD or schema files

Examples Code I/O

Community Feedback WSDL 2.0

Page 41: NEPHP '12: Create a RESTful API

What about SOAP and AMF?

PHP rocks with REST SOAP is heavy AMF is light but requires Flash But, if you still want to, you can

Page 42: NEPHP '12: Create a RESTful API

Example Flow

Gateway

REST API

REST request

User

POST

ResponseREST request

Aka the Façade Pattern

Page 43: NEPHP '12: Create a RESTful API

Some final words…

Page 44: NEPHP '12: Create a RESTful API

Caching and Scaling

Built-in to HTTP Expires Last-Modified Cache-Control Etag▪ If-None-Match

Stateless

Page 45: NEPHP '12: Create a RESTful API

HATEOAS

Hypermedia as the Engine of Application State

Roy Thomas Fielding

Page 46: NEPHP '12: Create a RESTful API

Contract

Page 47: NEPHP '12: Create a RESTful API

What about conquering the world?

Page 48: NEPHP '12: Create a RESTful API

API Developers Checklist

REST constraints Documentation Security Unit tests

Page 49: NEPHP '12: Create a RESTful API

Andrew Curioso

Contact: www.AndrewCurioso.com/contact @AndrewCurioso on Twitter Careers.FreePriceAlerts.com