Code your dreams into reality.
Every line of code is a step towards a better future.
Embrace the bugs, they make you a better debugger.

Codeigniter 4 Rest API Tutorial

Last Updated on August 12, 2024 by

Many methods have been added in the new CodeIgniter 4 version, which makes it easier for developers to create REST APIs using minimal code.

Let’s start creating the REST API and call it from Postman or curl:

Step 1: Set Up CodeIgniter 4

Run the following command to install codeigniter application in server:

composer create-project codeigniter4/appstarter myproject

Step 2: Configure Database and Application

Edit .app/config/database file from root directory of project, and set up database in it:

public $default = [
    'DSN'      => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mydatabase',
    'DBDriver' => 'MySQLi',
    'DBPrefix' => '',
    'pConnect' => false,
    'DBDebug'  => (ENVIRONMENT !== 'production'),
    'cacheOn'  => false,
    'cacheDir' => '',
    'charset'  => 'utf8',
    'DBCollat' => 'utf8_general_ci',
    'returnType' => 'array',
    'strictOn' => false,
    'failover' => [],
    'saveQueries' => true,
];

Edit app/Config/App.php file, and set up base url:

public $baseURL = 'http://localhost:8080/';

Step 3: Create a Model

Create a new file ItemModel.php file in the app/Models directory to interact with the database through the model:

<?php

namespace App\Models;

use CodeIgniter\Model;

class ItemModel extends Model
{
    protected $table = 'items';
    protected $primaryKey = 'id';

    protected $allowedFields = ['name', 'description', 'price'];

    protected $validationRules = [
        'name' => 'required|min_length[3]|max_length[255]',
        'description' => 'required|min_length[3]',
        'price' => 'required|decimal',
    ];
}

Step 4: Create a Controller

Create a new file ItemController.php file in the app/Controllers directory to exchange data from server to client or client to server through rest apis methods:

<?php

namespace App\Controllers;

use CodeIgniter\RESTful\ResourceController;

class ItemController extends ResourceController
{
    protected $modelName = 'App\Models\ItemModel';
    protected $format    = 'json';

    public function index()
    {
        $items = $this->model->findAll();
        return $this->respond($items);
    }

    public function show($id = null)
    {
        $item = $this->model->find($id);
        if (!$item) {
            return $this->failNotFound('Item not found');
        }
        return $this->respond($item);
    }

    public function create()
    {
        $data = $this->request->getPost();
        if (!$this->model->insert($data)) {
            return $this->failValidationErrors($this->model->errors());
        }
        return $this->respondCreated($data);
    }

    public function update($id = null)
    {
        $data = $this->request->getRawInput();
        if (!$this->model->update($id, $data)) {
            return $this->failValidationErrors($this->model->errors());
        }
        return $this->respond($data);
    }

    public function delete($id = null)
    {
        if (!$this->model->delete($id)) {
            return $this->failNotFound('Item not found');
        }
        return $this->respondDeleted(['id' => $id]);
    }
}

Step 5: Define Routes

Edit app/Config/Routes.php and define routes for rest API:

$routes->group('api', function($routes) {
    $routes->resource('items');
});

Step 6: Test the API

Run the following command to start application server for test rest apis:

php spark serve

You can use tools like Postman or CURL to test these restful apis with parameters.

  • List Items: GET http://localhost:8080/api/items
  • Get Item: GET http://localhost:8080/api/items/{id}
  • Create Item: POST http://localhost:8080/api/items
  • Update Item: PUT http://localhost:8080/api/items/{id}
  • Delete Item: DELETE http://localhost:8080/api/items/{id}

Leave a Comment