Creating a simple API using CodeIgniter MVC PHP framework

So for this tutorial I created a simple API using code igniter. CodeIgniter is a PHP MVC framework. Its extremely simple and straight forward to setup. It comes with a lot of features which I didn’t go into but I will eventually. To create the API we learn about using CodeIgniter’s base classes for Controllers and Models. We also work with the database. To recap this tutorial will cover

  • Creating a Controller
  • Creating a model
  • Connecting to a database
  • Outputting JSON
  • Working with the database
  • Code igniter directory structure.

The main files for this tutorial can be found in this folder. It will be updated with the content you need to understand it.

To get started I download the framework from the website and extracted it. You can check out the download page here. Once you download and extract the folder you can begin using CodeIgniter. Of course you will have to setup up your server to run a PHP application. I usually use XAMPP.

Learning CodeIgniter

The welcome page for CodeIgniter looks like below.

The first thing we want to do is understand how routing works in CodeIgniter. We can view the default Welcome Controller to understand this. You can find the Welcome Controller via application=>controllers=>Welcome.php.

class Welcome extends CI_Controller {
	public function index()

The main function index is what displays our welcome message above. A function load->view is used to display the message. We mimic this when we create our Users controller.

defined('BASEPATH') OR exit('No direct script access allowed');

class Users extends CI_Controller


The users controller is used to test our routing before we get into creating our API. So lets add some functions to it. The first function we add is called first.

public function first(){
   echo "This is the first user";

Our base URL is call this will be different for you. So to access this function we do What we see is “This is the first user”. Lets add another function called second. If you want to use utility functions you can change the type of function from public to private.

public function second(){
 echo $this->test();

private function test(){
 return "This is a private function";

Private functions can’t be access via a URL. So you can do


but you can’t do this


Instead we using the test in the second function as shown above.

Notice that our controllers extend the base controller CI_Controller this is important.

Now you know how to create different routes in our application we will want to work with our database now.

Configuration in codeigniter can be found in application=>config folder. The database configuration is in the application=>config=>database.php file.

We can create models by extending the CI_model class. Our user model is shown below.

class UserModel extends CI_Model

	public function __construct()

The this->load->database() function allows us to access our database in the model class. We can call this function any where. Calling it in the constructor allows us to access it in any method we choose.

To get all records from the database we create a getAll function.

public function getAll()
    $query = $this->db->get("users", 20);
    return $query->result()

The $this->db->get($tablename, $limit) function takes a table name and limit as arguments. The limit will determine how many results are returned. We can access the results using a foreach loop.

public function getAll()
    $data = array();
    $query = $this->db->get("users", 20);
    foreach($query->result() as $result){
      echo $result->first_name;
      echo $resuslt->last_name;

If we wanted to get just one row from the database we can do the following.

public function getOne(){
   $query = $this->db->get_where("users", array('id' => 1));
  return $query->result()[0];

So we can use the get_where function to get a single record. We have to take the first object from results array.

So now lets build the API.

Building the API

To build the API I created a API controller and created a private function. The private function is called json_output that is what we use to return JSON data.

private function json_output( $data=array()){
   header('Content-Type: application/json');
   echo json_encode($data);

So to test this we have the index function for the API controller.

public function index(){
       "test" => "test"

So we can call see what is returned by calling the index function via URL. Index is the default location.

To create the users part of the API we create a users function. Check it below.

public function users( $id="" ){
       $data = $this->UserModel->getAll($this->getLimit(30));
       $data = $this->UserModel->getOne($id);

Above what we do is we load the UserModel. We can then call the getAll function or the getOne function. If we have an id parameter in the URL we can get one result. With no id we return all the results from the database. So the urls will look like below.  # get All  # get One by id

Lets look at the getLimit function. We use this to limit how many records we get back in the getAll function.

private function getLimit($default=30){
       return $_GET['limit'];
      return $default;

So we check to see if we have a limit in the URL if we don’t have it we return the default limit.

So we can add a limit parameter to limit the results we get. Remember in the UserModel we can limit the results we return.

$query = $this->db->get($this->db_name, $limit);

The db->get function takes two arguments. The table name and a limit parameter. So we use this to limit the results we return from the query.

The final function we look at is the getApiData. All this does is maps the array to something more reasonable. Notice how fullname is a combination of first_name and last_name.

private function getApiData( $data ){
  return array(
       "firstname" => $data->first_name,
	"lastname" => $data->last_name,
        "fullname" => $data->first_name . ' ' . $data->last_name,
	"gender" => $data->gender,
        "age" => $data->age,
	"email" => $data->email,
	"phone" => $data->phone

So we map the results before we return the data.

And that’s it. We have created a simple API using codeigniter.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s