agyanadda@gmail.com

CodeIgniter 4 REST API

APIs and Advanced Topics 1 min read Updated Dec 3, 2026 Topic 24 of 30

CodeIgniter 4 makes JSON APIs easy with ResourceController and the ResponseTrait.

Create the controller

php spark make:controller Api/Products --restful creates a controller extending ResourceController. Set:

  • protected $modelName = 'App\Models\ProductModel'; — available as $this->model
  • protected $format = 'json';

Routes

$routes->resource('products') creates five API routes:

Method URL Controller method
GET /products index
GET /products/1 show
POST /products create
PUT/PATCH /products/1 update
DELETE /products/1 delete

(It also adds new and edit routes; limit with ['only' => [...]] or ['except' => 'new,edit'].)

Response helpers

  • respond($data) — 200
  • respondCreated($data) — 201
  • respondDeleted($data) — 200 after delete
  • failNotFound('Not found') — 404
  • failValidationErrors($errors) — 400
  • failUnauthorized() — 401

Read JSON input with $this->request->getJSON(true). Test with Postman or curl. Protect APIs with a token filter or Shield API tokens.

Example

Example — Products API PHP
<?php
namespace App\Controllers\Api;

use CodeIgniter\RESTful\ResourceController;

class Products extends ResourceController
{
    protected $modelName = 'App\Models\ProductModel';
    protected $format    = 'json';

    public function index()
    {
        return $this->respond($this->model->orderBy('id', 'DESC')->findAll(20));
    }

    public function show($id = null)
    {
        $product = $this->model->find($id);

        return $product ? $this->respond($product) : $this->failNotFound('Product not found');
    }

    public function create()
    {
        $data = $this->request->getJSON(true) ?? [];

        if (! $this->validateData($data, ['name' => 'required|max_length[100]', 'price' => 'required|decimal'])) {
            return $this->failValidationErrors($this->validator->getErrors());
        }
        $id = $this->model->insert($data);

        return $this->respondCreated($this->model->find($id));
    }
}

// app/Config/Routes.php
// $routes->group('api', ['namespace' => 'App\Controllers\Api'], static function ($routes) {
//     $routes->resource('products', ['except' => 'new,edit']);
// });

GET /api/products returns a JSON list. GET /api/products/99 returns 404 {"messages":{"error":"Product not found"}} if it does not exist. POST /api/products with JSON {"name":"Pen","price":"20.00"} returns 201 and the new product.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which helper returns status 201 Created?

Exercise 2 True / False

$this->request->getJSON(true) returns the JSON body as an array.

Exercise 3 Fill in the Blank

Create a REST controller with php spark make:controller Products --___

Frequently Asked Questions

Enable CORS. Newer CodeIgniter versions include a cors filter configured in app/Config/Cors.php: add the allowed origins and apply the filter to your api route group. Also handle OPTIONS preflight requests for those routes.