REST API in CI4
6 min read Quiz at the end
Extend ResourceController to map HTTP verbs to CRUD actions with automatic JSON/XML formatting.
REST API with CI4
namespace AppControllersApi;
use CodeIgniterRESTfulResourceController;
class PostController extends ResourceController {
protected $modelName = "AppModelsPostModel";
protected $format = "json";
public function index() {
return $this->respond($this->model->findAll());
}
public function show($id = null) {
$post = $this->model->find($id);
if (!$post) return $this->failNotFound("Post not found");
return $this->respond($post);
}
public function create() {
$rules = ["title"=>"required","body"=>"required"];
if (!$this->validate($rules)) {
return $this->failValidationErrors($this->validator->getErrors());
}
$id = $this->model->insert($this->request->getJSON(true));
return $this->respondCreated(["id" => $id]);
}
public function delete($id = null) {
if (!$this->model->delete($id)) return $this->failNotFound();
return $this->respondDeleted(["id" => $id]);
}
}
// routes/api.php
$routes->resource("posts", ["controller" => "ApiPost"]);
Topic Quiz · 3 questions
Test your understanding before moving on
1. Which class does a CI4 REST controller extend?
💡 Extend CodeIgniterRESTfulResourceController for automatic REST routing.
2. What does $this->respond($data) do?
💡 respond() auto-formats response based on the client Accept header.
3. Which method returns a 404 response in ResourceController?
💡 failNotFound($message) returns a standardized 404 JSON response.