Skip to content


Easyrest Rest Framework 1.0 Released (Client and Server Library)

What is the Easyrest?
Easyrest is a REST framework that contains client and server implementations.It has a easy structural data transfer unlike XML-RPC.Easyrest use a lot of pear packages and it has got custom apikey functionality.I think using the pear libraries is not a disadvantage because of  you don’t have to install required pear libraries, easyrest can work from its own custom pear directory without any pear installation.

It use HTTP Request, xml_serializer and xml_unserializer classes.
Look at the process shema.

schema of easyrest

schema of easyrest

User (Rest Client) send easyrest commands via call class then PIF (Parameters Input Filter) do filter for all function parameters and it converts all params to secure parameters.Secure parameters goes to server and server (Rest Server) checks all parameters types (int,boolean,string..) if server function  paramaters that defined by the user before is not correct it goes to an exceptional error.

If no error occurs server produce a xml content with PEAR::xml_serializer and Call class gets response (xml content) from server and it parses xml content via PEAR::xml_unserializer then it returns to array.

You can turn off PIF function for each paramaters.I did PIF function for filtering function paramaters.Other data types ($_POST and $_GET) don’t use any filter so if you will send a POST or GET paramaters you should use your own filter.Filtering GET and POST rules same as in real php world.

Advantages of Easyrest:

1- Easyrest can work from localhost for test operations unlike XML-RPC.
2- It has got a custom api key functionality.User can assign client ids and api keys.
3- It send raw data for HTTP Requests so it makes request very fast.
4- User can define function paramater types from server.php
5- It has got “type hints” switch so xml_serializer automatically able to determine types for all outputs.
6- Easyrest response is not exactly xml it comes with a lot of xml part when the response finish it looks like a xml content.(see it in debug mode)
7- User can assign custom function names like XML-RPC.
8- Intelligible Client and Server structures.

Multiple Reponse joined in one xml.

Xml Parts joined in one xml.

Xml Parts joined in one xml.

An example of easyrest Client Request

<?php

require ('easyrest/Client.php');

//config                      
/* -----------------------------------------*/
$client = new Client();
$client->config->uri('http://localhost/easyrest/server.php');
$client->config->id('1');  //client id.
$client->config->secretkey('my secret keyword here');
$client->config->apikey('my api key');
$client->config->debug(false);    //if true it returns to xml.

//call commands
/* ------------------------------------------*/

$client->call->POST(array('post_var1'=>'value1', 'post_var2'=>'value2'));
$client->call->command('example.test1'); 
$client->call->params(array('1', 'i am a string param 2',true,'strigns blabalblabla <b>hghjvg</b>',false));

//call another command               
$client->call->GET();                                                          
$client->call->command('example.test3');                           
$client->call->params(array('banana', '1'));

//run all commands
$response = $client->call->run();             

//result
/* -------------------------------------------*/                                    
header('Content-type: text/html;charset=UTF-8');
print_r($response);

?>

OUTPUT: (Response)

Array
(
    [example.test1] => Array
        (
            [cities] => Array
                (
                    [0] => Array
                        (
                            [city_id] => 1
                            [name] => istanbul
                            [option] => 1
                        )

                    [1] => Array
                        (
                            [city_id] => 2
                            [name] => london
                            [Easyrest_Default_Tag] => some utf-8 chars: çşğü
                        )

                    [2] => Array
                        (
                            [city_id] => 4
                            [name] => paris
                            [string] => strignsdskj <b>hghjvg</b>
                        )

                )

            [post] => Array
                (
                    [post_var1] => value1
                    [post_var2] => value2
                )

        )

    [example.test3] => Array
        (
            [fruits] => Array
                (
                    [0] => Array
                        (
                            [name] => banana
                            [no] => 1
                        )

                    [1] => Array
                        (
                            [name] => apple
                            [no] => 2
                        )

                    [2] => Array
                        (
                            [name] => orange
                            [no] => 3
                        )

                )

        )

)

An example of easyrest Server

<?php
require ('easyrest/Server.php');

//Your function or class.
/* ------------------------------------------*/ 

