Torbjorn Zetterlund

Wed 17 2015
Image

How to work with RESTful Services in CodeIgniter 3.x

by bernt & torsten

With the new release of CodeIgniter 3.0, one of the powerful add-on features to Codeigniter is the RESTful API server and client libraries. I will explain in this article how I use the Yggdrasil Codeigniter 3.x repo to create a RESTful API for your web applications, and demonstrate how to interact with your own API or other RESTful web services, such as Alchemy API.

First, download the Yggdrasil Codeigniter 3.0 repo from Github – the Yggdrasil repo comes packaged with CodeIgniter 3.0, CodeIgniter REST server and CodeIgniter REST client.

Installing Yggdrasil is straightforward, it comes with an installation script – all you need to do is to download the Github repo of Yggdrasil and unzip it into the root of your web service. In my example, I have installed it on a laptop running MAMP stack and accessing it as localhost. You would need to have some experience with Codeigniter and knowledge of RESTful API services.

Open up “app/config/config.php” and set the base_url to get links working. This base_url will be different for everyone and depends entirely on where you uploaded your files. Depending on your base URL you could access Yggdrasil  with http://localhost

You also need a tool to test the RestFul API – I’m using the Advanced Rest Client for Chrome.

Click on login, and log in with the credentials you gave when installing Yggdrasill – navigate to API key and create an API Key

yggdrasil api-key
yggdrasil api-key

In the Yggdrasil you find the APIs in app/controllers/api_1 – here you find the API file for users – users.php.

To make an API request to fetch the latest users, you make the following call http://localhost/api/1/users?apikey=<your api key>

Here is how it looks using the Advanced Rest Client

Chrome Advanced Rest Client Application
Chrome Advanced Rest Client Application

This URL looks very much like any other CodeIgniter URL with a controller and a method, but you will notice that the api/1 points you do the directory where the API is located you can interact with your API (i.e added, deleted, edited, queried) based on HTTP headers and URL query strings or HTTP arguments.

The default format for output is JSON which is what we see in this basic example. Normally in CodeIgniter, you just pass in parameter values, but a REST controller accepts any number of parameters in any order. For this to work, we need to pass in the name of the parameter followed by the value in pairs.

The Code
Now if you open up app/controllers/api/1/users.php you will immediately spot a few differences from normal CodeIgniter controllers.

REST_Controller

In the MVC pattern, a controller is the central point of the logic. It is called when a user makes a request and then based on the logic in the controller it fetches data and outputs views. CodeIgniter contains its own logic for how a Controller should work, but as we are doing something different we need our own REST_Controller library to contain its own REST-related logic. So instead of simply using:

class Users extends Controller {

}

…you will need to use:

class Users extends REST_Controller {

}

Now your empty controller is set up, next are the methods or “resources”. This is possibly the most confusing part if you are used to how CodeIgniter works. Basically, you take the Resource and the HTTP verb and combine them to make a method name. So the two examples we looked at before had a Resource of users and users. Because both of these were loaded in the browser, we know it was using a GET request and so the two methods below are used:

class Users extends REST_Controller {

function show_get()
{
// respond with information about a user
}

function index_get()
{
// respond with information about several users
}
}

This may seem a little strange, but it gives you the ability to use the same URL and respond to the request depending on the HTTP verb that has been used. If somebody tries to access your API in a way that is not allowed (in this example PUT or DELETE) it will simply respond with a 404. If you aren’t sure about HTTP verbs, let me explain.

GET

Used to fetch information about an existing resource. This is used by browsers when you enter a URL and hit go, or when you click on a link, so it is perfect for fetching information on one of your REST resources (like user).

POST

Used to update an existing resource with information. Browsers use this to submit most types of forms on the internet, although some use GET as well by submitting the form action with a query string containing the field data.

PUT

Less commonly used and not supported by most browsers, PUT is used to create a new resource.

DELETE

Also not used by many browsers, this HTTP verb rather obviously is used to delete a resource.

Using CodeIgniter models and libraries is one of the major benefits of using CodeIgniter for your API, you can use existing models and libraries and not have to re-code them.

Accessing parameters is also easy. Simply use the name of the HTTP verb as a method:

$this->get()

It is used to return GET variables from a query string like this http://localhost/api/1/users/user?id=1.

$this->post()
$this->put()

Reads in PUT arguments set in the HTTP headers or via cURL.

$this->delete()

The HTTP spec for DELETE requests precludes the use of parameters. For delete requests, you can add items to the URL

public function index_delete($id)
{
  $this->response(array(
    'returned from delete:' => $id,
  ));           
}

Working with your Models
Until now, we have been working with an example API in a clean install. So the next step is to get a REST API running from your existing codebase.

Although the download comes with a full CodeIgniter installation for the demo and to allow API’s to be built from scratch, the only two files of importance are:

app/config/rest.php
app/core/REST_Controller.php

Drop those two files into your CodeIgniter application and create a new API controller.

Securing the API
Now your API is built it needs securing so only users given access can interact with the API. To set the login type, usernames and passwords open up “app/config/rest.php” inside your codebase.

/*
|--------------------------------------------------------------------------
| REST Login
|--------------------------------------------------------------------------
|
| Is login required and if so, which type of login?
|
| '' = no login required, 'basic' = relatively secure login, 'digest' = secure login
|
*/
$config['rest_auth'] = 'basic';

None

Anyone can interact with anyone of your API controllers.

Basic

A relatively insecure login method should only be used on internal/secure networks.

Digest

A much more secure login method that encrypts usernames and passwords. If you wish to have a protected API which anyone could get at, use digest.

/*
|--------------------------------------------------------------------------
| REST Login usernames
|--------------------------------------------------------------------------
|
| Array of usernames and passwords for login
|
| array('admin' => '1234')
|
*/
$config['rest_valid_logins'] = array('admin' => '1234');

Setting up the users is simple. Each login is an array item, with a key and a value. The key is the username and the value is the password. Add as many as you like to this array and dish them out to anyone who will be using the API.

Interacting with RESTful Services
Whether it is the API you have just built or an external service such as Alchemy API, read the article using alchemy data news api with codeigniter 3-x, you will want to be able to interact with it somehow. Seeing as RESTful services work with basic HTTP requests it is very easy to do this in a number of different ways.

REST client library

The REST client library sits on top of cURL library which handles format conversion, HTTP logins and several other aspects of your REST API.

function rest_client_example($id)
{
$this->load->library('rest', array(
'server' => 'http://localhost/api/1/users/',
'http_user' => 'admin',
'http_pass' => '1234',
'http_auth' => 'basic' // or 'digest'
));

$user = $this->rest->get('user', array('id' => $id), 'json');

echo $user->name;
}

Here you can see we are making a GET request, sending id as a parameter and telling the library we want ‘json’ as the content format. This handles the setting of Content-type for you and converts the data into a PHP object for you. You can change this value to ‘xml’, ‘json’, ‘serialize’, ‘php’, ‘csv’ or any custom MIME-type you like, for example:

$user = $this->rest->get('user', array('id' => $id), 'application/json');

The library supports$this->rest->get(), $this->rest->post(), $this->rest->put(), $this->rest->delete() to match all of your REST_Controller methods.

You will need to var_dump() results coming from the REST client library to make sure you are getting the right data format back. The conversion will sometimes be an array and sometimes be an object, depending on how it is converted by PHP. If the returned MIME-type is not supported then it will simply return the format as plain-text.

Combining what you now know about RESTful services – you can create some very powerful applications that integrate with any custom or public web service using REST. You can extend your API by creating more REST_Controller’s.

Share: