Hmm, if your anything like me, the fact that CI only supports XML-RPC is not enough. And unless you’ve been in a hole the last few years..then you’ve probably heard of REST, which stands for Representational State Transfer, which is a simple way of providing web services, using HTTP as a transport, and using URLs to identify services. I personally, am not a big fan of XML, so I’m not too big on protocols like XML-RPC and SOAP(mostly SOAP, because SOAP is such a hassle to screw with), and so, I looked around the CI forums for a REST library, and apparently there isn’t one. So, I wanted to make an easy way to implement REST in CodeIgniter(and also just PHP), which is just as simple as CI’s XML-RPC interface. So thus, the Lovable REST library was born. Now onwards, to API docs.
First, copy Rest.php into application/libraries.
To use it, your going to have to load it, example:
$this->load->library('rest');
After it is loaded, the library will be available at $this->rest, and the methods are as follows:
You can add methods via the addFunction function, example:
$this->rest->addFunction('name of service method to be used as a url identifier', 'name_of_method', 'data type'); /*Btw, the name of the method is a method of whatever object is passed via the serve function. The data type parameters can be: get, post, raw, and none. In order to use get as a service, you have to set your URI protocol to PATH_INFO or ORIG_PATH_INFO in your config.php. If you want to use PUT and DELETE, use raw as your data type.*/
Other functions in the API are jsonEncode, jsonDecode(which are just wrappers to decode/encode JSON), and serve, which propagates the request (You have to pass a reference of the object in which the API methods will reside, if they are in your controller, your $this), getRawInput, which returns the raw http post data, and enableGet, which you can use to enable $_GET manually.
Now to put it all together, here is an example of all of it in action:
class Api extends Controller
{
function _test($data)
{
print_r($data); /* $data almost always is an object, but if you specify raw as a data type, it will pass a string containing the RAW_HTTP_POST data. If you specify none, $data will be null */
}
function rest()
{
$this->load->library('rest');
$this->rest->addFunction('test', '_test', 'get');
$this->rest->addFunction('testpost', '__test', 'post');
$this->rest->serve($this); //You have to pass a reference to the object that has the methods. In this example, it would be the controller. */
}
}
Now, to access the services, you would use http://domain-name.com/controller/name_of_function_that_serve_is_called/function/function_name
so say, if the above controller was located at http://ilikecheese.com, you could access the testpost service at http://ilikecheese.com/api/rest/function/testpost
So…sorry for the long-winded rant, if anyone gets confused by my attempt at API docs, please post your question, and I will clarify.
Download:
