How to Create RESTful APIs Using CodeIgniter
Introduction
CodeIgniter is a powerful PHP framework that is lightweight and easy to use, making it an excellent choice for developing RESTful APIs. In this guide, we will cover how to create a RESTful API using CodeIgniter, including setting up the environment, creating API routes, handling requests, and securing the API.
Prerequisites
Before you start, ensure you have the following:
PHP 7.2 or later
CodeIgniter 4 installed
A MySQL database (optional, for data storage)
Basic knowledge of PHP and CodeIgniter
Setting Up CodeIgniter
If you haven’t installed CodeIgniter yet, you can do so using Composer:
composer create-project codeigniter4/appstarter my_api_project
cd my_api_project
Enable .env File
Rename the .env.example
file to .env
and configure your database settings:
database.default.hostname = localhost
database.default.database = my_database
database.default.username = root
database.default.password = secret
database.default.DBDriver = MySQLi
Creating a RESTful Controller
CodeIgniter provides a ResourceController
that simplifies API development. Create a new controller:
php spark make:controller StudentController --resource
This generates StudentController.php
in app/Controllers/
with pre-defined CRUD methods.
Define API Routes
Modify app/Config/Routes.php
to add API routes:
$routes->resource('students');
This automatically maps CRUD operations to the corresponding API endpoints:
GET /students
– Fetch all studentsPOST /students
– Create a new studentGET /students/{id}
– Fetch a single studentPUT /students/{id}
– Update a studentDELETE /students/{id}
– Delete a student
Implementing API Logic
Edit app/Controllers/StudentController.php
to handle requests.
Define Model
Create a model StudentModel.php
in app/Models/
:
namespace App\Models;
use CodeIgniter\Model;
class StudentModel extends Model
{
protected $table = 'students';
protected $primaryKey = 'id';
protected $allowedFields = ['name', 'email', 'age'];
}
Implement Controller Methods
Edit StudentController.php
:
namespace App\Controllers;
use App\Models\StudentModel;
use CodeIgniter\RESTful\ResourceController;
class StudentController extends ResourceController
{
protected $modelName = 'App\Models\StudentModel';
protected $format = 'json';
public function index()
{
return $this->respond($this->model->findAll());
}
public function show($id = null)
{
$student = $this->model->find($id);
return $student ? $this->respond($student) : $this->failNotFound('Student not found');
}
public function create()
{
$data = $this->request->getPost();
if ($this->model->insert($data)) {
return $this->respondCreated($data);
}
return $this->failValidationErrors('Invalid data');
}
public function update($id = null)
{
$data = $this->request->getRawInput();
if ($this->model->update($id, $data)) {
return $this->respondUpdated($data);
}
return $this->failNotFound('Student not found');
}
public function delete($id = null)
{
if ($this->model->delete($id)) {
return $this->respondDeleted(['message' => 'Student deleted']);
}
return $this->failNotFound('Student not found');
}
}
Testing the API
Use Postman or cURL to test the endpoints.
Fetch All Students
curl -X GET http://localhost:8080/students
Create a New Student
curl -X POST http://localhost:8080/students -d "name=John Doe&email=john@example.com&age=22"
Update a Student
curl -X PUT http://localhost:8080/students/1 -d "name=Updated Name"
Delete a Student
curl -X DELETE http://localhost:8080/students/1
Securing the API
To secure the API, implement authentication and validation:
Authentication with API Key
Modify app/Filters/ApiAuthFilter.php
:
namespace App\Filters;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;
class ApiAuthFilter implements FilterInterface
{
public function before(RequestInterface $request, $arguments = null)
{
$apiKey = $request->getHeaderLine('X-API-KEY');
if ($apiKey !== 'your_secret_api_key') {
return service('response')->setJSON(['message' => 'Unauthorized'])->setStatusCode(401);
}
}
public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
{
// Optional post-processing
}
}
Enable the filter in app/Config/Filters.php
:
public $aliases = [
'apiauth' => \App\Filters\ApiAuthFilter::class,
];
Apply it to routes:
$routes->group('students', ['filter' => 'apiauth'], function ($routes) {
$routes->resource('students');
});
Conclusion
You have now created a RESTful API using CodeIgniter, complete with CRUD operations and API authentication. This setup can be extended further with features like JWT authentication, rate limiting, and versioning to enhance security and performance.