SlideShare una empresa de Scribd logo
1 de 97
Descargar para leer sin conexión
RESTful API Design & Implementation with
     CodeIgniter PHP Framework
           2012 PHP Conference
Who Am I

   Bo-Yi Wu
   @appleboy
   http://blog.wu-boy.com

  任職於瑞昱半導體 RealTek(IC Design House)
  - TV 多媒體部門
  - Sencha Touch 2, Backbone.js, CodeIgniter,
    Node.js, MongoDB, MySQL, Twitter Bootstrap,
    Twitter Hogan ...

                      2012 PHPConf                2
Who Am I
●   Open Source Contributions (github: appleboy)
    –   CodeIgniter-Native-Session
    –   CodeIgniter-i18n
    –   CodeIgniter-Template
    –   CodeIgniter-Nexmo-Message
    –   CodeIgniter-TextMagic-API




                           2012 PHPConf            3
My Focus
●   CodeIgbiter 3.0.x develop branch
    –   Support Native Session
    –   Support HMVC
    –   Support Sparks Package Management System
●   Laravel develop branch
●   Javascript (Node.js, Socket.io, Express,
    Backbone.js)


                          2012 PHPConf             4
Outline
● Restful API Basic
● API Design


● Implementing API with CodeIgniter


● Verify your API




                2012 PHPConf          5
Restful API Basic


       2012 PHPConf   6
Why Use Restful?




          Restful API Service



                Database
                2012 PHPConf
             (MySQL,MongoDB)    7
What is REST? Http Method

●   POST
●   GET
●   PUT
●   DELETE
●   OPTIONS

              Define in RFC 2616


                    2012 PHPConf   8
並非所有的瀏覽器都支援
    PUT, DELETE
  http://api.jquery.com/jQuery.ajax/



               2012 PHPConf            9
如何解決未支援的瀏覽器


    2012 PHPConf   10
<input type='hidden' name='type' value='PUT'>




                   2012 PHPConf            11
將 PUT,DELETE 一併寫成 POST API



           2012 PHPConf   12
REST Response Format?
●   JSON*
●   XML
●   Array
●   Html
●   CSV




             2012 PHPConf   13
現在皆以 JSON 為主
  格式簡單 , 相容性高 , 閱讀方便



         2012 PHPConf   14
Javascript Object Notation


  {
       key1: 'value1',
       key2: 20121103
       key3: [1,2,3]
  }

               2012 PHPConf   15
JSON in Javascript is familiar


        var object = {
          key1: 'value1',
          key2: 20121103
          key3: [1,2,3]
        }
                 2012 PHPConf    16
JSON in PHP (encode)

         PHP                             Outputs
<?php
echo json_encode(array(                  {key: 'value'}
    'key' => 'value'
));




                          2012 PHPConf                    17
JSON in PHP (decode)

               PHP                         Outputs
<?php
$json_data = '{key: value}';            array(
                                             'key' => 'value'
echo json_decode({                      );
      'key' => 'value'
});



                         2012 PHPConf                           18
你不可不知的 JSON 基本介紹
     http://goo.gl/Wvhwb




          2012 PHPConf     19
API Design

    2012 PHPConf   20
良好的 API 設計
●   Simple 簡單
●   Intuitive 直觀的
●   Stable 穩定
●   Well Document 線上文件




                    2012 PHPConf   21
Using Facebook API


       2012 PHPConf   22
Fucking Stable and Document




           2012 PHPConf   23
請務必撰寫 API 線上文件


      2012 PHPConf   24
大家每天在花在討論的時間太長
   Debug 時間變少


      2012 PHPConf   25
良好的文件減少人與人溝通成本
     團隊合作




      2012 PHPConf   26
Http Method   RFC 2616


           CRUD                     Method
●   Create                     ●   POST
●   Read                       ●   GET
●   Update                     ●   PUT
●   Delete                     ●   DELETE




                    2012 PHPConf             27
API URL Define

     2012 PHPConf   28
/API/Module/Method


       2012 PHPConf   29
Format 1: Topic Module

● /API/Topic/Add
● /API/Topic/Update


● /API/Topic/Delete


● /API/Topic/List




               2012 PHPConf   30
Format 2: Topic Module

● /API/Topic/Add
● /API/Topic/Update/1234


● /API/Topic/Delete/1234


● /API/Topic/List/sort/asc




               2012 PHPConf   31
個人偏好格式 1

   2012 PHPConf   32
不用記住多種不同 API 格式


      2012 PHPConf   33
API Response Format


        2012 PHPConf   34
請勿常常修改 format
     ( 除非你想黑掉 )




       2012 PHPConf   35
Example Create API

          Input                          Output
var object = {               {
   title: 'value1',                  title: 'value1',
   type: 'value2',                   type: 'value2',
   user_id: '1000'                   user_id: '1000',
};                                   success_text: 'ok'
                             }

           http://site.com/API/Topic/Add
                      2012 PHPConf                        36
Example Create API

           Input                         Output
var object = {               {
   title: 'value1',                  title: 'value1',
   type: 'value2'                    type: 'value2',
};                                   user_id: '1000',
                                     success_text: 'ok'
                             }

        http://site.com/API/Topic/Add/1000
                      2012 PHPConf                        37
Example Update API

           Input                         Output
var object = {               {
   id: '1000',                       id: '1000',
   title: 'value1',                  title: 'value1',
   type: 'value2'                    type: 'value2',
};                                   success_text: 'ok'
                             }

          http://site.com/API/Topic/Update
                      2012 PHPConf                        38
