REST API Development with Validation in CodeIgniter 4

Share this Article
Reading Time: 10 minutes
372 Views

CodeIgniter 4 is an open source framework of PHP. There are several libraries available in codeigniter 4 which makes application development very easy.

Inside this article we will see the concept of REST API development with validation in CodeIgniter 4. We will discuss about each method of CRUD operation like Create, Read, Update & Delete Request in APIs.

Additionally we will cover the API data validations and their outputs. Article is very interesting to learn and super easy to implement.

Learn more –

  • CodeIgniter 4 RESTful APIs with JWT Authentication, Click here.
  • CodeIgniter 4 CRUD REST APIs Development (without validation), Click here.
  • Basic Auth REST API Development in CodeIgniter 4, Click here.
  • Upload Image by REST API in CodeIgniter 4 Tutorial, Click here.

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.


Turn Development Mode On

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

To create a database, either we can create via Manual tool of PhpMyadmin or by means of a mysql command.

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 `employees` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(120) DEFAULT NULL,
 `email` varchar(120) DEFAULT NULL,
 `phone_no` varchar(45) DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Successfully, we have created a database and a table.


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.


Create Model

Open project into terminal and run this spark command.

$ php spark make:model Employee --suffix

It will create EmployeeModel.php file inside /app/Models folder.

Open EmployeeModel.php and write this complete code into it.

<?php

namespace App\Models;

use CodeIgniter\Model;

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

	// 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          = [];
}

Create Controller

Open project into terminal and run this spark command.

$ php spark make:controller Api/Api --suffix --restful

It will create ApiController.php file inside /app/Controllers/Api folder. Along with controller it will also create a folder.

Open ApiController.php and write this complete code into it.

<?php

namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;
use App\Models\EmployeeModel;

class ApiController extends ResourceController
{
	public function addEmployee()
	{
		$rules = [
			"name" => "required",
			"email" => "required|valid_email|is_unique[employees.email]|min_length[6]",
			"phone_no" => "required",
		];

		$messages = [
			"name" => [
				"required" => "Name is required"
			],
			"email" => [
				"required" => "Email required",
				"valid_email" => "Email address is not in format",
				"is_unique" => "Email address already exists"
			],
			"phone_no" => [
				"required" => "Phone Number is required"
			],
		];

		if (!$this->validate($rules, $messages)) {

			$response = [
				'status' => 500,
				'error' => true,
				'message' => $this->validator->getErrors(),
				'data' => []
			];
		} else {

			$emp = new EmployeeModel();

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

			$emp->save($data);

			$response = [
				'status' => 200,
				'error' => false,
				'message' => 'Employee added successfully',
				'data' => []
			];
		}

		return $this->respondCreated($response);
	}

	public function listEmployee()
	{
		$emp = new EmployeeModel();

		$response = [
			'status' => 200,
			"error" => false,
			'messages' => 'Employee list',
			'data' => $emp->findAll()
		];

		return $this->respondCreated($response);
	}

	public function singleEmployee($emp_id)
	{
		$emp = new EmployeeModel();

		$data = $emp->find($emp_id);

		if (!empty($data)) {

			$response = [
				'status' => 200,
				"error" => false,
				'messages' => 'Single employee data',
				'data' => $data
			];

		} else {

			$response = [
				'status' => 500,
				"error" => true,
				'messages' => 'No employee found',
				'data' => []
			];
		}

		return $this->respondCreated($response);
	}

	public function updateEmployee($emp_id)
	{
		$rules = [
			"name" => "required",
			"email" => "required|valid_email|min_length[6]",
			"phone_no" => "required",
		];

		$messages = [
			"name" => [
				"required" => "Name is required"
			],
			"email" => [
				"required" => "Email required",
				"valid_email" => "Email address is not in format"
			],
			"phone_no" => [
				"required" => "Phone Number is required"
			],
		];

		if (!$this->validate($rules, $messages)) {

			$response = [
				'status' => 500,
				'error' => true,
				'message' => $this->validator->getErrors(),
				'data' => []
			];
		} else {

			$emp = new EmployeeModel();

			if ($emp->find($emp_id)) {

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

				$emp->update($emp_id, $data);

				$response = [
					'status' => 200,
					'error' => false,
					'message' => 'Employee updated successfully',
					'data' => []
				];
			}else {

				$response = [
					'status' => 500,
					"error" => true,
					'messages' => 'No employee found',
					'data' => []
				];
			}
		}

		return $this->respondCreated($response);
	}

	public function deleteEmployee($emp_id)
	{
		$emp = new EmployeeModel();

		$data = $emp->find($emp_id);

		if (!empty($data)) {

			$emp->delete($emp_id);

			$response = [
				'status' => 200,
				"error" => false,
				'messages' => 'Employee deleted successfully',
				'data' => []
			];

		} else {

			$response = [
				'status' => 500,
				"error" => true,
				'messages' => 'No employee found',
				'data' => []
			];
		}

		return $this->respondCreated($response);
	}
}

We have added all methods like for add, update, single, update & delete. It covers all operation for a CRUD application.


Add Routes

Open Routes.php file from /app/Config folder. Add these routes into it.

//...

 $routes->group("api", ["namespace" => "App\Controllers\Api"] , function($routes){

	 $routes->group("employee", function($routes){

		$routes->get("list", "ApiController::listEmployee");
		$routes->post("add", "ApiController::addEmployee");
		$routes->get("single/(:num)", "ApiController::singleEmployee/$1");
		$routes->put("update/(:num)", "ApiController::updateEmployee/$1");
		$routes->delete("delete/(:num)", "ApiController::deleteEmployee/$1");
	 });
	  
});

//...

Application Testing

Start development server:

$ php spark serve

CREATE EMPLOYEE API

URL: http://localhost:8080/api/employee/add

METHOD: POST

HEADERS:

Content-Type:application/json
Accept:application/json

HANDLER: \App\Controllers\Api\ApiController::addEmployee

API Validation

API with Body Parameters

LIST EMPLOYEE API

URL: http://localhost:8080/api/employee/list

METHOD: GET

HEADERS:

Content-Type:application/json
Accept:application/json

HANDLER: \App\Controllers\Api\ApiController::listEmployee

SINGLE EMPLOYEE DETAIL API

URL: http://localhost:8080/api/employee/single/2

METHOD: GET

HEADERS:

Content-Type:application/json
Accept:application/json

HANDLER: \App\Controllers\Api\ApiController::singleEmployee

UPDATE EMPLOYEE API

URL: http://localhost:8080/api/employee/update/2

METHOD: PUT

HEADERS:

Content-Type:application/json
Accept:application/json

HANDLER: \App\Controllers\Api\ApiController::updateEmployee

DELETE EMPLOYEE API

URL: http://localhost:8080/api/employee/delete/2

METHOD: DELETE

HEADERS:

Content-Type:application/json
Accept:application/json

HANDLER: \App\Controllers\Api\ApiController::deleteEmployee

We hope this article helped you to learn REST API Development with Validation in CodeIgniter 4 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