# Example of RESTful features in DooPHP

It is very easy to implement your own REST API. What you have to do is just to define the routes with the request method you want it to be accessed

It is best that you know more on HTTP status code. and take some popular RESTful web services like Twitter as example.

    # simply assign routes and define the desire Request method
    $route['get']['/api/food/list/all.xml'] = array('RestServerController', 'listFood_xml');  //get only
    $route['post']['/api/food/create'] = array('RestServerController', 'createFood');         //post only
    $route['put']['/api/food/update'] = array('RestServerController', 'updateFood');         //put only
    $route['delete']['/api/food/delete/:id'] = array('RestServerController', 'deleteFood');  //delete only

Useful Features in Controller

If you want to support various data format for your RESTful API, you can either use $this->extension or $this->accept_type() to determine what format the client is requesting.

The difference between $extension and accept_type is that, $extension is get from the extension set in the routes config while accept_type() should be used if the client is issueing an Accept header for the desired format. $extension returns the extension with a dot in front '.json' while accept_type() returns just the extension name 'json'.

    # For a static route like this you don't have to use $this->extension as you can simply direct it to a method
    $route['get']['/api/food/list/all.xml'] = array('RestServerController', 'listFood_xml');

    # For dynamic routes you've to define the extension option
    # in the Controller you can verity $this->extension and output the result format accordingly
    $route['*']['/api/food/list/:id'] = array('RestServerController', 'listFoodById',
                                              'match'=>array('id'=>'/^\d+$/'),
                                              'extension'=>array('.json','.xml')
                                        );

    # Something like this would be best to $this->accept_type() to get the requested format
    # while the client can send an Accept header: header("Accept: application/json");
    # in the Server method you call $this->accept_type() and you will get 'json'
    $route['post']['/api/food/create'] = array('RestServerController', 'createFood');

    # when you are outputing the results, you might want to specify a header on what format is return
    # instead of doing header("Content-type: application/xml;"); you can do
    $this->setContentType('xml');
    echo $xmldata;

    #if you need to specify the Charset along with the data, simply
    $this->setContentType('xml', 'utf-8');

    #if your application supports multilanguage, you can get the client's desired language
    $this->language()       // this returns lang code such as 'en', 'cn', 'fr'
    $this->language(true)   // this returns lang code with the country code, 'en-US'

    # you can authenticate your API method with DooDigestAuth class, or define in the routes
    $users['doophp'] = '1234';
    $users['demo'] = 'demo';
    $this->load()->core('auth/DooDigestAuth');
    $username = DooDigestAuth::http_auth('Food Api Admin', $users, 'Failed to login!');
    echo 'You are login now. Welcome, ' . $username;

    # in a GET/POST request API, you can get variables from $_GET & $_POST
    # BUT, there's no $_PUT in PHP, instead you use  $this->puts
    echo  $this->puts['type'];
    echo  $this->puts['food'];

DooRestClient Usage

DooRestClient is a REST client to make requests to 3rd party RESTful web services such as Twitter. It wraps around CURL and supports method chaining for shorter code.

Example usage

    # make a GET request to Twitter
    $this->load()->helper('DooRestClient');
    $client = new DooRestClient;
    $client->connect_to('http://search.twitter.com/trends/daily.json')
    $client->get();

    if($client->isSuccess()){
        print_r( $client->resultCode() );
        print_r( $client->resultContentType() );
        print_r( $client->result() );
    }

    # for different Request type use
    $client->get();
    $client->post();
    $client->put();
    $client->delete();
    $client->execute('get');

Make your code shorter!

    # method chaining
    $this->load()->helper('DooRestClient');
    $client = new DooRestClient;
    $client->connect_to('http://search.twitter.com/trends/daily.json')->get();

    # Or even...
    $this->load()->helper('DooRestClient', true)
         ->connect_to('http://search.twitter.com/trends/daily.json')
         ->get();

    # It's the same
    Doo::loadHelper('DooRestClient', true)
         ->connect_to('http://search.twitter.com/trends/daily.json')
         ->get();

Pass in options, data, accept format type, authentication.

    # some random example...
    $client->connect_to( 'http://someapi.com/api/method' )
           ->options(array('SSL_VERIFYPEER'=>false))
           ->auth('username', 'password')
           ->accept(DooRestClient::XML)
           ->data( array() )
           ->post();

    # Twitter Status update example, Basic auth, need to pass in True in auth()
    $client = $this->load()->helper('DooRestClient', true)
                            ->connect_to("http://twitter.com/statuses/update.xml")
                            ->auth('username', 'password', true)
                            ->data( array('status'=>'Some message with DooPHP') )
                            ->post();

    # You can retrieve the data by calling the methods without params
    print_r( $client->data() );
    print_r( $client->auth() );
    print_r( $client->accept() );

BACK TO TOP