Example Update API

           Input                         Output
var object = {               {
   title: 'value1',                  id: '1000',
   type: 'value2'                    title: 'value1',
};                                   type: 'value2',
                                     success_text: 'ok'
                             }

        http://site.com/API/Topic/Update/1000
                      2012 PHPConf                        39
Example Delete API (single)

         Input                          Output
var object = {              {
   id: 1000                         id: '1000',
};                                  success_text: 'ok'
                            }



         http://site.com/API/Topic/Delete
                     2012 PHPConf                        40
Example Delete API (multiple)

         Input                           Output
var object = {               {
   id: [1000, 1001]                  id: '1000',
};                                   success_text: 'ok'
                             }



         http://site.com/API/Topic/Delete
                      2012 PHPConf                        41
Example Delete API

          Input                         Output
var object = {              {
                                    id: '1000',
};                                  success_text: 'ok'
                            }



        http://site.com/API/Topic/Delete/1000
                     2012 PHPConf                        42
Example Read API (Single)

         Input                            Output
var object = {               {
   id: 1000                          id: '1000',
};                                   success_text: 'ok',
                                     item: {
                                        title: 'Kate Upton'
                                     }
                             }
            http://site.com/API/Topic/List
                      2012 PHPConf                        43
Example Search API (Multiple)

         Input              {            Output
var object = {                      id: '1000',
   q: 'Kate Upton'                  success_text: 'ok',
};                                  items: [
                                       {title: 'I am kate'},
                                       {title: 'I am Upton'}
                                    ]
                         }
           http://site.com/API/Topic/List
                     2012 PHPConf                        44
Kate                  Upton



       2012 PHPConf      45
多虧了 Youtube API 讓我在上班時增加了很多動力




            2012 PHPConf   46
How to handle versioning?



           2012 PHPConf   47
內部 API 大改版

    2012 PHPConf   48
Old: http://site.com/v1/API/Topic/Add
New: http://site.com/v2/API/Topic/Add



                2012 PHPConf       49
利用 URI Routing 功能
Framework or mod_rewrite


          2012 PHPConf   50
http://site.com/API/Topic/Add

               = 
http://site.com/v1/API/Topic/Add

              2012 PHPConf         51
API Implementation


       2012 PHPConf   52
不用自己造輪子

   2012 PHPConf   53
Phil Sturgeon’s
        CodeIgniter REST Server
http://github.com/philsturgeon/codeigniter-restserver



                       2012 PHPConf                54
Requirements
●   PHP 5.2 or greater
●   CodeIgniter 2.1.x to 3.0-dev




                         2012 PHPConf   55
How to install?

      2012 PHPConf   56
Installation
●   Drag and drop the following files into your
    application's directories
    –   application/libraries/Format.php
    –   application/libraries/REST_Controller.php
    –   application/config/rest.php




                            2012 PHPConf            57
Setup the config
●   $config['rest_default_format'] = 'json';
●   $config['rest_enable_keys'] = false;
●   $config['rest_enable_logging'] = false;
●   $config['rest_enable_limits'] = false;
●   $config['rest_ajax_only'] = false;




                         2012 PHPConf          58
Include REST Controller



          2012 PHPConf   59
require(APPPATH.'/libraries/REST_Controller.php');




                      2012 PHPConf            60
Handling Requests

class Topic extends REST_Controller
{
  public function index_get() {}
  public function index_post() {}
  public function index_update() {}
  public function index_delete() {}
}


                   2012 PHPConf       61
CRUD Requests

class Topic extends REST_Controller
{
  public function list_get() {}
  public function add_post() {}
  public function update_update() {}
  public function delete_delete() {}
}


                   2012 PHPConf        62
Accessing parameters is also easy




              2012 PHPConf     63
Parameters
● GET
  – $this->get('blah');
● POST


  – $this->post('blah');
● UPDATE


  – $this->update('blah');
● DELETE


  – $this->delete('blah');
                    2012 PHPConf   64
Create API

           Input                               Output
var object = {                     {
   title: 'Kate Upton',                    id: '1000',
   text: 'Beautiful girl'                  success_text: 'ok',
};                                 }



            http://site.com/API/Topic/Add
                            2012 PHPConf                         65
Create API (POST)

public function Add_post()
{
  if (!$this->post('title')) {
      $this->response(array('error' => 'Title is required'), 404);
  }

    $output = $this->lib_topic->insert($data);

    if ($output) {
        $this->response($output, 200);
    } else {
        $this->response(array('error' => 'Insert error'), 404);
    }
}
                                2012 PHPConf                         66
Update API

           Input                               Output
var object = {                     {
   id: 1000,                               id: '1000',
   title: 'Kate Upton',                    success_text: 'ok',
   text: 'Beautiful girl'          }
};


          http://site.com/API/Topic/Update
                            2012 PHPConf                         67
Update API (PUT)

public function Update_put()
{
  if (!$this->update('id')) {
      $this->response(array('error' => 'ID is required'), 404);
  }

    $output = $this->lib_topic->update($this->update('id'), $data);

    if ($output) {
        $this->response($output, 200);
    } else {
        $this->response(array('error' => 'Insert error'), 404);
    }
}
                                2012 PHPConf                          68
Delete API

         Input                          Output
var object = {              {
   id: 1000                         id: '1000',
};                                  success_text: 'ok',
                            }



         http://site.com/API/Topic/Delete
                     2012 PHPConf                         69
Delete API (DELETE)

