CodeIgniter 4 Rest Api Example Tutorial
Codeigniter tutorial, you will learn how to create REST APIs in PHP CodeIgniter 4 framework. REST APIs are used to exchange data between applications and servers. This tutorial will show you how to create, read, update, and delete data from a database table using REST APIs in CodeIgniter 4. Before creating a REST API, it’s important to understand the architecture of a RESTful API. By following the steps outlined in this tutorial, you’ll be able to create a REST API in CodeIgniter 4 and use it to exchange data between your server and applications.
How to Create RESTful API in CodeIgniter 4

Follow the below given steps and create rest API in CodeIgniter 4 framework:
- Create Database and Table
- Download Codeigniter Latest
- Basic Configurations
- Setup Database Credentials
- Create Model
- Create Controller
- Start Development server
Step 1: Create Database and Table
Now, we need to create a database for our CodeIgniter 4 application. To do this, we will use PHPMyAdmin, which is a popular web-based database management tool.
To get started, open PHPMyAdmin and create a new database with the name “demo”. You can do this by selecting the “New” button from the left-hand menu and then entering the name “demo” in the appropriate field.
After that, select your database and run the following sql query to create a Product table into your database:
CREATE TABLE product(
product_id INT(11) PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(200),
product_price DOUBLE
)ENGINE=INNODB;
Next, run the following query to insert some data into product table:
INSERT INTO product(product_name,product_price) VALUES
('Product 1','2000'),
('Product 2','5000'),
('Product 3','4000'),
('Product 4','6000'),
('Product 5','7000');
Step 2: Download Codeigniter Project
To get started with CodeIgniter 4, the first step is to download the latest version of the framework. You can download the framework from the official CodeIgniter website at https://codeigniter.com/download.
Once you have downloaded the CodeIgniter 4 setup, unzip the archive and save it in your local system. You can save it in the XAMPP/htdocs/ directory if you are using XAMPP as your local development environment.
Step 3: Basic Configurations
Now, we need to configure some basic settings in the “app/config/app.php” file. To do this, we will open the “config.php” file located in the “application/config” folder using a text editor.
Set Base Url Like This
public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';
Step 4: Setup Database Credentials
Now, we need to connect our CodeIgniter 4 project to the database. To do this, we will open the “database.php” file located in the “app/Config” folder using a text editor.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'demo',
'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,
];
Step 5: Create Model
To create a model in CodeIgniter 4, go to the “app/Models/” directory and create a new file called “ProductModel.php”. Then, add the following code to the “ProductModel.php” file:
<?php namespace App\Models;
use CodeIgniter\Model;
class ProductModel extends Model
{
protected $table = 'product';
protected $primaryKey = 'product_id';
protected $allowedFields = ['product_name','product_price'];
}
Step 6: Create Controller
Now, Navigate app/Controllers and create a controller name Products.php. Then update the following method into Products.php controller file:
<?php namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ProductModel;
class Products extends ResourceController
{
use ResponseTrait;
// get all product
public function index()
{
$model = new ProductModel();
$data = $model->findAll();
return $this->respond($data);
}
// get single product
public function show($id = null)
{
$model = new ProductModel();
$data = $model->getWhere(['product_id' => $id])->getResult();
if($data){
return $this->respond($data);
}else{
return $this->failNotFound('No Data Found with id '.$id);
}
}
// create a product
public function create()
{
$model = new ProductModel();
$data = [
'product_name' => $this->request->getVar('product_name'),
'product_price' => $this->request->getVar('product_price')
];
$model->insert($data);
$response = [
'status' => 201,
'error' => null,
'messages' => [
'success' => 'Data Saved'
]
];
return $this->respondCreated($response);
}
// update product
public function update($id = null)
{
$model = new ProductModel();
$input = $this->request->getRawInput();
$data = [
'product_name' => $input['product_name'],
'product_price' => $input['product_price']
];
$model->update($id, $data);
$response = [
'status' => 200,
'error' => null,
'messages' => [
'success' => 'Data Updated'
]
];
return $this->respond($response);
}
// delete product
public function delete($id = null)
{
$model = new ProductModel();
$data = $model->find($id);
if($data){
$model->delete($id);
$response = [
'status' => 200,
'error' => null,
'messages' => [
'success' => 'Data Deleted'
]
];
return $this->respondDeleted($response);
}else{
return $this->failNotFound('No Data Found with id '.$id);
}
}
}
In the above controller method works as follow:
- Index() – This is used to fetch all product.
- create() – This method is used to insert product info into DB table.
- update() – This is used to validate the form data server-side and update it into the MySQL database.
- show() – This method is used to fetch single product info into DB table.
- delete() – This method is used to delete data from the MySQL database.
Now Navigate to App/Configuration folder. And Open the file “Routes.php”, then find the following code:
$Route->get('/', 'home :: index');
Then, change the following:
$Route->resource('product');
This configuration allows us to access the following EndPoint:
Step 7: Start Development server
Open your terminal and run the following command to start development server:
php spark serve
Next, Open the postman app to call above created APIs as follow:
1: Get all products info from DB table, you can call get all product info api in postman app as follow:
http://localhost:8080/products

2: And if you want to get single product info, you can use the as follow in postman app:
http://localhost:8080/products/10

3: For insert new product info into DB table, you can call create apis as follow:
http://localhost:8080/products

4: For update info into DB table using the update api, you can call update info api as follow:

5: For delete product info using codeigniter api, you can call delete api as follow:

Conclusion
In this tutorial about Codeigniter 4, you learned how to make a restful API using this framework.
You May Also Like
- Codeigniter 4 CRUD with Bootstrap and MySQL Example
- CodeIgniter 4 Pagination Example Tutorial
- CodeIgniter 4 Multiple Image File Upload Example
- Codeigniter 4 Ajax Image Upload with Preview Example
- Codeigniter 4 Database & Email Config Example
- Codeigniter 4 jQuery Image Upload with Preview Example
- CodeIgniter 4 Image File Upload Example

