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/Controllers
directory.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 the app/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 a greet
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');
Conclusion
Congratulations! You have created your first REST API endpoint in CodeIgniter. This simple example can serve as a foundation for more complex APIs. In the next blog, we’ll discuss handling CRUD operations in a REST API.