NEPHP '12: Create a RESTful API
-
Upload
andrew-curioso -
Category
Health & Medicine
-
view
3.336 -
download
1
description
Transcript of NEPHP '12: Create a RESTful API
Creating an Epic RESTful APIand Conquering the World
Andrew Curioso
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
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
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
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
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
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
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
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
Become a platform
Internal only (closed) Multiple consumers Scalable
Semi-Private Partner Integration
External (open) Everything + Growth▪ Mash-ups!▪ Innovation▪ Evangelists
“The Platform Play”
Types of APIs
PATTERNS
Representation State Transfer (REST)
Remote Procedure Calls (RPC)
PROTOCOLS / FORMATS XML JSON YAML AMF Etc...
RESTful
Representational State Transfer Resource based (nouns) 5 verbs
GET PUT POST DELETE HEAD
Easy in PHP
REST Constraints
1. Client / Server2. Stateless3. Cacheable4. Layered5. Uniform Interface6. ???
Today’s Example App
URL shortening website User authentication (simple) Create, read, update, and delete (CRUD)
Models
id user_id url created modified
users urls
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
Handling Request with PHP<?php if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) { ... }?>
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
Content Negotiation
HTTP Accepts Mime Types
Json
Simple Fast Wide-spread Mime: application/json
<?php echo json_encode( $urlObject );?>
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 ')'; ?>
XML
Strongly Typed Human readable Lots of existing tools Mime: application/xml
<?php ...?>
Other Formats
HUMAN READABLE
XML Json / JsonP HTML YAML CSV Serialized PHP Etc…
BINARY
AMF Microsoft Excel PDF JPEG / PNG Etc…
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
Done?
WE HAVE
Request handling RESTful Output
Formats XML Json / JsonP
WE’RE MISSING
Error handling Pagination Authentication Authorization Documentation
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
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
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
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
Global
User is not allowed to access resource 403 Forbidden
User is not logged in 401 Unauthorized
Throwing Errors
Same format Descriptive
Human Computer
Comprehensive
Implementation
{"Error": { "code" : 404, "description" : "File Not Found"}}
HTTP Headers
Return meta-information Rate limiting Pagination Expiration / cache Etc.
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);
Platform Support
SOME PLATFORMS (LIKE MANY WEB BROWSERS)
Do not support: DELETE PUT
FORTUNATELY…
You can/should do this:
_method=DELETE
Platform Support
DELETE /urls/123.json HTTP1.1Host: www.example.com
POST /urls/123.json HTTP1.1Host: www.example.com
_method=DELETE
Authentication
Authorization
There are no shortcuts One or more:
All Users (public) Owner Shared User Moderator Administrator
Documentation
Vocabularies / Schemas DTD or schema files
Examples Code I/O
Community Feedback WSDL 2.0
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
Example Flow
Gateway
REST API
REST request
User
POST
ResponseREST request
Aka the Façade Pattern
Some final words…
Caching and Scaling
Built-in to HTTP Expires Last-Modified Cache-Control Etag▪ If-None-Match
Stateless
HATEOAS
Hypermedia as the Engine of Application State
Roy Thomas Fielding
Contract
What about conquering the world?
API Developers Checklist
REST constraints Documentation Security Unit tests
Andrew Curioso
Contact: www.AndrewCurioso.com/contact @AndrewCurioso on Twitter Careers.FreePriceAlerts.com