Codeigniter 4: Creating Your First REST API Endpoint in CodeIgniter
Building a REST API in CodeIgniter starts with creating endpoints to handle client requests. In this guide, we will demonstrate how to create a simple “Hello World” REST API endpoint.
Step 1: Set Up a Controller
CodeIgniter organizes its logic into controllers. Start by creating a controller for your API:- Navigate to the
app/Controllersdirectory. - Create a new file named
HelloController.php. - Add the following code to define the controller:
namespace App\Controllers;
use CodeIgniter\RESTful\ResourceController;
class HelloController extends ResourceController {
public function index() {
return $this->respond([
'message' => 'Hello, World! Welcome to CodeIgniter REST API.'
]);
}
}
Step 2: Define a Route
Routes map URL requests to specific controller methods. Add a route for your endpoint in theapp/Config/Routes.php file:
$routes->get('hello', 'HelloController::index');
Step 3: Test Your Endpoint
- Start your development server:
php spark serve - Open your browser or use a tool like Postman to send a GET request to:
http://localhost:8080/hello - You should see the following JSON response:
{ "message": "Hello, World! Welcome to CodeIgniter REST API." }
Step 4: Expand Functionality
To add more endpoints, create additional methods in your controller and define corresponding routes. For instance, to create agreet method:
public function greet($name) {
return $this->respond([
'message' => "Hello, $name! Welcome to CodeIgniter REST API."
]);
}
Add the route:
$routes->get('hello/greet/(:any)', 'HelloController::greet/$1');

