CodeIgniter 4 CRUD REST APIs Development

Share this Article
Reading Time: 10 minutes
25 Views

CodeIgniter 4 is an open source framework of PHP. It is pretty easy to handle and go with the development process. There are several development modules which is simpler to integrate in CodeIgniter 4.

Inside this article we will see that How can we create CodeIgniter 4 REST APIs development from Scratch ? We will see about each method of CRUD operation like Create, Read, Update & Delete Request APIs. This article session will give you complete idea and logic of CodeIgniter 4 APIs development with a CRUD example.

Note*: For this article, CodeIgniter v4.1 setup has been installed. May be when you are seeing, version will be updated. CodeIgniter 4.x still is in development mode.

Let’s get started.


Download & Install CodeIgniter 4 Setup

We need to download & install CodeIgniter 4 application setup to system. To set application we have multiple options to proceed. Here are the following ways to download and install CodeIgniter 4 –

  • Manual Download
  • Composer Installation
  • Clone Github repository of CodeIgniter 4

Complete introduction of CodeIgniter 4 basics – Click here to go. After going through this article you can easily download & install setup.

Here is the command to install via composer –

$ composer create-project codeigniter4/appstarter codeigniter-4

Assuming you have successfully installed application into your local system.

Now, let’s configure database and application connectivity.


Settings Environment Variables

When we install CodeIgniter 4, we have env file at root. To use the environment variables means using variables at global scope we need to do env to .env

Open project in terminal

$ cp env .env

Above command will create a copy of env file to .env file. Now we are ready to use environment variables.

CodeIgniter starts up in production mode by default. Let’s do it in development mode. So that while working if we get any error then error will show up.

# CI_ENVIRONMENT = production

// Do it to 

CI_ENVIRONMENT = development

Now application is in development mode.


Create Database & Table in Application

We need to create a database. For database we will use MySQL. We have 2 options available to create database. Either we can use PhpMyAdmin Manual interface Or we can use command to create.

CREATE DATABASE codeigniter4_app;

Next, we need a table. That table will be responsible to store data. Let’s create table with some columns.

CREATE TABLE `tbl_members` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `mobile` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table. Let’s connect with the application.


Database Connectivity to Application

Open .env file from project root. Search for DATABASE. You should see the connection environment variables.

Let’s set the value for those to connect with database.

 
#--------------------------------------------------------------------
# DATABASE
#-------------------------------------------------------------------- 
 database.default.hostname = localhost
 database.default.database = codeigniter4_app
 database.default.username = root
 database.default.password = root
 database.default.DBDriver = MySQLi
   

Now, database successfully connected with application.


Application Routes Configuration

To configure application routes, we need to open up the file /app/Config/Routes.php. This is the main routes config file where we will put all CRUD route of application.

//.. Other routes

$routes->resource('member');

Here, we have added a resource route which generates routes from CRUD operation.

In the file you can see we have a single route added, but when we back to terminal or command prompt and type the command to see available routes of application you can find as –

$ php spark routes

After running this command, you will see all routes generated by resource controller.

Let’s create Model.


Configure Application Model

Model is the face of application with the database. We need a Member Model which will do some basic model configuration.

Models are created at /app/Models. We are going to create MemberModel.php at this location.

$ php spark make:model Member --suffix
<?php

namespace App\Models;

use CodeIgniter\Model;

class MemberModel extends Model
{
	protected $DBGroup              = 'default';
	protected $table                = 'tbl_members';
	protected $primaryKey           = 'id';
	protected $useAutoIncrement     = true;
	protected $insertID             = 0;
	protected $returnType           = 'array';
	protected $useSoftDelete        = false;
	protected $protectFields        = true;
	protected $allowedFields        = [
		"name", 
		"email", 
		"mobile"
	];

	// Dates
	protected $useTimestamps        = false;
	protected $dateFormat           = 'datetime';
	protected $createdField         = 'created_at';
	protected $updatedField         = 'updated_at';
	protected $deletedField         = 'deleted_at';

	// Validation
	protected $validationRules      = [];
	protected $validationMessages   = [];
	protected $skipValidation       = false;
	protected $cleanValidationRules = true;

	// Callbacks
	protected $allowCallbacks       = true;
	protected $beforeInsert         = [];
	protected $afterInsert          = [];
	protected $beforeUpdate         = [];
	protected $afterUpdate          = [];
	protected $beforeFind           = [];
	protected $afterFind            = [];
	protected $beforeDelete         = [];
	protected $afterDelete          = [];
}

