7 days of WordPress plugins, themes & templates - for free!* Unlimited asset downloads! Start 7-Day Free Trial
  1. Code
  2. PHP

Working with RESTful Services in CodeIgniter

Scroll to top
Read Time: 16 mins

CodeIgniter is becoming well known for its power as a PHP based web application framework, but it's not often that we see examples of it being used for anything else. Today we'll learn how we can use CodeIgniter to create a RESTful API for your existing web applications, and demonstrate how to interact with your own API or other RESTful web-services, such as Facebook and Twitter.

As you may know, you can find a wide selection of CodeIgniter scripts and apps on Envato Market, from user login and management system to menu managers and much more.

Tutorial Details


If you have been following the CodeIgniter From Scratch series you will know by now that it is relatively quick and easy to put together simple web applications, such as blogs, CMS systems, brochure sites, etc. One thing you may not have thought about is using CodeIgniter to create an interactive API. After trying several existing REST implementations, I found they not only lacked simplicity but were missing most of the features you would expect from a RESTful implementation; so I built my own. This tutorial will show you how to use this code to set up your REST API, and gives example of how to interact with it from your web application.


  1. You have a web server set up, locally or online and known how to manage files on it.
  2. You have read a few of the CodeIgniter from Scratch tutorials.
  3. You know how to set up CodeIgniter.
  4. You know a little about RESTful services.

This tutorial is broken down into two parts. We will start by learning how to create a RESTful service, then further down, we will learn how to interact with it in a few different ways.

Part 1 - Creating a RESTful API

Step 1: Setting up the Demo

Firstly you need to download the codeigniter-restserver code from GitHub and extract it and move the code to your server.

When you open the folder, you will see an entire CodeIgniter install, which is there to power the demo. This allows people to have a play with the REST demo before integrating with your existing application.

Open up "application/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.

Step 2: The URLs

With the files extracted and the base_url set, we are ready to load up our RESTful CodeIgniter installation, and have a look at the demo supplied with it. Browse the base URL, which by default is:


Here you will find a few example links to the example_api controller, which can be found at "application/controllers/example_api.php". Let's dissect the URL's of these examples to see what is going on. The first URL is a very simple one.

This URL looks very much like any other CodeIgniter URL with a controller and a method, but you will notice in this diagram that the method is named a "Resource". REST is all about Resources and they are essentially a noun within your application, which are interacted with (i.e added, deleted, edited, queried) based on HTTP headers and URL query strings or HTTP arguments.

The default format for output is XML which is what we see in this basic example. The other links are slightly larger and demonstrate how to pass parameters and show how the output format can be modified in the URL:

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.

At the end of the URL is the "format" parameter. This is a reserved parameter that will modify the output format of the requested data like so:

By giving both the API developer and the client application the choice of data formats to use, the API is opened up to a much wider audience and can be used with more programming languages and systems. These three are not the only formats supported, out of the box your REST API can use:

  • xml - almost any programming language can read XML
  • json - useful for JavaScript and increasingly PHP apps.
  • csv - open with spreadsheet programs
  • html - a simple HTML table
  • php - Representation of PHP code that can be eval()'ed
  • serialize - Serialized data that can be unserialized in PHP

While adding the format to the URL is not technically the most RESTful way to change formats, it allows for easy browser testing and lets developers without cURL perform simple GET requests on the API. The more RESTful way is to send a Content-type HTTP header to the REST controller using cURL, but that will be explained later.

Step 3: The Code

Now if you open up application/controllers/example_api.php you will immediatley spot a few differences from normal CodeIgniter controllers.


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:

...you will need to use:

Working with Resources

Now your empty controller is set up, next are the methods or "resources". This is prossibly the most confusing part of the tutorial 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:

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.


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).


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.


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


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

If we put that into code and allow each verb on the resource user it would look like this:

Accessing parameters and returning data

So now the API has been given its structure by setting up the resources and defining a method for each HTTP verb we wish to support; we need parameters so we can use our CodeIgniter models and libraries. This is one of the major benefits of using CodeIgniter for our API, as we can use our existing models and libraries and not have to re-code them.

