In this tutorial, We will inform you how to create a Rest API example in CodeIgniter 4(CodeIgniter 4 Rest API Example Tutorial).
REST stands for Representational State Transfer. It means allows two clients to communicate with a server. the Rest API uses HTTP requests to GET, PUT, POST, and DELETE data.
There are four types of API. such as SOAP, XML-RPC, JSON-RPC. and REST. so here we will use REST API.
Overview
Step 1: Download Codeigniter
Step 2: Basic Configurations
Step 3: Create a Database in table
Step 4: Connect to Database
Step 5: Create Controller and Model
Step 6: Create REST API Route
Step 7: Run The Application
Download Codeigniter
If you want to download or install CodeIgniter 4 then you can below Url.
How To Install Codeigniter 4 Using Manual, Composer, Git
Basic Configurations
If you want to Basic Configurations in your project then you can below Url.
Codeigniter 4 Removing Index.Php From Url
Create a Database in table
In this step, We will create the database and table.
CREATE TABLE IF NOT EXISTS `students` ( `id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(64) NOT NULL, `last_name` varchar(64) NOT NULL, `address` text NOT NULL, `email` varchar(64) NOT NULL, `mobile` varchar(12) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=15 ;
Connect to Database
Go to the “app/Config/Database.php” folder and open the database.php file some changes in this file like hostname, database username, database password, and database name.
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'codeigniter4_crud', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ];
Create Controller and Model
In this step, we will a create “Student.php” controller and “StudentModel.php” model.
app/Controllers/Student.php
<?php namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\StudentModel;
class Student extends ResourceController
{
use ResponseTrait;
//get all Student data
public function index()
{
$model = new StudentModel();
$data['students'] = $model->orderBy('id', 'DESC')->findAll();
return $this->respond($data);
}
//get single student data
public function show($id = null)
{
$model = new StudentModel();
$data = $model->where('id', $id)->first();
if($data){
return $this->respond($data);
}else{
return $this->failNotFound('No Data found');
}
}
//create student data
public function create()
{
$model = new StudentModel();
$data = [
'first_name' => $this->request->getVar('first_name'),
'last_name' => $this->request->getVar('last_name'),
'address' => $this->request->getVar('address'),
'email' => $this->request->getVar('email'),
'mobile' => $this->request->getVar('mobile'),
];
$model->insert_data($data);
$response = [
'status' => 201,
'error' => null,
'messages' => [
'success' => 'Student Created successfully'
]
];
return $this->respondCreated($response);
}
//update student data
public function update($id = null)
{
$model = new StudentModel();
$data = [
'first_name' => $this->request->getVar('first_name'),
'last_name' => $this->request->getVar('last_name'),
'address' => $this->request->getVar('address'),
'email' => $this->request->getVar('email'),
'mobile' => $this->request->getVar('mobile'),
];
$update = $model->update($id,$data);
$response = [
'status' => 200,
'error' => null,
'messages' => [
'success' => 'Student Updated successfully'
]
];
return $this->respond($response);
}
//delete student data
public function delete($id = null){
$model = new StudentModel();
$data = $model->find($id);
if($data){
$model->where('id', $id)->delete();
$response = [
'status' => 200,
'error' => null,
'messages' => [
'success' => 'Student Deleted successfully'
]
];
return $this->respondDeleted($response);
}else{
return $this->failNotFound('No Data Found');
}
}
}
?>app/Models/StudentModel.php
<?php namespace App\Models;
use CodeIgniter\Database\ConnectionInterface;
use CodeIgniter\Model;
class StudentModel extends Model
{
protected $table = 'Students';
protected $allowedFields = ['first_name','last_name','address','email', 'mobile'];
}
?>
Create REST API Route
Add the following route code in the “app/config/Routes.php” file.
$routes->resource('student');
Run The Application
Now we will run our example using the postman. so you can see the below example.
http://localhost/codeigniter4_rest_api/student
Get All Records using Rest API
http://localhost/codeigniter4_rest_api/student
Get Single Record using Rest API
http://localhost/codeigniter4_rest_api/student/16

Create Record using Rest API
http://localhost/codeigniter4_rest_api/student

Update Record using Rest API
http://localhost/codeigniter4_rest_api/student

Delete Record using Rest API
http://localhost/codeigniter4_rest_api/student/20

The post CodeIgniter 4 Rest Api Example Tutorial appeared first on XpertPhp.