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->modelprotected $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)— 200respondCreated($data)— 201respondDeleted($data)— 200 after deletefailNotFound('Not found')— 404failValidationErrors($errors)— 400failUnauthorized()— 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
<?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.