Codeigniter 4 REST API Tutorial

by Pom
~1 นาที

Install Codeigniter 4 Application

The first step begins with installing the CodeIgniter 4 application. This setup requires Composer Package Manager installed in your development machine.

composer create-project codeigniter4/appstarter ci4-api

After installation rename appstarter folder, such as codeigniter-rest-api.

Next, head over to the project folder:

cd ci4-api

Next, Copy env to .env and insert variable:

CI_ENVIRONMENT = development
app.appTimezone = 'Asia/Bangkok'

Create REST Controller

Create a controller Common.php in app/Controllers/Api/ folder. In this file we will create the functions those will relentlessly handle the Create, Read, Update and Delete operations.

<?php
namespace App\Controllers\Api;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;

class Common extends ResourceController
{
use ResponseTrait;
public function index()
{
$data = [
'error' => false,
'timestamp' => date("Y-m-d H:i:s"),
'environment' => ENVIRONMENT,
'timezone' => app_timezone()
];
return $this->setResponseFormat('json')->respond($data);
}
}

Create REST API Route

To sustain the impetus of data between client and server we need API, to access the api we also need to define the route in CI.

Open the app/Config/Routes.php file, and look for the following code.

$routes->get('/', 'Home::index');

Next, remove the above line of code and add the given line of code.

$routes->group('api', function ($routes) {
$routes->get('index', 'Api\Common::index');
});

TEST Codeigniter RESTful API

Eventually, we have gone through every imperative. Now, Its time to start the application using the following command:

php spark serve

Let us test out the REST API that gets app configuration.

http://localhost:8080/api/index