Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Cakefest 2010: API Development

4,149 views

Published on

Published in: Entertainment & Humor
  • Be the first to comment

Cakefest 2010: API Development

  1. 1. API Development<br />Becoming the Platform<br />(CakePHP for Back-End Development<br />or Cake for Web Services)<br />By Andrew Curioso<br />CakeFest<br />2010<br />
  2. 2. Introduction<br />Yesterday: <br />Designing CakePHPplug-ins for consuming APIs<br />Today:<br />Create your own API<br />Basic setup<br />Extras<br />
  3. 3. Become a platform<br />Be “a” platform<br />A blog is a platform<br />
  4. 4. Become a platform<br />Internal only (closed)<br />Multi-platform (consumers)<br />Scalable<br />External (open)<br />Everything +<br />Growth<br />Mash-ups!<br />Innovation<br />Evangelists<br />“The Platform Play”<br />
  5. 5. Who’s already a platform<br />Google<br />Facebook<br />Digg<br />Twitter<br />Yahoo BOSS / Flickr / Delicious / etc.<br />Salesforce<br />Ebay<br />Amazon<br />Gowalla<br />FourSquare<br />Bit.ly<br />Paypal<br />Authorize.net<br />Etc…<br />
  6. 6. Types of APIs<br />Patterns<br />Representation State Transfer (REST)<br />Remote Procedure Calls (RPC)<br />Protocols / Formats<br />XML<br />JSON<br />YAML <br />AMF<br />Etc...<br />
  7. 7. RESTful<br />Representational State Transfer<br />Resource based (nouns)<br />5 verbs<br />GET<br />PUT<br />POST<br />DELETE<br />HEAD<br />Easy in CakePHP<br />
  8. 8. Today’s App<br />URL shortening website<br />User authentication (simple)<br />Create, read, update, and delete (CRUD)<br />
  9. 9. Models<br />id<br />user_id<br />url<br />created<br />modified<br />users<br />urls<br />
  10. 10. Making it RESTful<br />APP/config/routes.php<br />Router::mapResource(‘users’)<br />Source: http://book.cakephp.org/view/1239/The-Simple-Setup<br />
  11. 11. Security Pitfall<br /><ul><li>Only you can prevent CSRF</li></ul>Only POST and PUT should write data<br />Only POST and DELETE should delete data<br />
  12. 12. Mapping Extensions<br />Router::parseExtensions()<br />RequestHandler component<br />Switches layouts / views<br />Includes helpers<br />Parses incoming XML on POST<br />Router::connect(<br /> "/:controller/:id”,<br /> array ("action" => "edit", "[method]" => "PUT"), array("id" => "[0-9]+”)<br />);<br />Source: http://book.cakephp.org/view/1240/Custom-REST-Routing<br />
  13. 13. Json View<br />Simple<br />Fast<br />Wide-spread<br /><?php<br /> echo json_encode( $url );<br />?><br />APP/views/urls/json/view.ctp<br />
  14. 14. JsonP<br />P w/ padding<br />Uses callback<br />Cross domain<br /><?php<br /> if ( $callbackFunc !== false )<br />echo $callbackFunc.'(';<br /> echo $content_for_layout;<br />if ( $callbackFunc)<br /> echo $callbackFunc.')';<br />?><br />function beforeFilter()<br />{<br /> if ( array_key_exists('callback’, $this->params[‘url’]) )<br /> $this->set(‘callbackFunc’, $this->params[‘url’][‘callback’]);<br /> else<br /> $this->set(‘callbackFunc’, false);<br />}<br />APP/views/layouts/json/default.ctp<br />APP/app_controller.php<br />
  15. 15. XML View<br />Strongly Typed<br />Human readable<br />Lots of existing tools<br /><?<br /> echo ‘<url>’;<br /> echo $xml->serialize( $url );<br /> echo ‘<url>’;<br />?><br />APP/views/urls/xml/view.ctp<br />
  16. 16. Other Views<br />Human Readable<br />XML<br />Json / JsonP<br />HTML<br />YAML<br />CSV<br />Serialized PHP<br />Etc…<br />Binary<br />AMF<br />Microsoft Excel<br />PDF<br />JPEG / PNG<br />Etc…<br />
  17. 17. Testing It Out Using cURL<br />Create<br />curl –d “url=www.example.com” http://tinyr.me/urls.json<br />Read<br />curl http://tinyr.me/urls/123.json<br />Update<br />curl –d “url=www.example.com/foo” http://tinyr.me/urls/123.json<br />Delete<br />curl –X DELETE http://tinyr.me/urls/123.json<br />
  18. 18. Done?<br />We have<br />MVC files<br />RESTful Views<br />XML<br />Json / JsonP<br />We’re missing<br />Error handling<br />Pagination<br />Authentication<br />Authorization<br />Documentation<br />
  19. 19. Status Codes<br />Success<br />200 OK *<br />201 Created *<br />303 See Other *<br />Error<br />401 Unauthorized *<br />402 Payment Required<br />403 Forbidden *<br />404 Not Found *<br />Error (continued)<br />405 Method Not Allowed *<br />409 Conflict<br />410 Gone<br />500 Internal Server Error<br />501 Not Implemented<br />503 Service Unavailable<br />
  20. 20. Add Method<br />If not a POST or PUT request<br />405 Method Not Allowed<br />Already existed<br />303 See Other<br />Save success<br />201 Created<br />Failure<br /> 200 OK with explanation<br />
  21. 21. Edit Method<br />If not a POST request<br />405 Method Not Allowed<br />Invalid ID<br />404 File Not Found<br />Success<br />200 OK<br />Failure<br />200 OK with explanation<br />
  22. 22. Delete Method<br />If not a POST request<br />405 Method Not Allowed<br />Invalid ID<br />404 File Not Found<br />Success<br />200 OK<br />Failure<br />200 OK with explanation<br />
  23. 23. Global<br />User is not allowed to access resource<br />403 Forbidden<br />User is not logged in<br />401 Unauthorized<br />
  24. 24. Throwing Errors<br />Same format<br />Descriptive<br />Human<br />Computer<br />Comprehensive<br />
  25. 25. Implementation<br />functionyour_action() {<br /> …<br /> $this->_userError(404);<br /> …<br />}<br />APP/controllers/your_controller.php<br />function _userError( $code, $options=array() ) {<br /> $codes = array(<br /> 402 => 'Payment Required',<br /> …<br /> );<br /> $this->header("HTTP/1.1 {$type} {$codes[$type]}");<br /> $this->cakeError('error'.$type, array( array( 'options' => $options ) ) );<br />}<br />APP/app_controller.php<br />
  26. 26. Implementation<br />{"Error": {<br /> "code" : 404,<br /> "description" : "File Not Found"<br />}}<br />APP/views/errors/error404.ctp<br />
  27. 27. HTTP Headers<br />Return meta-information<br />Rate limiting<br />Pagination<br />Etc.<br />
  28. 28. Pagination<br />Uses HTTP headers<br />App defined start with “X-”<br />function paginate($object=NULL, $scope=array(), $whitelist=array() ) {<br /> $data = parent::paginate($object,$scope,$whitelist);<br /> // … messy code to get the object …<br /> $this->header('X-Current-Page: '.((int)$this->params['paging'][$object->alias]['page']));<br /> $this->header('X-Page-Limit: '.((int)$this->params['paging'][$object->alias]['options']['limit']));<br /> $this->header('X-Page-Total: '.((int)$this->params['paging'][$object->alias]['count']));<br /> return $data;<br />}<br />APP/app_controller.php<br />
  29. 29. Multi-Platform Dev<br />Use a UI that makes sense<br />Bring something to the table<br />
  30. 30. Platform Support<br />Web Browsers<br />Do not support:<br />DELETE<br />PUT<br />Fortunately Cake…<br />Let’s you do this:<br />_method=DELETE<br />
  31. 31. Platform Support<br />DELETE /urls/123.json HTTP1.1<br />Host: www.example.com<br />POST /urls/123.json HTTP1.1<br />Host: www.example.com<br />_method=DELETE<br />
  32. 32. Authentication<br />
  33. 33. Authorization<br />There is no magic<br />One or more:<br />user_id<br />Administrator<br />Moderator<br />
  34. 34. Documentation<br />Vocabularies / Schemas<br />DTD or schema files<br />Examples<br />Code<br />I/O<br />Community<br />Feedback<br />
  35. 35. What about SOAP and AMF?<br />CakePHP rocks with REST<br />SOAP is heavy<br />AMF is light but requires Flash<br />But, if you still want to, you can<br />
  36. 36. Flow for SOAP and AMF<br />
  37. 37. Example Flow<br />Router<br />UrlsController<br />AmfController<br />User<br />POST<br />::gateway()<br />::view()<br />Return data<br />Format envelope<br />
  38. 38. Some final words…<br />
  39. 39. Don’t Choose<br />Views are easy<br />
  40. 40. API Developers Checklist<br />Documentation<br />Example code<br />Definition files (if applicable)<br />Unit tests<br />
  41. 41. Finding the code<br />MIT License<br />http://tinyr.me<br />
  42. 42. Happy Aniversary<br />Happy anniversary, Laura.<br />1 year: Sept. 5, 2010<br />
  43. 43. Andrew Curioso<br />Contact:<br />www.AndrewCurioso.com/contact<br />@AndrewCurioso on Twitter<br />

×