public function Delete_delete()
{
  if (!$this->delete('id')) {
      $this->response(array('error' => 'ID is required'), 404);
  }

    $output = $this->lib_topic->delete($this->delete('id'));

    if ($output) {
        $this->response($output, 200);
    } else {
        $this->response(array('error' => 'Insert error'), 404);
    }
}
                                2012 PHPConf                      70
Read API (GET)

          Input                            Output
var object = {                {
   id: 1000,                          id: '1000',
   type: [1, 2]                       success_text: 'ok',
};                                    item: {
                                         title: 'Kate Upton'
                                      }
                              }
             http://site.com/API/Topic/List
                       2012 PHPConf                        71
Read API (GET)

public function List_get()
{
  if (!$this->get('id') or ) {
      $this->response(array('error' => 'ID is required'), 404);
  }

    $output = $this->lib_topic->list($this->get('id'), $this->get('type'));

    if ($output) {
        $this->response($output, 200);
    } else {
        $this->response(array('error' => 'Insert error'), 404);
    }
}
                                2012 PHPConf                            72
目錄結構

 2012 PHPConf   73
Folder

 application
    controllers/
      api/
       topic.php
       user.php
       acl.php
 system
 index.php

                   2012 PHPConf   74
Routing (config/routes.php)

 Default URL http://site.com/api/topic/Add

  $route['API/Topic/(:any)'] = 'api/topic/$1';
  $route['API/User/(:any)'] = 'api/user/$1';
  $route['API/Acl/(:any)'] = 'api/acl/$1';

 New URL http://site.com/API/Topic/Add


                    2012 PHPConf                 75
Verify Your API

      2012 PHPConf   76
一樣不需要自己造輪子

    2012 PHPConf   77
Phil Sturgeon’s
         CodeIgniter REST Client
https://github.com/philsturgeon/codeigniter-restclient



                       2012 PHPConf                 78
Requirements

     2012 PHPConf   79
Requirements
●   PHP 5.1+
●   CodeIgniter 2.0.0+
●   CURL
●   CodeIgniter Curl library:
    http://getsparks.org/packages/curl/show




                         2012 PHPConf         80
Load Rest Client Library



          2012 PHPConf   81
Load Library

// Load the rest client spark
$this->load->spark('restclient/2.1.0');

// Load the library
$this->load->library('rest');




                  2012 PHPConf            82
Setup API Server

// Run some setup
$this->rest->initial('xxxxxx');

// twitter server
$this->load->initial('http://twitter.com');




                  2012 PHPConf           83
Parameter

// set api path
$api = '/API/Topic/Add';

// set api data
$data = array(
   'title' => 'I am Kate Upton',
   'type' => 'girl'
);



                  2012 PHPConf     84
Test it


// GET API
$this->rest->get($api, $data);
// POST API
$this->rest->post($api, $data);
// UPDATE API
$this->rest->update($api, $data);
// DELETE API
$this->rest->delete($api, $data);

               2012 PHPConf         85
$this->rest->debug();
     Rest Client Library debug mode




                 2012 PHPConf         86
以上是 CodeIgniter PHP Framework




            2012 PHPConf   87
Implement another Framework?




            2012 PHPConf   88
Laravel PHP Framework?



         2012 PHPConf   89
public $restful = true;

          2012 PHPConf   90
class Home_Controller extends Base_Controller
{
   public $restful = true;

    public function get_index()
    {
      //
    }

    public function post_index()
    {
      //
    }
                       2012 PHPConf         91
}
More Introduction to Laravel Framework
               14:20 – 14:50
用 Laravel Framework 打造現代化網站應用程式
                大澤木小鐵




                  2012 PHPConf         92
RESTful API 就講到這裡


       2012 PHPConf   93
如果有任何問題

   2012 PHPConf   94
可以上 CodeIgniter 論壇


        2012 PHPConf   95
http://www.codeigniter.org.tw/forum/



               2012 PHPConf       96
謝謝大家及工作團隊

    2012 PHPConf   97

Más contenido relacionado

La actualidad más candente

An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...joaomatosf_
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKJosé Paumard
 
IBM Integration Bus and REST APIs - Sanjay Nagchowdhury
IBM Integration Bus and REST APIs - Sanjay NagchowdhuryIBM Integration Bus and REST APIs - Sanjay Nagchowdhury
IBM Integration Bus and REST APIs - Sanjay NagchowdhuryKaren Broughton-Mabbitt
 
WebLogic authentication debugging
WebLogic authentication debuggingWebLogic authentication debugging
WebLogic authentication debuggingMaarten Smeets
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentationOleksii Usyk
 
OAuth 2.0 with IBM WebSphere DataPower
OAuth 2.0 with IBM WebSphere DataPowerOAuth 2.0 with IBM WebSphere DataPower
OAuth 2.0 with IBM WebSphere DataPowerShiu-Fun Poon
 
Time based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webserviceTime based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webserviceFrans Rosén
 
APIConnect Security Best Practice
APIConnect Security Best PracticeAPIConnect Security Best Practice
APIConnect Security Best PracticeShiu-Fun Poon
 
How to create a User Defined Policy with IBM APIc (v10)
How to create a User Defined Policy with IBM APIc (v10)How to create a User Defined Policy with IBM APIc (v10)
How to create a User Defined Policy with IBM APIc (v10)Shiu-Fun Poon
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?GlobalLogic Ukraine
 
Token, token... From SAML to OIDC
Token, token... From SAML to OIDCToken, token... From SAML to OIDC
Token, token... From SAML to OIDCShiu-Fun Poon
 