Application Controller Settings

Inside this we will write all code for application controller. This code will provide the functions for APIs. Controllers are stored inside /app/Controllers.

Need to create a controller named as Member.php

$ php spark make:controller Member --restful
<?php

namespace App\Controllers;
use App\Models\MemberModel;
use CodeIgniter\RESTful\ResourceController;

class Member extends ResourceController
{
	/**
	 * Return an array of resource objects, themselves in array format
	 *
	 * @return mixed
	 */
	public function index()
	{
		$model = new MemberModel();
        $data = $model->findAll();
        $response = [
            'status' => 200,
            'error' => null,
            'messages' => "Members Found",
            "data" => $data,
        ];
        return $this->respond($response);
	}

	/**
	 * Return the properties of a resource object
	 *
	 * @return mixed
	 */
	public function show($id = null)
	{
		$model = new MemberModel();
        $data = $model->where(['id' => $id])->first();
        if ($data) {
            $response = [
                'status' => 200,
                'error' => null,
                'messages' => "Member Found",
                "data" => $data,
            ];
            return $this->respond($response);
        } else {
            return $this->failNotFound('No Member Found with id ' . $id);
        }
	}

	/**
	 * Return a new resource object, with default properties
	 *
	 * @return mixed
	 */
	public function new()
	{
		//
	}

	/**
	 * Create a new resource object, from "posted" parameters
	 *
	 * @return mixed
	 */
	public function create()
	{
		$model = new MemberModel();

        $data = [
            'name' => $this->request->getVar('name'),
            'email' => $this->request->getVar('email'),
            'mobile' => $this->request->getVar('mobile'),
        ];

        $model->insert($data);

        $response = [
            'status' => 200,
            'error' => null,
            'messages' => "Member Saved",
        ];
        return $this->respondCreated($response);
	}

	/**
	 * Return the editable properties of a resource object
	 *
	 * @return mixed
	 */
	public function edit($id = null)
	{
		//
	}

	/**
	 * Add or update a model resource, from "posted" properties
	 *
	 * @return mixed
	 */
	public function update($id = null)
	{
		$model = new MemberModel();

        $data = [
            'name' => $this->request->getVar('name'),
            'email' => $this->request->getVar('email'),
            'mobile' => $this->request->getVar('mobile'),
        ];

        $model->update($id, $data);

        $response = [
            'status' => 200,
            'error' => null,
            'messages' => "Data Updated"
        ];
        return $this->respond($response);
	}

	/**
	 * Delete the designated resource object from the model
	 *
	 * @return mixed
	 */
	public function delete($id = null)
	{
		$model = new MemberModel();

        $data = $model->find($id);

        if ($data) {

            $model->delete($id);

            $response = [
                'status' => 200,
                'error' => null,
                'messages' => "Data Deleted",
            ];
            return $this->respondDeleted($response);
        } else {
            return $this->failNotFound('No Data Found with id ' . $id);
        }
	}
}

All the methods we have now created. Need to open these configured routes inside a API testing tool. We are opening Postman to Test APIs. You can use any other tool as per your preferences.


Testing Application APIs at Postman

We are going to start development server –

$ php spark serve

CREATE MEMBER API

URL: http://localhost:8080/member

METHOD: POST

HANDLER: \App\Controllers\Member::create

LIST MEMBER API

URL: http://localhost:8080/member

METHOD: GET

HANDLER: \App\Controllers\Member::index

SHOW SINGLE MEMBER API

URL: http://localhost:8080/member/{member_id}

METHOD: GET

HANDLER: \App\Controllers\Member::show/$1

UPDATE MEMBER API

URL: http://localhost:8080/member/{member_id}

METHOD: POST

Parameters – name, email, mobile, _method = PUT (Method Spoofing)

HANDLER: \App\Controllers\Member::update/$1

DELETE MEMBER API

URL: http://localhost:8080/member/{member_id}

METHOD: DELETE

HANDLER: \App\Controllers\Member::delete/$1

To learn about Method Spoofing in CodeIgniter 4, Click here.

We hope this article helped you to learn about CodeIgniter 4 REST APIs Development in a very detailed way.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Find More on CodeIgniter 4 here

Leave a Comment