You can create RESTfuI API in Codeigniter 4. This will be helpful when you want to manage the front end using a front end technology like React, Angular, Vue, etc. The CodeIgniter REST API can fulfill your requirement for request handling in the backend. The REST API will handle the request sent through the front-end application. It will control the request and after processing, you will get the response. This is a simple architecture of exchanging data based on the request to the front-end application. In this post, you will be learning how to create Restful API Codeigniter 4. Here, we will see the different request types which will be used in the request handling. Most commonly GET and POST methods are used with form. But, with REST API, we will see GET, POST, PUT and DELETE.
For creating the RESTful API in CodeIgniter 4, we will create a new project.
Prerequisites
To create a project in CodeIgniter 4, your system must have the following configurations.
- PHP >= 7.3
- MySQL (version > 5)
- Apache/Nginx Server
- VS Code Editor
- Composer
- Postman
Once you are ready, create a new project using composer.
CodeIgniter 4 Ajax Form Handling With Form Validation
Create a New Project For REST API in Codeigniter 4
At the very first, open the terminal or command prompt whatever you use. Now, hit the below command to have a new project set up.
composer create-project codeigniter4/appstarter ci4-rest-api
The command will create a new folder. Then inside the folder, it will install Codeigniter 4 files and dependencies.
After creating the project, open it in VS Code editor for the configuration.
Resize Image By Image Manipulation in CodeIgniter 4
Project Environment and Database Configuration
Once, you opened the project in VS Code editor, just look for the env file. Now, you have to rename it to .env. Then come under that file (.env). By default, all the environment configurations are commented on inside the .env file.
Firstly, you have to uncomment CI_ENVIRONMENT and change the production to development.
Secondly, scroll down and come under the database configuration. Add the database credentials as shown below.
database.default.hostname = localhost
database.default.database = ci4_rest_api
database.default.username = root
database.default.password = root
database.default.DBDriver = MySQLi
database.default.DBPrefix =
The database configuration will look as shown in the result.
Now, let’s move to the migration for the CodeIgniter 4 REST API.
Create Migration in CodeIgniter 4 For REST API
In this RESTful API demo, I will make CRUD operations for students. Hence, it is required a database table. Hence, I am going to create a migration file for managing the schema.
In order to create a schema in CodeIgniter 4, you can run the below spark command.
php spark make:migration Student
This will generate a new file inside the app/Database/Migrations folder.
After creating the migration, let’s add the below schema. I have added a couple of fields for now. You can add more if you required.
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Migration;
class Student extends Migration
{
public function up()
{
$this->forge->addField([
'id' => [
'type' => 'INT',
'auto_increment' => true
],
'name' => [
'type' => 'VARCHAR',
'constraint' => '100'
],
'email' => [
'type' => 'VARCHAR',
'constraint' => '100'
],
'created_at datetime default current_timestamp',
'updated_at datetime default current_timestamp on update current_timestamp'
]);
$this->forge->addKey('id', true);
$this->forge->createTable('students');
}
public function down()
{
$this->forge->dropTable('students');
}
}
Now, in the next step, this schema should be dumped into the database. Hence, there is a command to migrate the created schema in the configured database.
php spark migrate
It will take a couple of seconds to dump out in the database based on the available migrations file.
You have the table now. In the next step, let’s create a model respective to this table. Actually, we will be using model eloquent instead of DB query. Hence, let’s do that.
Login and Registration Authentication in Codeigniter 4
Create a Model in CodeIgniter 4 For REST API
We will create a model for the student. Therefore, to create a model, use the below command.
php spark make:model Student
Here, the Student model has been created.
After creating the model, navigate to the model class and add the below snippets.
<?php
namespace App\Models;
use CodeIgniter\Model;
class Student extends Model
{
protected $DBGroup = 'default';
protected $table = 'students';
protected $primaryKey = 'id';
protected $useAutoIncrement = true;
protected $insertID = 0;
protected $returnType = 'array';
protected $useSoftDeletes = false;
protected $protectFields = true;
protected $allowedFields = ['name', 'email'];
// Dates
protected $useTimestamps = false;
protected $dateFormat = 'datetime';
protected $createdField = 'created_at';
protected $updatedField = 'updated_at';
protected $deletedField = 'deleted_at';
}
In the model, we configured the table name. Also, we set the allowed fields as per the schema of students table. Now, it’s time to create a RESTful controller in CodeIgniter 4.
Create RESTful Controller in CodeIgniter 4 For REST API
You can create a basic controller class or RESTful class in Codeigniter 4. For our application, we are going to create a RESTful API. Therefore, it required a restful controller.
So, in the terminal, hit the below command with the given flag.
php spark make:controller Students --restful
Here, the --restful
flag will generate the default functions in the controller for the CRUD operations.
Add Functionalities of RESTful API in Controller
In the Student controller class, you will notice, it is extending ResourceController. In this base class, there are predefined methods for managing CRUD functionality such are –
- index
- create
- new
- show
- edit
- update
- delete
Here, we will not be taking inputs from the form. Therefore, we won’t use all the above methods in the Students controller.
<?php
namespace App\Controllers;
use App\Models\Student;
use CodeIgniter\RESTful\ResourceController;
class Students extends ResourceController
{
private $student;
public function __construct()
{
$this->student = new Student();
}
/**
* Return an array of resource objects, themselves in array format
*
* @return mixed
*/
public function index()
{
$students = $this->student->findAll();
return $this->respond($students);
}
/**
* Return the properties of a resource object
*
* @return mixed
*/
public function show($id = null)
{
$student = $this->student->find($id);
if ($student) {
return $this->respond($student);
}
return $this->failNotFound('Sorry! no student found');
}
/**
* Create a new resource object, from "posted" parameters
*
* @return mixed
*/
public function create()
{
$validation = $this->validate([
'name' => 'required',
"email" => "required|valid_email|is_unique[students.email]|min_length[6]",
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$student = [
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email')
];
$studentId = $this->student->insert($student);
if ($studentId) {
$student['id'] = $studentId;
return $this->respondCreated($student);
}
return $this->fail('Sorry! no student created');
}
/**
* Add or update a model resource, from "posted" properties
*
* @return mixed
*/
public function update($id = null)
{
$student = $this->student->find($id);
if ($student) {
$validation = $this->validate([
'name' => 'required',
"email" => "required|valid_email",
]);
if (!$validation) {
return $this->failValidationErrors($this->validator->getErrors());
}
$student = [
'id' => $id,
'name' => $this->request->getVar('name'),
'email' => $this->request->getVar('email')
];
$response = $this->student->save($student);
if ($response) {
return $this->respond($student);
}
return $this->fail('Sorry! not updated');
}
return $this->failNotFound('Sorry! no student found');
}
/**
* Delete the designated resource object from the model
*
* @return mixed
*/
public function delete($id = null)
{
$student = $this->student->find($id);
if ($student) {
$response = $this->student->delete($id);
if ($response) {
return $this->respond($student);
}
return $this->fail('Sorry! not deleted');
}
return $this->failNotFound('Sorry! no student found');
}
}
After adding functionalities. Let’s add the routes for executing the functions.
How to Send Email in CodeIgniter 4 Using Gmail SMTP
Add RESTful Route in CodeIgniter 4
For adding a route, navigate to the config/Route.php and add a single resource route. We created the restful controller. Therefore for executing all its methods, we don’t require the route separately. Instead, the single resource route will work.
$routes->resource('students');
That’s it for the functionality. Now, we are ready to test our RESTful Api in CodeIgniter 4.
CodeIgniter 4 RESTful API Results
For testing the API result, open Postman. Now, let’s start with creating a new student.
Post Request – Create Student
Endpoint: http://localhost:8080/students
Request Type: POST
Request Body:
{
"name": "John Doe",
"email": "johndoe@test.com"
}
Firstly, hit this API endpoint without the request body. So, that we can see the validation error message. In the below result, you can see, I have hit the API without the request body. In the response, I got the validation error for the name and email field.
If you enter the only name but email has skipped. Then for this case, you will also get the validation error.
Next, I have entered the name, but the email is not a valid email. Here, I got the response for a valid email address.
So, this was the basic validation for the data. Now, let’s fill up the required details and hit the API again. If the student is created then in the response you will get the inserted data.
I have created a few records so that we can check the GET request now.
GET Request – Get All Students
For getting all students, change the request method to GET. Remove the request body. Now, hit the API.
Endpoint: http://localhost:8080/students
Request Type: GET
In the response, you will get the list of students as shown below.
Get Single Student
If you want to get detail of a student then you have to pass the id of that student as a parameter.
Endpoint: http://localhost:8080/students/{id}
Request Type: GET
In the result, you will get the data of the given id.
In case, if you enter any id that doesn’t belong to any student then it will return a 404 not found response.
PUT Request – Update Record
For updating any field of a specific student, you have to use a PUT request.
Endpoint: http://localhost:8080/students/{id}
Request Type: PUT
Request Body:
{
"name": "John Doe",
"email": "johndoe@test.com"
}
Let’s see the result by updating the email of the given student id.
If the field has been updated, it will return the updated details as shown above.
While updating the student, if you enter an invalid id that doesn’t belong to any student then it will return 404.
The validation will also apply to the update API for the request body.
DELETE Request – For Deleting Record
For deleting a student record, we have a DELETE request. Pass the id of the student that is going to be deleted.
Endpoint: http://localhost:8080/students/{id}
Request Type: DELETE
If the entered id doesn’t belong to any student then it will throw 404.
If that id belongs to any student then it will return the deleted student record.
Conclusion
We created a RESTful API for a basic CRUD application in CodeIgniter 4. In this post, I tried to give you a basic demonstration of RESTful API. We have seen, how we handled different request types in CodeIgniter 4 resource routing. CodeIgniter 4 provides a Restful controller for handling CRUD operations. I hope you will find helpful to this post.
Leave a Reply