Swagger pour documenter votre REST API - présentation en français
Swagger pour documenter votre REST API - présentation en françaisSwagger pour documenter votre REST API - présentation en français
Swagger pour documenter votre REST API - présentation en françaisMartin Yung
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injectionMickey Jack
 
SAML VS OAuth 2.0 VS OpenID Connect
SAML VS OAuth 2.0 VS OpenID ConnectSAML VS OAuth 2.0 VS OpenID Connect
SAML VS OAuth 2.0 VS OpenID ConnectUbisecure
 
今更聞けないOAuth2.0
今更聞けないOAuth2.0今更聞けないOAuth2.0
今更聞けないOAuth2.0Takahiro Sato
 
OpenID Connect: An Overview
OpenID Connect: An OverviewOpenID Connect: An Overview
OpenID Connect: An OverviewPat Patterson
 

La actualidad más candente (20)

An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
An Overview of Deserialization Vulnerabilities in the Java Virtual Machine (J...
 
Deep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UKDeep Dive Java 17 Devoxx UK
Deep Dive Java 17 Devoxx UK
 
IBM Integration Bus and REST APIs - Sanjay Nagchowdhury
IBM Integration Bus and REST APIs - Sanjay NagchowdhuryIBM Integration Bus and REST APIs - Sanjay Nagchowdhury
IBM Integration Bus and REST APIs - Sanjay Nagchowdhury
 
WebLogic authentication debugging
WebLogic authentication debuggingWebLogic authentication debugging
WebLogic authentication debugging
 
Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Rest API
Rest APIRest API
Rest API
 
OAuth 2.0 with IBM WebSphere DataPower
OAuth 2.0 with IBM WebSphere DataPowerOAuth 2.0 with IBM WebSphere DataPower
OAuth 2.0 with IBM WebSphere DataPower
 
Time based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webserviceTime based CAPTCHA protected SQL injection through SOAP-webservice
Time based CAPTCHA protected SQL injection through SOAP-webservice
 
Java 17
Java 17Java 17
Java 17
 
APIConnect Security Best Practice
APIConnect Security Best PracticeAPIConnect Security Best Practice
APIConnect Security Best Practice
 
How to create a User Defined Policy with IBM APIc (v10)
How to create a User Defined Policy with IBM APIc (v10)How to create a User Defined Policy with IBM APIc (v10)
How to create a User Defined Policy with IBM APIc (v10)
 
“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?“How to Secure Your Applications With a Keycloak?
“How to Secure Your Applications With a Keycloak?
 
Token, token... From SAML to OIDC
Token, token... From SAML to OIDCToken, token... From SAML to OIDC
Token, token... From SAML to OIDC
 
An Introduction To REST API
An Introduction To REST APIAn Introduction To REST API
An Introduction To REST API
 
Swagger pour documenter votre REST API - présentation en français
Swagger pour documenter votre REST API - présentation en françaisSwagger pour documenter votre REST API - présentation en français
Swagger pour documenter votre REST API - présentation en français
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injection
 
SAML VS OAuth 2.0 VS OpenID Connect
SAML VS OAuth 2.0 VS OpenID ConnectSAML VS OAuth 2.0 VS OpenID Connect
SAML VS OAuth 2.0 VS OpenID Connect
 
今更聞けないOAuth2.0
今更聞けないOAuth2.0今更聞けないOAuth2.0
今更聞けないOAuth2.0
 
OpenID Connect: An Overview
OpenID Connect: An OverviewOpenID Connect: An Overview
OpenID Connect: An Overview
 
Web api
Web apiWeb api
Web api
 

Similar a RESTful API Design & Implementation with CodeIgniter PHP Framework

Api details for american syscorp
Api details for american syscorpApi details for american syscorp
Api details for american syscorpCarmor Bass
 
API Details For Ascitconsultancyservices.com
API Details For Ascitconsultancyservices.comAPI Details For Ascitconsultancyservices.com
API Details For Ascitconsultancyservices.comCarmor Bass
 
Introduction to the Pods JSON API
Introduction to the Pods JSON APIIntroduction to the Pods JSON API
Introduction to the Pods JSON APIpodsframework
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswanivvaswani
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Claire Townend Gee
 
HTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene DounarHTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene DounarMinsk PHP User Group
 
Découplez votre appli en micro-APIs
Découplez votre appli en micro-APIsDécouplez votre appli en micro-APIs
Découplez votre appli en micro-APIsNicolas Blanco
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profithanbeom Park
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinGavin Pickin
 
O365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side RenderingO365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side RenderingRiwut Libinuko
 
PHP MVC Tutorial
PHP MVC TutorialPHP MVC Tutorial
PHP MVC TutorialYang Bruce
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterHaehnchen
 
A Closer Look At React Native
A Closer Look At React NativeA Closer Look At React Native
A Closer Look At React NativeIan Wang
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For BeginnersWilson Su
 
Running gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesRunning gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesSungwon Lee
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpdayStephan Hochdörfer
 
Introducing the All New RESTful API for API Management
Introducing the All New RESTful API for API ManagementIntroducing the All New RESTful API for API Management
Introducing the All New RESTful API for API ManagementWSO2
 
[4developers2016] PHP 7 (Michał Pipa)
[4developers2016] PHP 7 (Michał Pipa)[4developers2016] PHP 7 (Michał Pipa)
[4developers2016] PHP 7 (Michał Pipa)PROIDEA
 

Similar a RESTful API Design & Implementation with CodeIgniter PHP Framework (20)

Api details for american syscorp
Api details for american syscorpApi details for american syscorp
Api details for american syscorp
 
API Details For Ascitconsultancyservices.com
API Details For Ascitconsultancyservices.comAPI Details For Ascitconsultancyservices.com
API Details For Ascitconsultancyservices.com
 
Api guide
Api guide Api guide
Api guide
 
Introduction to the Pods JSON API
Introduction to the Pods JSON APIIntroduction to the Pods JSON API
Introduction to the Pods JSON API
 
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram VaswaniCreating REST Applications with the Slim Micro-Framework by Vikram Vaswani
Creating REST Applications with the Slim Micro-Framework by Vikram Vaswani
 
Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0Swift LA Meetup at eHarmony- What's New in Swift 2.0
Swift LA Meetup at eHarmony- What's New in Swift 2.0
 
HTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene DounarHTTP Middlewares in PHP by Eugene Dounar
HTTP Middlewares in PHP by Eugene Dounar
 
Découplez votre appli en micro-APIs
Découplez votre appli en micro-APIsDécouplez votre appli en micro-APIs
Découplez votre appli en micro-APIs
 
soscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profitsoscon2018 - Tracing for fun and profit
soscon2018 - Tracing for fun and profit
 
Itb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin PickinItb 2021 - Bulding Quick APIs by Gavin Pickin
Itb 2021 - Bulding Quick APIs by Gavin Pickin
 
O365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side RenderingO365 Saturday - Deepdive SharePoint Client Side Rendering
O365 Saturday - Deepdive SharePoint Client Side Rendering
 
PHP MVC Tutorial
PHP MVC TutorialPHP MVC Tutorial
PHP MVC Tutorial
 
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years laterSymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
SymfonyCon Berlin 2016 - Symfony Plugin for PhpStorm - 3 years later
 
第26回PHP勉強会
第26回PHP勉強会第26回PHP勉強会
第26回PHP勉強会
 
A Closer Look At React Native
A Closer Look At React NativeA Closer Look At React Native
A Closer Look At React Native
 
Mirage For Beginners
Mirage For BeginnersMirage For Beginners
Mirage For Beginners
 
Running gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on KubernetesRunning gRPC Services for Serving Legacy API on Kubernetes
Running gRPC Services for Serving Legacy API on Kubernetes
 
Real World Dependency Injection - phpday
Real World Dependency Injection - phpdayReal World Dependency Injection - phpday
Real World Dependency Injection - phpday
 
Introducing the All New RESTful API for API Management
Introducing the All New RESTful API for API ManagementIntroducing the All New RESTful API for API Management
Introducing the All New RESTful API for API Management
 
[4developers2016] PHP 7 (Michał Pipa)
[4developers2016] PHP 7 (Michał Pipa)[4developers2016] PHP 7 (Michał Pipa)
[4developers2016] PHP 7 (Michał Pipa)
 

Más de Bo-Yi Wu

Drone CI/CD 自動化測試及部署
Drone CI/CD 自動化測試及部署Drone CI/CD 自動化測試及部署
Drone CI/CD 自動化測試及部署Bo-Yi Wu
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構Bo-Yi Wu
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in GolangBo-Yi Wu
 
Golang Project Layout and Practice
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and PracticeBo-Yi Wu
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub ActionsBo-Yi Wu
 
Drone 1.0 Feature
Drone 1.0 FeatureDrone 1.0 Feature
Drone 1.0 FeatureBo-Yi Wu
 
Drone CI/CD Platform
Drone CI/CD PlatformDrone CI/CD Platform
Drone CI/CD PlatformBo-Yi Wu
 
GraphQL IN Golang
GraphQL IN GolangGraphQL IN Golang
GraphQL IN GolangBo-Yi Wu
 
Go 語言基礎簡介
Go 語言基礎簡介Go 語言基礎簡介
Go 語言基礎簡介Bo-Yi Wu
 
drone continuous Integration
drone continuous Integrationdrone continuous Integration
drone continuous IntegrationBo-Yi Wu
 
Gorush: A push notification server written in Go
Gorush: A push notification server written in GoGorush: A push notification server written in Go
Gorush: A push notification server written in GoBo-Yi Wu
 
用 Drone 打造 輕量級容器持續交付平台
用 Drone 打造輕量級容器持續交付平台用 Drone 打造輕量級容器持續交付平台
用 Drone 打造 輕量級容器持續交付平台Bo-Yi Wu
 
用 Go 語言 打造微服務架構
用 Go 語言打造微服務架構用 Go 語言打造微服務架構
用 Go 語言 打造微服務架構Bo-Yi Wu
 
Introduction to Gitea with Drone
Introduction to Gitea with DroneIntroduction to Gitea with Drone
Introduction to Gitea with DroneBo-Yi Wu
 
運用 Docker 整合 Laravel 提升團隊開發效率
運用 Docker 整合 Laravel 提升團隊開發效率運用 Docker 整合 Laravel 提升團隊開發效率
運用 Docker 整合 Laravel 提升團隊開發效率Bo-Yi Wu
 
用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務Bo-Yi Wu
 
用 Go 語言打造 DevOps Bot
用 Go 語言打造 DevOps Bot用 Go 語言打造 DevOps Bot
用 Go 語言打造 DevOps BotBo-Yi Wu
 
A painless self-hosted Git service: Gitea
A painless self-hosted Git service: GiteaA painless self-hosted Git service: Gitea
A painless self-hosted Git service: GiteaBo-Yi Wu
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golangBo-Yi Wu
 
用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式Bo-Yi Wu
 

Más de Bo-Yi Wu (20)

Drone CI/CD 自動化測試及部署
Drone CI/CD 自動化測試及部署Drone CI/CD 自動化測試及部署
Drone CI/CD 自動化測試及部署
 
用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構用 Go 語言打造多台機器 Scale 架構
用 Go 語言打造多台機器 Scale 架構
 
Job Queue in Golang
Job Queue in GolangJob Queue in Golang
Job Queue in Golang
 
Golang Project Layout and Practice
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and Practice
 
Introduction to GitHub Actions
Introduction to GitHub ActionsIntroduction to GitHub Actions
Introduction to GitHub Actions
 
Drone 1.0 Feature
Drone 1.0 FeatureDrone 1.0 Feature
Drone 1.0 Feature
 
Drone CI/CD Platform
Drone CI/CD PlatformDrone CI/CD Platform
Drone CI/CD Platform
 
GraphQL IN Golang
GraphQL IN GolangGraphQL IN Golang
GraphQL IN Golang
 
Go 語言基礎簡介
Go 語言基礎簡介Go 語言基礎簡介
Go 語言基礎簡介
 
drone continuous Integration
drone continuous Integrationdrone continuous Integration
drone continuous Integration
 
Gorush: A push notification server written in Go
Gorush: A push notification server written in GoGorush: A push notification server written in Go
Gorush: A push notification server written in Go
 
用 Drone 打造 輕量級容器持續交付平台
用 Drone 打造輕量級容器持續交付平台用 Drone 打造輕量級容器持續交付平台
用 Drone 打造 輕量級容器持續交付平台
 
用 Go 語言 打造微服務架構
用 Go 語言打造微服務架構用 Go 語言打造微服務架構
用 Go 語言 打造微服務架構
 
Introduction to Gitea with Drone
Introduction to Gitea with DroneIntroduction to Gitea with Drone
Introduction to Gitea with Drone
 
運用 Docker 整合 Laravel 提升團隊開發效率
運用 Docker 整合 Laravel 提升團隊開發效率運用 Docker 整合 Laravel 提升團隊開發效率
運用 Docker 整合 Laravel 提升團隊開發效率
 
用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務用 Go 語言實戰 Push Notification 服務
用 Go 語言實戰 Push Notification 服務
 
用 Go 語言打造 DevOps Bot
用 Go 語言打造 DevOps Bot用 Go 語言打造 DevOps Bot
用 Go 語言打造 DevOps Bot
 
A painless self-hosted Git service: Gitea
A painless self-hosted Git service: GiteaA painless self-hosted Git service: Gitea
A painless self-hosted Git service: Gitea
 
Write microservice in golang
Write microservice in golangWrite microservice in golang
Write microservice in golang
 
用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式用 Docker 改善團隊合作模式
用 Docker 改善團隊合作模式
 

RESTful API Design & Implementation with CodeIgniter PHP Framework

  • 1. RESTful API Design & Implementation with CodeIgniter PHP Framework 2012 PHP Conference
  • 2. Who Am I Bo-Yi Wu @appleboy http://blog.wu-boy.com 任職於瑞昱半導體 RealTek(IC Design House) - TV 多媒體部門 - Sencha Touch 2, Backbone.js, CodeIgniter, Node.js, MongoDB, MySQL, Twitter Bootstrap, Twitter Hogan ... 2012 PHPConf 2
  • 3. Who Am I ● Open Source Contributions (github: appleboy) – CodeIgniter-Native-Session – CodeIgniter-i18n – CodeIgniter-Template – CodeIgniter-Nexmo-Message – CodeIgniter-TextMagic-API 2012 PHPConf 3
  • 4. My Focus ● CodeIgbiter 3.0.x develop branch – Support Native Session – Support HMVC – Support Sparks Package Management System ● Laravel develop branch ● Javascript (Node.js, Socket.io, Express, Backbone.js) 2012 PHPConf 4
  • 5. Outline ● Restful API Basic ● API Design ● Implementing API with CodeIgniter ● Verify your API 2012 PHPConf 5
  • 6. Restful API Basic 2012 PHPConf 6
  • 7. Why Use Restful? Restful API Service Database 2012 PHPConf (MySQL,MongoDB) 7
  • 8. What is REST? Http Method ● POST ● GET ● PUT ● DELETE ● OPTIONS Define in RFC 2616 2012 PHPConf 8
  • 9. 並非所有的瀏覽器都支援 PUT, DELETE http://api.jquery.com/jQuery.ajax/ 2012 PHPConf 9
  • 11. <input type='hidden' name='type' value='PUT'> 2012 PHPConf 11
  • 12. 將 PUT,DELETE 一併寫成 POST API 2012 PHPConf 12
  • 13. REST Response Format? ● JSON* ● XML ● Array ● Html ● CSV 2012 PHPConf 13
  • 14. 現在皆以 JSON 為主 格式簡單 , 相容性高 , 閱讀方便 2012 PHPConf 14
  • 15. Javascript Object Notation { key1: 'value1', key2: 20121103 key3: [1,2,3] } 2012 PHPConf 15
  • 16. JSON in Javascript is familiar var object = { key1: 'value1', key2: 20121103 key3: [1,2,3] } 2012 PHPConf 16
  • 17. JSON in PHP (encode) PHP Outputs <?php echo json_encode(array( {key: 'value'} 'key' => 'value' )); 2012 PHPConf 17
  • 18. JSON in PHP (decode) PHP Outputs <?php $json_data = '{key: value}'; array( 'key' => 'value' echo json_decode({ ); 'key' => 'value' }); 2012 PHPConf 18
  • 19. 你不可不知的 JSON 基本介紹 http://goo.gl/Wvhwb 2012 PHPConf 19
  • 20. API Design 2012 PHPConf 20
  • 21. 良好的 API 設計 ● Simple 簡單 ● Intuitive 直觀的 ● Stable 穩定 ● Well Document 線上文件 2012 PHPConf 21
  • 22. Using Facebook API 2012 PHPConf 22
  • 23. Fucking Stable and Document 2012 PHPConf 23
  • 25. 大家每天在花在討論的時間太長 Debug 時間變少 2012 PHPConf 25
  • 26. 良好的文件減少人與人溝通成本 團隊合作 2012 PHPConf 26
  • 27. Http Method RFC 2616 CRUD Method ● Create ● POST ● Read ● GET ● Update ● PUT ● Delete ● DELETE 2012 PHPConf 27
  • 28. API URL Define 2012 PHPConf 28
  • 29. /API/Module/Method 2012 PHPConf 29
  • 30. Format 1: Topic Module ● /API/Topic/Add ● /API/Topic/Update ● /API/Topic/Delete ● /API/Topic/List 2012 PHPConf 30
  • 31. Format 2: Topic Module ● /API/Topic/Add ● /API/Topic/Update/1234 ● /API/Topic/Delete/1234 ● /API/Topic/List/sort/asc 2012 PHPConf 31
  • 32. 個人偏好格式 1 2012 PHPConf 32
  • 34. API Response Format 2012 PHPConf 34
  • 35. 請勿常常修改 format ( 除非你想黑掉 ) 2012 PHPConf 35
  • 36. Example Create API Input Output var object = { { title: 'value1', title: 'value1', type: 'value2', type: 'value2', user_id: '1000' user_id: '1000', }; success_text: 'ok' } http://site.com/API/Topic/Add 2012 PHPConf 36
  • 37. Example Create API Input Output var object = { { title: 'value1', title: 'value1', type: 'value2' type: 'value2', }; user_id: '1000', success_text: 'ok' } http://site.com/API/Topic/Add/1000 2012 PHPConf 37
  • 38. Example Update API Input Output var object = { { id: '1000', id: '1000', title: 'value1', title: 'value1', type: 'value2' type: 'value2', }; success_text: 'ok' } http://site.com/API/Topic/Update 2012 PHPConf 38
  • 39. Example Update API Input Output var object = { { title: 'value1', id: '1000', type: 'value2' title: 'value1', }; type: 'value2', success_text: 'ok' } http://site.com/API/Topic/Update/1000 2012 PHPConf 39
  • 40. Example Delete API (single) Input Output var object = { { id: 1000 id: '1000', }; success_text: 'ok' } http://site.com/API/Topic/Delete 2012 PHPConf 40
  • 41. Example Delete API (multiple) Input Output var object = { { id: [1000, 1001] id: '1000', }; success_text: 'ok' } http://site.com/API/Topic/Delete 2012 PHPConf 41
  • 42. Example Delete API Input Output var object = { { id: '1000', }; success_text: 'ok' } http://site.com/API/Topic/Delete/1000 2012 PHPConf 42
  • 43. Example Read API (Single) Input Output var object = { { id: 1000 id: '1000', }; success_text: 'ok', item: { title: 'Kate Upton' } } http://site.com/API/Topic/List 2012 PHPConf 43
  • 44. Example Search API (Multiple) Input { Output var object = { id: '1000', q: 'Kate Upton' success_text: 'ok', }; items: [ {title: 'I am kate'}, {title: 'I am Upton'} ] } http://site.com/API/Topic/List 2012 PHPConf 44
  • 45. Kate Upton 2012 PHPConf 45
  • 46. 多虧了 Youtube API 讓我在上班時增加了很多動力 2012 PHPConf 46
  • 47. How to handle versioning? 2012 PHPConf 47
  • 48. 內部 API 大改版 2012 PHPConf 48
  • 50. 利用 URI Routing 功能 Framework or mod_rewrite 2012 PHPConf 50
  • 51. http://site.com/API/Topic/Add =  http://site.com/v1/API/Topic/Add 2012 PHPConf 51
  • 52. API Implementation 2012 PHPConf 52
  • 53. 不用自己造輪子 2012 PHPConf 53
  • 54. Phil Sturgeon’s CodeIgniter REST Server http://github.com/philsturgeon/codeigniter-restserver 2012 PHPConf 54
  • 55. Requirements ● PHP 5.2 or greater ● CodeIgniter 2.1.x to 3.0-dev 2012 PHPConf 55
  • 56. How to install? 2012 PHPConf 56
  • 57. Installation ● Drag and drop the following files into your application's directories – application/libraries/Format.php – application/libraries/REST_Controller.php – application/config/rest.php 2012 PHPConf 57
  • 58. Setup the config ● $config['rest_default_format'] = 'json'; ● $config['rest_enable_keys'] = false; ● $config['rest_enable_logging'] = false; ● $config['rest_enable_limits'] = false; ● $config['rest_ajax_only'] = false; 2012 PHPConf 58
  • 59. Include REST Controller 2012 PHPConf 59
  • 61. Handling Requests class Topic extends REST_Controller { public function index_get() {} public function index_post() {} public function index_update() {} public function index_delete() {} } 2012 PHPConf 61
  • 62. CRUD Requests class Topic extends REST_Controller { public function list_get() {} public function add_post() {} public function update_update() {} public function delete_delete() {} } 2012 PHPConf 62
  • 63. Accessing parameters is also easy 2012 PHPConf 63
  • 64. Parameters ● GET – $this->get('blah'); ● POST – $this->post('blah'); ● UPDATE – $this->update('blah'); ● DELETE – $this->delete('blah'); 2012 PHPConf 64
  • 65. Create API Input Output var object = { { title: 'Kate Upton', id: '1000', text: 'Beautiful girl' success_text: 'ok', }; } http://site.com/API/Topic/Add 2012 PHPConf 65
  • 66. Create API (POST) public function Add_post() { if (!$this->post('title')) { $this->response(array('error' => 'Title is required'), 404); } $output = $this->lib_topic->insert($data); if ($output) { $this->response($output, 200); } else { $this->response(array('error' => 'Insert error'), 404); } } 2012 PHPConf 66
  • 67. Update API Input Output var object = { { id: 1000, id: '1000', title: 'Kate Upton', success_text: 'ok', text: 'Beautiful girl' } }; http://site.com/API/Topic/Update 2012 PHPConf 67
  • 68. Update API (PUT) public function Update_put() { if (!$this->update('id')) { $this->response(array('error' => 'ID is required'), 404); } $output = $this->lib_topic->update($this->update('id'), $data); if ($output) { $this->response($output, 200); } else { $this->response(array('error' => 'Insert error'), 404); } } 2012 PHPConf 68
  • 69. Delete API Input Output var object = { { id: 1000 id: '1000', }; success_text: 'ok', } http://site.com/API/Topic/Delete 2012 PHPConf 69
  • 70. Delete API (DELETE) public function Delete_delete() { if (!$this->delete('id')) { $this->response(array('error' => 'ID is required'), 404); } $output = $this->lib_topic->delete($this->delete('id')); if ($output) { $this->response($output, 200); } else { $this->response(array('error' => 'Insert error'), 404); } } 2012 PHPConf 70
  • 71. Read API (GET) Input Output var object = { { id: 1000, id: '1000', type: [1, 2] success_text: 'ok', }; item: { title: 'Kate Upton' } } http://site.com/API/Topic/List 2012 PHPConf 71
  • 72. Read API (GET) public function List_get() { if (!$this->get('id') or ) { $this->response(array('error' => 'ID is required'), 404); } $output = $this->lib_topic->list($this->get('id'), $this->get('type')); if ($output) { $this->response($output, 200); } else { $this->response(array('error' => 'Insert error'), 404); } } 2012 PHPConf 72
  • 74. Folder application controllers/ api/ topic.php user.php acl.php system index.php 2012 PHPConf 74
  • 75. Routing (config/routes.php) Default URL http://site.com/api/topic/Add $route['API/Topic/(:any)'] = 'api/topic/$1'; $route['API/User/(:any)'] = 'api/user/$1'; $route['API/Acl/(:any)'] = 'api/acl/$1'; New URL http://site.com/API/Topic/Add 2012 PHPConf 75
  • 76. Verify Your API 2012 PHPConf 76
  • 78. Phil Sturgeon’s CodeIgniter REST Client https://github.com/philsturgeon/codeigniter-restclient 2012 PHPConf 78
  • 79. Requirements 2012 PHPConf 79
  • 80. Requirements ● PHP 5.1+ ● CodeIgniter 2.0.0+ ● CURL ● CodeIgniter Curl library: http://getsparks.org/packages/curl/show 2012 PHPConf 80
  • 81. Load Rest Client Library 2012 PHPConf 81
  • 82. Load Library // Load the rest client spark $this->load->spark('restclient/2.1.0'); // Load the library $this->load->library('rest'); 2012 PHPConf 82
  • 83. Setup API Server // Run some setup $this->rest->initial('xxxxxx'); // twitter server $this->load->initial('http://twitter.com'); 2012 PHPConf 83
  • 84. Parameter // set api path $api = '/API/Topic/Add'; // set api data $data = array( 'title' => 'I am Kate Upton', 'type' => 'girl' ); 2012 PHPConf 84
  • 85. Test it // GET API $this->rest->get($api, $data); // POST API $this->rest->post($api, $data); // UPDATE API $this->rest->update($api, $data); // DELETE API $this->rest->delete($api, $data); 2012 PHPConf 85
  • 86. $this->rest->debug(); Rest Client Library debug mode 2012 PHPConf 86
  • 87. 以上是 CodeIgniter PHP Framework 2012 PHPConf 87
  • 88. Implement another Framework? 2012 PHPConf 88
  • 89. Laravel PHP Framework? 2012 PHPConf 89
  • 90. public $restful = true; 2012 PHPConf 90
  • 91. class Home_Controller extends Base_Controller { public $restful = true; public function get_index() { // } public function post_index() { // } 2012 PHPConf 91 }
  • 92. More Introduction to Laravel Framework 14:20 – 14:50 用 Laravel Framework 打造現代化網站應用程式 大澤木小鐵 2012 PHPConf 92
  • 93. RESTful API 就講到這裡 2012 PHPConf 93
  • 94. 如果有任何問題 2012 PHPConf 94
  • 95. 可以上 CodeIgniter 論壇 2012 PHPConf 95
  • 97. 謝謝大家及工作團隊 2012 PHPConf 97