• Home
  • My Work
  • How to work with RESTful Services in CodeIgniter 3.x
https://torbjornzetterlund.com/wp-content/uploads/2015/06/apis-960x600_c.jpeg

How to work with RESTful Services in CodeIgniter 3.x


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.0 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 straight forward, 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 on a laptop running MAMP stack and accesing 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 baseurl 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 login 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 API’s 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 user 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 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 in 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()

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 any one of your API controllers.

Basic

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

Digest

A much more secure login method which encrypts usernames and password. 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 a 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 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.

8 Responses

  • Max on September 21, 2016, 18:58:01

    Hi,
    How easy would it be to build an API for https://tastyigniter.com/?

    Reply to Max
    • torbjornzetterlund on September 22, 2016, 09:37:29

      Are you just using Codeigniter out of the box, or have you added additional libraries?

      To get CodeIgniter to work with a restFUL API and get it started quickly – you can use the RESTful API Server – the instructions are straight forward.

      The task that takes time is to define what API’s you need, I assume from your site that customer and order should be easy to do, most of the API calls on the server side are basically to handle incoming request POST, GET, DELETE and then making sql call to the database and from the result output a json response.

      I can give you some examples, if you going down this road.

      Reply to torbjornzetterlund
      • kayalvizhi on February 20, 2017, 09:50:19

        hi..i cant understand..can u explain with videos fromstarting to end…i know only codeigniter..but i have to know codeigniter with api clearly

        Reply to kayalvizhi
  • Jacek on March 3, 2017, 07:45:56

    What is the advantage of using on the server side RESTful API server vs. CodeIgniter’s ‘input’ methods (e.g., $this->input->post (‘xyz’, TRUE/FALSE); or just $_POST [‘xyz’])?
    Best, Jacek

    Reply to Jacek
    • torbjornzetterlund on March 3, 2017, 15:15:19

      Wit a RESTful API server you can build an Android App, that makes API call to your CodeIgniter backend. The CodeIgniter RESTful API server, uses the methods (e.g., $this->input->post (‘xyz’, TRUE/FALSE); or just $_POST [‘xyz’]) to get the data from the API call. I hope that simple answer explains.

      Reply to torbjornzetterlund
      • Jacek on March 3, 2017, 19:32:46

        Actually, I am still confused :) Whichever client we have (whether Android, iOS or just a browser), the call they will make is a POST request with data passed in the body of that call. Those clients also expect to get results in the body of whatever the server is responding with.

        With that in mind, whether on the server side we are using CI $this->input->post, or RAS (RESTfull API Server) introduced methods, we are getting the same data, aren’t we? Also, whether we push back from CI with echo $whatever (eventually adding proper headers) or with RAS methods, the client will not know the difference (I think).

        I have to be missing something, as to me that is a toss, with a potential headache to use a third party library that does the same thing what CI already do.

        Actually, I have it working in CI without the library right now, and it is working for me (sort of – have it working with an Android client), and if the RAS can simplify my life, I would like to use it.

        Best, Jacek

        Reply to Jacek
        • torbjornzetterlund on March 7, 2017, 11:26:33

          Jacek,

          What you referring to is correct, you can make a page AJAX call e.g. localhost/greengarden/warehouse/inventory/ajax_add&name=car&description=volvo&type_id=1, in your code you can use $this->input->post and use echo json_encode(array(“status” => TRUE));

          Here is example of the full code.

          public function ajax_add()
          {
          $data = array(
          'user_id' => ci()->current_user->id,
          'name' => $this->input->post('name'),
          'description' => $this->input->post('description'),
          'type_id' => $this->input->post('type_id'),
          'use_id' => $this->input->post('use_id'),
          'skills_required_id' => $this->input->post('skills_required_id'),
          'certifications_id' => $this->input->post('certifications_id'),
          'location_id' => $this->input->post('location_id'),
          'quantity' => $this->input->post('quantity'),
          'condition_id' => $this->input->post('condition_id'),
          'size' => $this->input->post('size'),
          'image_name' => $this->input->post('image_name') ?: 'default.jpg',
          'location_in_warehouse' => $this->input->post('location_in_warehouse'),
          );
          $insert = $this->Inventory_m->save($data);
          echo json_encode(array("status" => TRUE));
          }

          I used this when I create forms, or a list of items.

          Then I use javascript to send that information from my form to the backend.

          $.ajax({
          url : url,
          async:false, // Fix for Firefox - Async call do not work in FF if you trigger on form submission
          type: "POST",
          data: $('#form').serialize() + '&image_name=' + filename,
          dataType: "JSON",
          success: function(data)
          {

          Sure, you could use the same method to send data back to your Android phone. The RESTFul API is a much better option, is a recognisable standard in the industry. And it comes with a lot of security options, e.g.

              force https,
              authentication of users that using the API,
              source of authentication,
              API Key to authenticate,
              whitelist IP,
              blacklist IP,
              length of API key,
              to log API calls,
              setting limits on the number of API calls.

          To mention a few functions that are available with the RESTFul API library, Yes, you could build all this, it will take time and using the RESTFul API server library will save you times.

          Here is an example of an API key request – localhost/greengarden/api/1/insight/newsitems_per_day?apikey=oBThDgL…00%3A00%7D&end=2017-03-07+%7B23%3A59%3A59%7D&feed=82&campaign=0&tagged=all

          Data will only be display back if the APIKEY matches.

          $.getJSON('http://localhost/greengarden/api/1/insight/newsitems_per_day', {
          apikey: '< ?php echo $apikey; ?>',
          start: startDate.format('{yyyy}-{MM}-{dd} {00:00:00}'),
          end: endDate.format('{yyyy}-{MM}-{dd} {23:59:59}'),
          feed: '< ?php echo '82' ?>',
          campaign: '< ?php echo '0' ?>',
          tagged: '< ?php echo 'all' ?>'
          }, function(data) {

          The code above makes an API call and setting all the parameters that goes in the call. On the server side the code that needs to be added, is only a few lines –

          // /api/v1/insight/newsitems_per_day
          // startday =
          // endday =
          public function newsitems_per_day_get()
          {
          $feed = $this->get('feed') ? $this->get('feed') : false;
          $tagged = $this->get('tagged') == 'all' ? false : ($this->get('tagged') == 'tagged' ? 1 : 0);
          $results = $this
          ->Insight_m
          ->get_number_of_newsitems_per_day($this->get('start'), $this->get('end'), $tagged);
          $this->response($results, 200);
          }

          All the authentication, checking APIKEY etc, is done by the RESTFul API library.

          I hope this gives you more insights, to make your choice going forward.

          Reply to torbjornzetterlund
  • Saquib Rizwan on May 15, 2017, 14:37:51

    Thanks a lot. It’s a very nice tutorial.

    Reply to Saquib

Menu