Class My_class 
{
    function method($int, $string="", $boolean="", $string="", $empty="")
    {       
       $data['cities'][] = array('city_id' => '1', 'name'=> 'istanbul', 'option'=> $boolean); 
       $data['cities'][] = array('city_id' => '2', 'name'=> 'nyc', 'some utf-8 chars: çşğü'); 
       $data['cities'][] = array('city_id' => '3', 'name'=> 'london');
       $data['cities'][] = array('city_id' => '4', 'name'=> 'paris', 'string'=> $string);
       
       $data['post'][]   = array(
                                        'post_var1' => $_POST['post_var1'],  //==> WARNING! user your input filter
                                        'post_var2' => $_POST['post_var2'],
                                        );
        
       return $data; 
    }
    
    function method2($int='',$string='',$array='')
    {
       $data['countries'][] = array('country_id' => '1', 'name'=> 'usa');  
       $data['countries'][] = array('country_id' => '2', 'name'=> 'turkey');
       $data['countries'][] = array('country_id' => '3', 'name'=> 'africa');
       
       return $data;  
    }

}

function my_function($fruit_name, $number)
{
       $data['fruits'][] = array('name' => $fruit_name, 'no'=> $number);
       $data['fruits'][] = array('name' => 'apple', 'no'=> '2');
       $data['fruits'][] = array('name' => 'orange', 'no'=> '3');
       
       return $data;
}

//Config part.
/* ---------------------------------------------*/ 

$server = new Server();
$server->config->apikey_function('callback_check_apikey');

/* ---------------------------------------------*/


//Callback check apikey part.
/* ---------------------------------------------*/   

function callback_check_apikey()       
{
    //multiple keys - it should be come from db -> Select from apikeys where id = $id
    $db_apikeys = array(                              
            //client_id            //secretkey              //create an apikey
                     '1' => array('my secret keyword here','my api key'),  //secretkey => apikey
                     '2' => array('my secret keyword here2','my api key2'),
                     '3' => array('my secret keyword here3','my api key3')
                    );
                    
 //incoming keys                
    $apikey = Server::get_apikey();  //client apikey 
    $id     = Server::get_id();      //client_id
    
    
    //compare client and server keys
    if(!isset($db_apikeys[$id]))
    return FALSE;
    
    $key = $db_apikeys[$id];
    $encrypted_key = Server::encrypt($key[0],$key[1]);
    
    if($apikey == $encrypted_key)
    return TRUE;
    
    //else false 
    return FALSE; 
}                                                


//Define your functions.
/* -------------------------------------------------------*/ 

$server->define(

    array(
            'example.test1' => array(
                'function'  => 'My_class::method', //class::method
                'params'    => array('0'  => 'int|min[1]|max[5]',
                                     '1'  => 'string|maxchar[30]', //maximum character length
                                     '2'  => 'boolean',                         
                                     '3'  => 'string|maxchar[30]|filter[false]', //input filter                                                                                         //incase you Must use your own filter filtering for paramaters.Default switch on.(filter = true)
                                     '4'  => ''
                                     )
                //'request' => array()
                ),
                
            'example.test2' => array(               
                'function'  => 'My_class::method2', //class::method
                'params'    => array(
                                     '0'  => 'int',
                                     '1'  => 'string',  //default filter true.
                                     '2'  => 'array'
                                     )
                ),
                
            'example.test3' => array(               
                'function'  => 'my_function', //method (func)
                'params'    => array(
                                     '0'  => 'string|maxchar[30]',
				     '1'  => 'int'
                                     )
                ),
                       
         )

);


//Start serving...
/* --------------------------------------------*/ 

$server->serve();

/* --------------------------------------------*/    


?>

See xml content in debug mode:

<?xml version=”1.0″ encoding=”UTF-8″?>
<rest>
<example.test1>
<cities>
<city_id>1</city_id>
<name>istanbul</name>
<option>1</option>
</cities>
<cities>
<city_id>2</city_id>
<name>nyc</name>
<Easyrest_Default_Tag>some utf-8 chars: çşğü</Easyrest_Default_Tag>
</cities>
<cities>
<city_id>3</city_id>
<name>london</name>
</cities>
<cities>
<city_id>4</city_id>
<name>paris</name>
<string>strignsdskj <b>hghjvg</b></string>
</cities>
<post>
<post_var1>value1</post_var1>
<post_var2>value2</post_var2>
</post>
</example.test1>
<example.test3>
<fruits>
<name>banana</name>
<no>1</no>
</fruits>
<fruits>
<name>apple</name>
<no>2</no>
</fruits>
<fruits>
<name>orange</name>
<no>3</no>
</fruits>
</example.test3>
</rest>

Installing Easyrest?

Download easyrest v.1.0 package from http://sourceforge.net/projects/easyrest/

1- Server Installation:
Create a directory named Server  in your web root folder.
Copy easyrest package to this folder

server view

server view

Delete client.php (you will not need it.)

delete client.php

delete client.php

Open restConfig.php file from easyrest folder.

open restConfig.php

open restConfig.php

And look at important things.

$config['common']['pear']  = FALSE;

If you sure all required packages installed on your host set it TRUE.
If you don’t want to install pear libraries don’t worry Easyrest can work with pear packages from it’s own pear folder without any installation.For working independent from PEAR   ['common']['pear'] option must be FALSE.

$config['common']['iv'] = “zx#6}4&%”;

Change blowfish encryption key for security reason.
It must be minumum 8 and maximum 8 characters.!!

Open server.php and change your custom apikey function if you want.

open server.php

open server.

First if you don’t want to change it you can set just clients array for testing and then you can learn how it works, look at client $db_apikeys variable.Please define secret key and apikey for every clients.

configure apikeys

configure apikeys

Insert your class or functions top of the file below the require (‘easyrest/Server.php’);  line.

Insert your functions or classes

Insert your functions or classes

Define your Server functions and function paramaters.

Define your Server functions and function paramaters.

Define your Server functions and function paramaters.

PIF (Paramaters Input Filter) Validate Rules

Types Using Validate Rules Rules Description
Integer int min[int value],
max[int value],
filter[boolean]
Min-Max: Minumum and maximum range of integer limit.Filter: Easyrest input_filter switch on/off.Default on.
String string maxchar[int value],filter[boolean] Maxchar: Maximum character limit of string.Filter: Easyrest input_filter switch on/off.Default on.
Boolean bool or boolean filter[boolean] Filter: Easyrest input_filter switch on/off.Default on.
Float float filter[boolean] Filter: Easyrest input_filter switch on/off.Default on.
Array array filter[boolean] Filter: Easyrest input_filter switch on/off.Default on.

Note:  Server defined function paramaters number in ($server->define() func.) must be equal with your function method’s paramaters number.Otherwise you will get an error.

Server installation finished now you can look at client installation.

2- Client Installation:

Create a directory named Client  in your web root folder.
Copy easyrest package to this folder.
And Delete server.php. (you will not need it.)

Creating Client

Creating Client

Open restConfig.php file from easyrest folder.

set config file for client

set config file for client

And look at important things.

$config['common']['pear']  = FALSE;

If you sure all required packages installed on your host set it TRUE.
If you don’t want to install pear libraries don’t worry Easyrest can work with pear packages from it’s own pear folder without any installation.For working independent from PEAR   ['common']['pear'] option must be FALSE.

$config['common']['iv'] = “zx#6}4&%”;

Before you were set this option in Server config file.So set it same value.Client and server config file iv value must be same !!!

Open client.php

open client.php

open client.php

 Set server url
$client->config->uri(‘http://localhost/Server/server.php’); 

Set client id , set secret and apikeys of current id.
$client->config->id(’1′);  //client id.
$client->config->secretkey(‘my secret keyword here’); //secret key of id 1
$client->config->apikey(‘my api key’); //apikey of id 1

and Run client.php from your browser.

run client.php

run client.php

Note: This installation for localhost for testing but normally when you do a real application you have to create a client directory on your Client web root  and Server directory have to be in your Server web root.(Different machines.)

Download Easyrest v1.0

If you have a any question or when you find a bug please mail me.
Thanks.

FacebookDiggDeliciousGoogle BookmarksTechnorati FavoritesYahoo BookmarksWebnewsTechnotizieLinkatopiaPingStumbleUponTwitterShare

Posted in php articles.

Tagged with , , , , , , , .


16 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.

  1. Luke says

    This is one of the worst abuses of the term “REST” that I’ve seen in the PHP community. This is XML-RPC disguised as REST. Where is the support for uniform HTTP interface? What about flexible hypermedia and content type’s?

    This is nothing more than an XML-RPC router and serializer with a “REST” label on it.

  2. admin says

    I think this class contains both , XML-RPC and REST mostly it seems like XML-RPC but if you want to do REST operation you need just setup Server class.And your users will do request for server.php with send apikey (POST -GET).
    Next version of this class i will improve REST side i promise..

    And last thing i did research on internet and i looked somebooks before write this class but i couldn’t find enough source about a real rest implementation and really i don’t know good class sample or package example on the net.

    If you know a good REST Library or you know good articles about rest please Share with us.
    Thanks.

  3. Luke says

    This is an awesome book on the subject.

    http://oreilly.com/catalog/9780596529260/

  4. Johnmen says

    Could you give a example to invoke easyrest webservce through the JAVA client , I dont understand what is the url mapped, just like above example ,Could you tell me what is the url of example.test1?

  5. admin says

    example.test1 function defined in server.php it works like xml-rpc.when you call the example.test1 command you get its response.
    and i don’t know anything about java client sorry :(

  6. Johnmen says

    when my function has no paramenter how to Define the mapped functions?
    I just do like this

    //no parameter function
    function my_function()
    {
    $data['fruits'][] = array(‘name’ => $fruit_name, ‘no’=> $number);
    $data['fruits'][] = array(‘name’ => ‘apple’, ‘no’=> ’2′);
    $data['fruits'][] = array(‘name’ => ‘orange’, ‘no’=> ’3′);
    return $data;
    }
    //I try to define
    $server->define(
    ‘example.myfunc’ => array(
    ‘function’ => ‘my_function’, //method (func)
    ‘params’ => array()
    ),
    )
    but it tell me the params must be a array,how can I do?

  7. admin says

    Thanks i fixed this bug.
    Use it like this:

    // Client
    -------------------------------------
    $client->call->post();
    $client->call->command('example.test3');
    $client->call->params(array());

    // Server
    --------------------------------------
    'example.test3' => array(
    'function' => 'my_function', //method (func)
    'params' => array(), // no params
    ),

    You can download new beta version from below the link:

    http://code.google.com/p/easyrest/

  8. ersin says

    oreilly rest services book is very abstract and its utopic for php developers..
    look at this book for how to build advanced php restful services
    it tells real worls php rest services

    http://www.packtpub.com/restful-php-web-services/book

  9. Lorenz says

    Hi admin, thanx for posting this article, this is what i’m looking for, a REST/XML-RPC like library. I’m working on a project using php based REST server and client applications runs on Android.

    Thanx.

  10. admin says

    your welcome ;)

  11. DEViANT says

    This is Briliant!

    Thanks allot man. Really gonna help me out on a project Im working on. Cheers

Continuing the Discussion

  1. Community News: Easyrest Freamwork 1.0 Released | Webs Developer linked to this post on 20/08/2009

    [...] assign client ids and API keys. It send raw data for HTTP Requests so it makes request very fast. The post includes plenty of examples for use on both the client and server side (including output). Share [...]

  2. Community News: Easyrest Freamwork 1.0 Released | PHP linked to this post on 21/08/2009

    [...] to this new entry to the devturk blog, the stable (1.0) version of the Easyrest framework has been released. [...]

  3. The Zend Framework plugin a Wordpress plugin and theme developers life saver | Timani linked to this post on 14/03/2010

    [...] EasyRest Framework [...]

  4. XML-PRC的替代者:Easyrest框架发布 | PHP教程 – PHP、Oracle、MySQL、Js、Jquery教程、基础、实例 linked to this post on 17/04/2012

    [...] 发布声明页面:点击这里 [...]



Some HTML is OK

or, reply to this post via trackback.