This example contains five new pieces of code:


Is used to return GET variables from either a query string like this index.php/example_api/user?id=1 or can be set in the more CodeIgniter'esque way with index.php/example_api/user/id/1.


Is an alias for $this->input->post() which is CodeIgniter's method to access $_POST variables with XSS protection.


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


You guessed it, this reads in DELETE arguments, also set in HTTP headers or via cURL.


Sends data to the browser in whichever data format has been requested, or defaults to XML. You can optionally pass a HTTP status code to show it has worked or failed. E.g if the ID provided was not in the database, you could use $this->response(array('error' => 'User not found.'), 404);

Step 4: 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:

  1. application/config/rest.php
  2. application/libraries/REST_Controller.php

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

This shows an example API with some generic model names. In the first method, we are picking up a ?id=XX and passing it to the model. If data is found we send it to the $this->response() function with a status 200. If nothing is found, return no body and a 404 to say nothing was found. You can imagine how this could be expanded to run all sorts of API activities for your web application.

Step 5: 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 "application/config/rest.php" inside your codebase.


Anyone can interact with any one of of your API controllers.


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


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.

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.

Part 2 - Interacting with RESTful Services

Whether it is the API you have just built or a public service such as Twitter, 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.

Different Methods to Interact with REST

Each of these different interaction methods will be shown with the code placed directly in the Controller methods. This is purely so the demos are easier to read and would normally would be placed inside a model or a library for correct MVC separation.


Using the very simple PHP function file_get_contents(), you can perform a basic GET request. This is the most basic of all the methods but is worth mentioning for those "quick and dirty" moments.

It's worth noting that, while this method will not work using HTTP Digest authentication, if you are using HTTP Basic authentication you can use the following syntax to get data from your password protected RESTful API:

There are a few problems with using this method: the only way to set extra HTTP headers is to set them manually using the PHP function stream_context_create(), which can be very complicated for developers who are new to the internal workings of HTTP requests. Another disadvantage is that you only receive the body of the HTTP response in its raw format, which means you need to handle conversion from very single request.


cURL is the most flexible way to interact with a REST API as it was designed for exactly this sort of thing. You can set HTTP headers, HTTP parameters and plenty more. Here is an example of how to update a user with our example_api and cURL to make a POST request:

Interacting with your API this way works fine, but there are two problems with this method:

  1. It uses an ugly confusing syntax - imagine creating several an application based on that.
  2. cURL is not installed on all servers by default.

To solve this ugly syntax, a cURL library has been developed for CodeIgniter which simplifies things immensely.

The exact same request made with the cURL library would look like this:

Much nicer to look at right? Well there is an even easier method to work with REST in your CodeIgniter applications that this.

REST client library

A REST client library has been developed that sits on top of this cURL library which handles format conversion, HTTP logins and several other aspects of your REST API.

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:

As you have probably guessed as well as $this->rest->get(), the library also supports $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 somtimes 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.

Talking to Twitter

Using this REST library you can talk other RESTful services such as Twitter and Facebook. Here is a simple example of how you can get details for a specfic user based on their ID, using Twitter's default format XML.

Looking at this, you will notice that interacting with the Twitter API is a bit different in a few ways.

  1. They support URL based format switching in the form of .json instead of /format/json. Some require an extension, some do not; so it's best to always add them.
  2. They mostly only support GET/POST, but are starting to add more DELETE methods
  3. They don't always have just a resource in their URL, for example: users/search is one REST method, but lists is another.

Keep an eye out for these differences as they can catch you out. If you get stuck, simply echo $this->rest->debug() for a whole range of information on your REST request.


Combining what you now know about RESTful services, the CodeIgniter REST client library and the Twitter API documentation - or any other RESTful API documentation for that matter - 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 and even make a modular API by using Matchbox or Modular Separation to create an api.php controller for each module to help keep your API as neatly organized as your application.

Follow us on Twitter, or subscribe to the Nettuts+ RSS Feed for the best web development tutorials on the web. And don't forget to check out the useful CodeIgniter scripts and apps on Envato Market.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.