SlideShare a Scribd company logo
API DevelopmentBecoming the Platform(CakePHP for Back-End Developmentor Cake for Web Services)By Andrew CuriosoCakeFest2010
IntroductionYesterday: Designing CakePHP plug-ins for consuming APIsToday:Create your own APIBasic setupExtras
Become a platformBe “a” platformA blog is a platform
Become a platformInternal only (closed)Multi-platform (consumers)ScalableExternal (open)Everything +GrowthMash-ups!InnovationEvangelists“The Platform Play”
Who’s already a platformGoogleFacebookDiggTwitterYahoo BOSS / Flickr / Delicious / etc.SalesforceEbayAmazonGowallaFourSquareBit.lyPaypalAuthorize.netEtc…
Types of APIsPatternsRepresentation State Transfer (REST)Remote Procedure Calls (RPC)Protocols / FormatsXMLJSONYAML AMFEtc...
RESTfulRepresentational State TransferResource based (nouns)5 verbsGETPUTPOSTDELETEHEADEasy in CakePHP
Today’s AppURL shortening websiteUser authentication (simple)Create, read, update, and delete (CRUD)
Modelsiduser_idurlcreatedmodifiedusersurls
Making it RESTfulAPP/config/routes.phpRouter::mapResource(‘users’)Source: http://book.cakephp.org/view/1239/The-Simple-Setup
Security PitfallOnly you can prevent CSRFOnly POST and PUT should write dataOnly POST and DELETE should delete data
Mapping ExtensionsRouter::parseExtensions()RequestHandler componentSwitches layouts / viewsIncludes helpersParses incoming XML on POSTRouter::connect(     "/:controller/:id”,    array ("action" => "edit", "[method]" => "PUT"), array("id" => "[0-9]+”));Source: http://book.cakephp.org/view/1240/Custom-REST-Routing
Json ViewSimpleFastWide-spread<?php    echo json_encode( $url );?>APP/views/urls/json/view.ctp
JsonPP w/ paddingUses callbackCross domain<?php    if ( $callbackFunc !== false )        echo $callbackFunc.'(';    echo $content_for_layout;    if ( $callbackFunc )        echo $callbackFunc.')';   ?>function beforeFilter(){    if ( array_key_exists('callback’, $this->params[‘url’]) )        $this->set(‘callbackFunc’, $this->params[‘url’][‘callback’]);    else        $this->set(‘callbackFunc’, false);}APP/views/layouts/json/default.ctpAPP/app_controller.php
XML ViewStrongly TypedHuman readableLots of existing tools<?  echo ‘<url>’;  echo $xml->serialize( $url );  echo ‘<url>’;?>APP/views/urls/xml/view.ctp
Other ViewsHuman ReadableXMLJson / JsonPHTMLYAMLCSVSerialized PHPEtc…BinaryAMFMicrosoft ExcelPDFJPEG / PNGEtc…
Testing It Out Using cURLCreatecurl –d “url=www.example.com” http://tinyr.me/urls.jsonReadcurl http://tinyr.me/urls/123.jsonUpdatecurl –d “url=www.example.com/foo” http://tinyr.me/urls/123.jsonDeletecurl –X DELETE http://tinyr.me/urls/123.json
Done?We haveMVC filesRESTful ViewsXMLJson / JsonPWe’re missingError handlingPaginationAuthenticationAuthorizationDocumentation
Status CodesSuccess200 OK *201 Created *303 See Other *Error401 Unauthorized *402 Payment Required403 Forbidden *404 Not Found *Error (continued)405 Method Not Allowed *409 Conflict410 Gone500 Internal Server Error501 Not Implemented503 Service Unavailable
Add MethodIf not a POST request405 Method Not AllowedAlready existed303 See OtherSave success201 CreatedFailure 200 OK with explanation
Edit MethodIf not a POST or PUT request405 Method Not AllowedInvalid ID404 File Not FoundSuccess200 OKFailure200 OK with explanation
Delete MethodIf not a POST or DELETE request405 Method Not AllowedInvalid ID404 File Not FoundSuccess200 OKFailure200 OK with explanation
GlobalUser is not allowed to access resource403 Forbidden User is not logged in401 Unauthorized
Throwing ErrorsSame formatDescriptiveHumanComputerComprehensive
Implementationfunction your_action() {  …  $this->_userError(404);  …}APP/controllers/your_controller.phpfunction _userError( $code, $options=array() ) {  $codes = array(    402 => 'Payment Required',    …  );  $this->header("HTTP/1.1 {$type} {$codes[$type]}");  $this->cakeError('error'.$type, array( array( 'options' => $options ) ) );}APP/app_controller.php
Implementation{"Error": {  "code" : 404,  "description" : "File Not Found"}}APP/views/errors/error404.ctp
HTTP HeadersReturn meta-informationRate limitingPaginationEtc.
PaginationUses HTTP headersApp defined start with “X-”function paginate($object=NULL, $scope=array(), $whitelist=array() ) {    $data = parent::paginate($object,$scope,$whitelist);    // … messy code to get the object …    $this->header('X-Current-Page: '.((int)$this->params['paging'][$object->alias]['page']));    $this->header('X-Page-Limit: '.((int)$this->params['paging'][$object->alias]['options']['limit']));    $this->header('X-Page-Total: '.((int)$this->params['paging'][$object->alias]['count']));    return $data;}APP/app_controller.php
Multi-Platform DevUse a UI that makes senseBring something to the table
Platform SupportWeb BrowsersDo not support:DELETEPUTFortunately Cake…Let’s you do this:_method=DELETE
Platform SupportDELETE /urls/123.json HTTP1.1Host: www.example.comPOST /urls/123.json HTTP1.1Host: www.example.com_method=DELETE
Authentication
AuthorizationThere is no magicOne or more:user_idAdministratorModerator
DocumentationVocabularies / SchemasDTD or schema filesExamplesCodeI/OCommunityFeedback
What about SOAP and AMF?CakePHP rocks with RESTSOAP is heavyAMF is light but requires FlashBut, if you still want to, you can
Flow for SOAP and AMF
Example FlowRouterUrlsControllerAmfControllerUserPOST::gateway()::view()Return dataFormat envelope
Some final words…
Don’t ChooseViews are easy
API Developers ChecklistDocumentationExample codeDefinition files (if applicable)Unit tests
Finding the codeMIT Licensehttp://tinyr.me
Happy AniversaryHappy anniversary, Laura.1 year: Sept. 5, 2010
Andrew CuriosoContact:www.AndrewCurioso.com/contact@AndrewCurioso on Twitter

More Related Content

What's hot (20)

KEY
Using PHP
Mark Casias
 
PDF
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
PPT
Open Source Package PHP & MySQL
kalaisai
 
PPTX
Secure PHP Coding - Part 1
Vinoth Kumar
 
PPTX
Secure PHP Coding - Part 2
Vinoth Kumar
 
PPT
Php mysql
Alebachew Zewdu
 
PPT
Introduction to PHP
Jussi Pohjolainen
 
PDF
Make WordPress realtime.
Josh Hillier
 
PPT
Php Lecture Notes
Santhiya Grace
 
PPT
PHP
webhostingguy
 
PPTX
Introduction to PHP Lecture 1
Ajay Khatri
 
PPT
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
PDF
Flask patterns
it-people
 
PPT
PHP Workshop Notes
Pamela Fox
 
PPTX
Playing nice with others
Eric Mann
 
PPT
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
PPTX
PHP Basics
Saraswathi Murugan
 
PPT
Php Calling Operators
mussawir20
 
PPTX
Oracle APEX Performance
Scott Wesley
 
PDF
Action View Form Helpers - 1, Season 2
RORLAB
 
Using PHP
Mark Casias
 
Introduction to PHP - Basics of PHP
wahidullah mudaser
 
Open Source Package PHP & MySQL
kalaisai
 
Secure PHP Coding - Part 1
Vinoth Kumar
 
Secure PHP Coding - Part 2
Vinoth Kumar
 
Php mysql
Alebachew Zewdu
 
Introduction to PHP
Jussi Pohjolainen
 
Make WordPress realtime.
Josh Hillier
 
Php Lecture Notes
Santhiya Grace
 
Introduction to PHP Lecture 1
Ajay Khatri
 
PHP - Introduction to PHP - Mazenet Solution
Mazenetsolution
 
Flask patterns
it-people
 
PHP Workshop Notes
Pamela Fox
 
Playing nice with others
Eric Mann
 
Short Intro to PHP and MySQL
Jussi Pohjolainen
 
PHP Basics
Saraswathi Murugan
 
Php Calling Operators
mussawir20
 
Oracle APEX Performance
Scott Wesley
 
Action View Form Helpers - 1, Season 2
RORLAB
 

Similar to Cakefest 2010: API Development (20)

PDF
PHP and Rich Internet Applications
elliando dias
 
PDF
Web Scraping with PHP
Matthew Turland
 
ODP
State Machines to State of the Art
Rowan Merewood
 
ODP
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
PPTX
Introduction to PHP
Collaboration Technologies
 
PPT
Framework
Nguyen Linh
 
PDF
PHP and Rich Internet Applications
elliando dias
 
PPTX
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Michael Wales
 
PPT
Php frameworks
Anil Kumar Panigrahi
 
PDF
The Django Web Application Framework
Simon Willison
 
PPT
Web Scraping with PHP
Matthew Turland
 
PPS
Php security3895
PrinceGuru MS
 
PPS
PHP Security
manugoel2003
 
ODP
B03-GenomeContent-Intermine
Bioinformatics Open Source Conference
 
PPS
Php Security3895
Aung Khant
 
PDF
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
ODP
Implementing Comet using PHP
King Foo
 
PPTX
Ellerslie User Group - ReST Presentation
Alex Henderson
 
ODP
Web Scraping with PHP
Matthew Turland
 
PPT
Introduction To Lamp
Amzad Hossain
 
PHP and Rich Internet Applications
elliando dias
 
Web Scraping with PHP
Matthew Turland
 
State Machines to State of the Art
Rowan Merewood
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
vvaswani
 
Introduction to PHP
Collaboration Technologies
 
Framework
Nguyen Linh
 
PHP and Rich Internet Applications
elliando dias
 
Introduction to CodeIgniter (RefreshAugusta, 20 May 2009)
Michael Wales
 
Php frameworks
Anil Kumar Panigrahi
 
The Django Web Application Framework
Simon Willison
 
Web Scraping with PHP
Matthew Turland
 
Php security3895
PrinceGuru MS
 
PHP Security
manugoel2003
 
B03-GenomeContent-Intermine
Bioinformatics Open Source Conference
 
Php Security3895
Aung Khant
 
Bootstrat REST APIs with Laravel 5
Elena Kolevska
 
Implementing Comet using PHP
King Foo
 
Ellerslie User Group - ReST Presentation
Alex Henderson
 
Web Scraping with PHP
Matthew Turland
 
Introduction To Lamp
Amzad Hossain
 
Ad

Recently uploaded (20)

PDF
Wondla_204_55_version11_Editedforfolio_.pdf
Giovanny Cardenas
 
PPTX
一比一还原日本工业大学毕业证/NIT毕业证书2025原版定制成绩单
e7nw4o4
 
PDF
Wedding Planners in India | Weddings & !
Weddingsandeventsbyamitesh
 
PPTX
PPP;O'P;IYHFDSDFGYUIKHTLIUYHGDFGHJILUYGT.pptx
dilludcruz
 
PPTX
Season 14 Comes to a Beautiful Close – A Heartfelt Tribute to the Dreams, Str...
Mrs India Worldwide
 
PDF
TAIPANQQ SITUS MUDAH MENANG DAN MUDAH MAXWIN SEGERA DAFTAR DI TAIPANQQ DAN RA...
TAIPANQQ GACOR
 
PPTX
TQM Report.pptx How to Improve your self
ellengracedecir10099
 
PPTX
EXP 401- On farm Advisory for Soil Health, Water Quality and Plant Nutrition....
AbedhSabu
 
PPTX
电子版本制作约克圣约翰大学毕业证学历认证学位证展示学历学位证制作
6b9ab940
 
PPTX
90's Kallinvhvhvugguygubibiytggjrbkg.pptx
bhaswatideka11
 
PPTX
Types_of_Shoes_in_Ghana we have many of t
sheilababy2014
 
PDF
Chennai Female Emcee Jenifer Jayamani Profile Managed by Chennai Event Emcees...
Chennai Event Emcees
 
PPTX
Problem-Solving-Involving-Sequences.pptx
dominicdaltoncaling2
 
PDF
Chennai Female Emcee VJ Shakti Priya Profile Managed by Chennai Event Emcees ...
Chennai Event Emcees
 
PPTX
CODE REDPOIUYTRESDAZDXFGHJKLIUYTRDF.pptx
dilludcruz
 
PDF
The Science Behind Viral Growth on TikTok_ Trends, Timing & Engagement.pdf
revathimsr06
 
PPTX
Entrepreneurship innovator Chapter 1-PPT.pptx
ahmed5156
 
PPTX
Theatre of the Absurd: Understanding the Philosophy Behind Absurdist Drama
maxmag791
 
PDF
Chennai Male Emcee Vignesh Profile Managed by Chennai Event Emcees and Entert...
Chennai Event Emcees
 
PPTX
Concluding Season 14 of Haut Monde Mrs. India Worldwide – A Milestone in Empo...
Mrs India Worldwide
 
Wondla_204_55_version11_Editedforfolio_.pdf
Giovanny Cardenas
 
一比一还原日本工业大学毕业证/NIT毕业证书2025原版定制成绩单
e7nw4o4
 
Wedding Planners in India | Weddings & !
Weddingsandeventsbyamitesh
 
PPP;O'P;IYHFDSDFGYUIKHTLIUYHGDFGHJILUYGT.pptx
dilludcruz
 
Season 14 Comes to a Beautiful Close – A Heartfelt Tribute to the Dreams, Str...
Mrs India Worldwide
 
TAIPANQQ SITUS MUDAH MENANG DAN MUDAH MAXWIN SEGERA DAFTAR DI TAIPANQQ DAN RA...
TAIPANQQ GACOR
 
TQM Report.pptx How to Improve your self
ellengracedecir10099
 
EXP 401- On farm Advisory for Soil Health, Water Quality and Plant Nutrition....
AbedhSabu
 
电子版本制作约克圣约翰大学毕业证学历认证学位证展示学历学位证制作
6b9ab940
 
90's Kallinvhvhvugguygubibiytggjrbkg.pptx
bhaswatideka11
 
Types_of_Shoes_in_Ghana we have many of t
sheilababy2014
 
Chennai Female Emcee Jenifer Jayamani Profile Managed by Chennai Event Emcees...
Chennai Event Emcees
 
Problem-Solving-Involving-Sequences.pptx
dominicdaltoncaling2
 
Chennai Female Emcee VJ Shakti Priya Profile Managed by Chennai Event Emcees ...
Chennai Event Emcees
 
CODE REDPOIUYTRESDAZDXFGHJKLIUYTRDF.pptx
dilludcruz
 
The Science Behind Viral Growth on TikTok_ Trends, Timing & Engagement.pdf
revathimsr06
 
Entrepreneurship innovator Chapter 1-PPT.pptx
ahmed5156
 
Theatre of the Absurd: Understanding the Philosophy Behind Absurdist Drama
maxmag791
 
Chennai Male Emcee Vignesh Profile Managed by Chennai Event Emcees and Entert...
Chennai Event Emcees
 
Concluding Season 14 of Haut Monde Mrs. India Worldwide – A Milestone in Empo...
Mrs India Worldwide
 
Ad

Cakefest 2010: API Development

Editor's Notes

  • #2: Who am I.Introduce myVBO.About this presentation.What I’ll talk about.
  • #3: Neil – plugins to consumeNot much code.Overview.All the slides will be online right after lunch.
  • #4: Raise your hand up if you use CakePHP to handle some kind of data.Now put your hand down if you don’t have an API.If you have info why not be a platform?It doesn’t matter if the platform is very simple. A blog is a platform. It has an API for posting new articles and it has an RSS feed for syndicating them.Now that I simplified it.That’s my take.
  • #5: Even if you are developing a closed API…I hope everyone considers open APIs.All this roles up into one concept. “The platform play.” So if you need something to go back to your boss or your investors with… that’s the thing. You’re making a platform play.
  • #6: If this was five years ago...But the strategy works pretty well. TwitterFacebookBit.lyAmazonandSalesforceNow it is almost a necessity to have an API of some sort.
  • #7: There are multiple patterns for APIs. There are a couple more lesser used ones but the two big ones are REST and RPC.Within those patterns you can use one or more formats to transfer your data.
  • #8: Rest stands for Representational State Transfer incase you missed it in Neal’s presentation. As mentioned yesterday, the largest example of REST in the wild is HTTP.Luckily for us, CakePHP is usually layered on-top of HTTP so it inherits all the RESTful mechanisms.REST has a concept called resources (a specific user or comment are two examples).They are also called nouns which are acted on by verbs.There are five verbs in HTTP. We will focus on three.Finally, one last important thing… CakePHP makes REST easy.
  • #9: The app that I will be using as an example today is the simplest app that I could think of.It is a URL shortening services that allows you to authenticate and thus be able to delete and edit URLs that you yourself shortened, and also basic CRUD.
  • #10: There are two models. The user model, which is pretty standard for a CakePHP project, and the urls model which I have on the screen.A full URL shortened can, of course, get much more complicated than that. But for today I’m keeping it basic.
  • #11: Once you’ve baked your model and what not you can open up your router and map the resource. This will register all the routes you need for REST in one call.You can still do it manually if you want but you don’t have to.These are the six routes registered when you map a resource.
  • #12: One rule to live by is to never write or delete data on anything that is not a POST, PUT, or DELETE request.The main purpose of this rule is to protect against Cross Site Request Forgeries or CSRF attacks which are every difficult to defend against otherwise.Say that the add method accepted GET requests. Someone could then simply embed an image on a page with the add URL as a source and execute a add() as any user who visits the site.
  • #13: Before we begin developing views we’ll haveto tell PHP to recognize file extensions and switch the views and layouts accordingly.We do this by turning on parseExtensions in the routes.php file and including the RequestHandler component in the app_controller.The RequestHandler component is what actually switches the views. It also includes helpers automatically in the view if a helper has the same name as the extension (like XML) and parses incoming POSTed XML and assigns it to the data property of the controller.
  • #14: We now need to create a couple views.The Json view is the first and the one that I like the most. Because it is simple and easy to understand.It is fast thanks to native PHP support, and also very wide-spread.What you see here is the entire view for the view action in the urls controller.Notice the path to the view. The RequestHandler will tell Cake to look in the json folder for the appropriate view.
  • #15: We can also easily support JsonP or Json with padding.JsonP specifies a Javascript callback function to execute with the results of a request.It allows for cross domain requests because you can trigger it via a simple script-include and function calls works across domains so the callback will work just fine.One important note is that it is only for GET requests. So, as I said earlier, it shouldn’t be able to write or delete data.JsonP can be handle generically in the layout. Notice the layout path.A JsonP request always takes the callback via a query parameter. So your app controller can read in the callback then set it for use in the view. The layout then reads it sand wraps the output in it is necessary.
  • #16: Now for the XML view. And I can hear the boos now.XML does have some benefits. It is strongly typed, human readable, and has lots of existing tools available.Like Json, the view is pretty self-explanatory. Note the xml sub-directory in the view path.
  • #17: One of the best parts about using parseExtensions and RequestHandler is you can literally have as many views as you want into the data.I listed just some of them here.
  • #22: Erik’s talk.
  • #24: If you did the ACL stuff Erik was talking about…Little difficult. Default behavior is redirectController, model, and object
  • #28: Maintenance mode