Codeigniter 4 REST API Development Example Tutorial

Codeigniter 4 REST API Development Example

PHP Codeigniter 4 RESTful API tutorial; This comprehensive guide will step by step explain how to create REST API in Codeigniter 4 application.

You will also learn how to test RESTful API in the postman API development tool.

The REST API creates coherence between the remote server and the application. You must be thinking, why do we need REST APIs? Well, rest API is useful for exchanging the information between app and server.

This Codeigniter API example will reveal every instruction which helps you get started with REST API development in Codeigniter 4.

How to Create CRUD REST API in Codeigniter 4 App

  • Step 1: Install New Codeigniter App
  • Step 2: Add Database Credentials
  • Step 3: Generate Table in Database
  • Step 4: Build Controller File
  • Step 5: Create API Routes
  • Step 6: Run Development Server
  • Step 7: Test REST API with Postman

Install New Codeigniter App

Downloading a Codeigniter app is easy; you can simply download it Codeigniter from:

https://www.codeigniter.com/download

Next, Unzip the package, change the project’s name, and keep Codeigniter files and folder in your server directory.

Another way is to download the app is by the Composer command.

composer create-project codeigniter4/appstarter

Add Database Credentials

After you have successfully install the brand new codeigniter app, its time to make the app connection with database.

Open app/Config/Database.php and enter your username, password, and database name.

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'db_username',
        'password' => 'db_password',
        'database' => 'db_name',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
    ];

Generate Table in Database

SQL query is the best option for generating a table, and adding the dummy records into the table.

Next, let’s add a new table into the database, name it customers or anything you want;

Execute provided command in the SQL console.

--
-- Table structure for `customers` table 
--

CREATE TABLE `customers` (
  `id` int(11) NOT NULL COMMENT 'Primary Key',
  `name` varchar(100) NOT NULL COMMENT 'name',
  `email` varchar(100) NOT NULL COMMENT 'email'
) ENGINE=InnoDB DEFAULT CHARSET=latin1 COMMENT='Customers collection';

--
-- Dumping data in `customers` table
--

INSERT INTO `customers` (`id`, `name`, `email`) VALUES
(1, 'Jessica Pierce', '[email protected]'),
(2, 'Tim Spencer', '[email protected]'),
(3, 'Charlie Brewer', '[email protected]'),
(4, 'Yvonne Washington', '[email protected]'),
(5, 'Marion Matthews', '[email protected]'),
(6, 'Marshall Palmer', '[email protected]'),
(7, 'Joshua Torres', '[email protected]'),
(8, 'Mario Powell', '[email protected]'),
(9, 'James Ferguson', '[email protected]'),
(10, 'Delores Little', '[email protected]'),
(11, 'Phillip Bennett', '[email protected]'),
(12, 'Lee Washington', '[email protected]'),
(13, 'Harold Ramirez', '[email protected]'),
(14, 'Marcia Diaz', '[email protected]'),
(15, 'Ramona Castillo', '[email protected]');

Set Up Model File

Head over to the app/Models/ folder, create an ApiModel.php file within the models’ directory.

Next, define ApiModel class, extend it with Model service, and define your table name and the table properties.

Update code in app/Models/ApiModel.php file.

<?php 

namespace App\Models;
use CodeIgniter\Model;

class ApiModel extends Model
{
    protected $table = 'customers';
    protected $primaryKey = 'id';
    protected $allowedFields = [
      'name', 
      'email'
    ];
}

Build Controller File

Get into the app/Controllers folder; you need to create a brand new file, give it a name (ApiController.php).

In this file, you have to add the complete functions, which will help handle the CRUD operations.

Append the given code in app/Controllers/Customer.php file.

<?php 

namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use App\Models\ApiModel;


class Customer extends ResourceController
{

    use ResponseTrait;

    // get all
    public function index(){
      $apiModel = new ApiModel();
      $data = $apiModel->orderBy('id', 'DESC')->findAll();
      return $this->respond($data);
    }

    // create
    public function create() {
        $apiModel = new ApiModel();
        $data = [
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
        ];
        $apiModel->insert($data);
        $response = [
          'status'   => 201,
          'error'    => null,
          'messages' => [
              'success' => 'Customer created'
          ]
      ];
      return $this->respondCreated($response);
    }

    // single
    public function getCustomer($id = null){
        $apiModel = new ApiModel();
        $data = $apiModel->where('id', $id)->first();
        if($data){
            return $this->respond($data);
        }else{
            return $this->failNotFound('Customer does not exist.');
        }
    }

    // update
    public function update($id = null){
        $apiModel = new ApiModel();
        $id = $this->request->getVar('id');
        $data = [
            'name' => $this->request->getVar('name'),
            'email'  => $this->request->getVar('email'),
        ];
        $apiModel->update($id, $data);
        $response = [
          'status'   => 200,
          'error'    => null,
          'messages' => [
              'success' => 'Customer updated.'
          ]
      ];
      return $this->respond($response);
    }

    // delete
    public function delete($id = null){
        $apiModel = new ApiModel();
        $data = $apiModel->where('id', $id)->delete($id);
        if($data){
            $apiModel->delete($id);
            $response = [
                'status'   => 200,
                'error'    => null,
                'messages' => [
                    'success' => 'Customer deleted'
                ]
            ];
            return $this->respondDeleted($response);
        }else{
            return $this->failNotFound('Customer does not exist.');
        }
    }

   
}

Create API Routes

The main reason to define routes is to initialize the methods and functions we formed in the controller class; These routes will execute the controller functions for the crud operations.

To make the request using the REST API requires setting up routes into the app/Config/Routes.php file.

After getting into the routes file, find the below route.

$Route->get('/', 'home::index');

Make sure to add the given route and remove the above url.

/*
 * --------------------------------------------------------------------
 * Route Definitions
 * --------------------------------------------------------------------
*/

$routes->resource('customer');

Run Development Server

We followed almost every instruction so far and created the desired feature.

Do one more thing and start the app and use url to run the app in the view.

php spark serve

You can use the below url as the base url; remember, you can switch the localhost to your domain name if developing on the server.

http://localhost:8080/customer

Test REST API with Postman

Once the app development server has started, open the Postman API development app and start testing the APIs we have built.

For creating the brand new client record in the database use the following REST API.

Codeigniter Create REST API

For updating the client record in the database through the REST API, you can use the below API.

Codeigniter Update API

If you want to retrieve the single object from the database, paste the provided API with the id in the postman.

Codeigniter Get Single REST API

To get all the records located in the database, use the provided REST API in the postman app. Select the GET method, and relentlessly click on the send button.

Codeigniter GET All Record REST API

For deleting a client record from the database use the suggested REST API in the postman app.

Codeigniter Delete REST API Example

Conclusion

A RESTful API is an application programming interface (API or web API) that corresponds to REST architectural style and grants for communication with RESTful web services. In this tutorial, we learned how to create Codeigniter CRUD REST APIs and test them in postman.