Hi, in this tutorial, you will learn how to use the REST API CRUD in CodeIgniter 4.
In CodeIgniter 4, various libraries help developers build projects faster. With its resource routes and ResourceController, CodeIgniter 4 makes it simple to develop RESTful APIs.
This example includes a complete guide that teaches how to create a REST API in a Codeigniter 4 application step by step.
I'll teach you how to use the Postman tool to test a Restful API that communicates with a MySQL database.
So, Let’s start.
Table Content
1. What is REST?
2. What's an API?
3. Download Codeigniter 4
4. Turn Development Mode On
5. Create New Database and Table
6. Connect Database Credentials
7. Create Model
8. Creat Controller
9. Add Routes
10. Test Application
Before continuing with the tutorial, it is essential to know what REST API is.
What is REST?
REST (REpresentational State Transfer) is an interactive approach architectural that involves the HTTP protocol (GET, PUT, POST, DELETE.) for information exchange between apps and servers.
What's an API?
An application programming interface (API) is a set of principles and protocols for creating and combining web applications.
In other words, if you wish to connect with a system to retrieve data, an API allows you to convey your request to the system so that it can interpret and reply.
For instance, the API design for a weather forecast could require the client to provide a postal code and the server to respond with a two-part response, the first of which is the high temperature and the second of which is the low temperature.
The REST API (also known as RESTful API) is a data communication interface that connects the app (client) and the server.
Now dive into the tutorial.
Download Codeigniter 4
It's simple to get a Codeigniter framework; just go to the official Codeigniter 4 site and manually download it.
After that, extract the package, rename the project, and save the Codeigniter files and folder to your server location.
Because I use the XAMPP server on my PC, I set it up under the xampp/htdoc folder.
If you're using WAMP, unpack CodeIgniter and place it in the www folder.
Take a look at the structure of the project files.
xampp/
+-- htdocs/
+-- CodeIgniter-4-Rest-API-CRUD/
+-- app/
+-- controllers/
¦ +-- BaseController
¦ +-- Home
¦ +-- User
+-- Models/
¦ +-- UserModel
¦system
¦writable
¦env
Turn Development Mode On
We have an env file at the root of the CodeIgniter 4 installation.
By default, CodeIgniter starts in production mode. Let's do it in development mode first.
#CI_ENVIRONMENT = production
Remove # and update it to
CI_ENVIRONMENT = development
Create New Database and Table
You must construct a database in this phase. Create a database with the name "codeigniter_rest_api_crud_db" in PHPMyAdmin.
After you've successfully created a database, run the SQL statement below to create a user table in it.
CREATE TABLE `tbl_user` (
`user_id` int(11) NOT NULL,
`firstname` varchar(30) NOT NULL,
`lastname` varchar(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
Connect Database Credentials
After you've successfully installed the new Codeigniter 4 project, you'll need to link it to the database in this step.
Enter your username, password, and database name in the app/Config/Database.php file.
public $default = [
'DSN' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => '',
'database' => 'codeigniter_rest_api_crud_db',
'DBDriver' => 'MySQLi',
'DBPrefix' => '',
'pConnect' => false,
'DBDebug' => (ENVIRONMENT !== 'production'),
'charset' => 'utf8',
'DBCollat' => 'utf8_general_ci',
'swapPre' => '',
'encrypt' => false,
'compress' => false,
'strictOn' => false,
'failover' => [],
'port' => 3306,
];
Create Model
To do database operations, you'll require a model class. We implement CRUD operations for the Rest API in this example.
Our table name, primary id, and fields are all stored in the model class.
In the app/Model/ folder, we must build a new UserModel.php file. To create the User Model, write the following code in the same file.
The name of the database table must be defined in the $table variable of this class.
protected $table = 'tbl_user';
The primary key for the user table must be defined in the $primaryKey variable.
protected $primaryKey = 'user_id';
We must define table fields names (firstname, lastname) in the $allowedFields variable, which will be utilized for database operations.
protected $allowedFields = ['firstname','lastname'];
app\Models\UserModel.php
<?php
namespace App\Models;
use CodeIgniter\Model;
class UserModel extends Model
{
protected $table = 'tbl_user';
protected $primaryKey = 'user_id';
protected $allowedFields = ['firstname','lastname'];
}
Creat Controller
In this section of the tutorial, we'll build the new controller called User.php within app\Controllers.
To accomplish the required operations, the following resource controller sets endpoints for REST APIs and interacts with the database table. We do CRUD operations in this example.
With the resource() method, you can rapidly establish RESTful routes for a single resource.
Create a new resource, update an existing one, list all of that resource, show a single resource, and delete a single resource are the five most typical routes created using the resource() method.
The resource name is the first parameter ( controller name ).
$routes->get('user/new', 'User::new');
$routes->post('user', 'User::create');
$routes->get('user', 'User::index');
$routes->get('user/(:segment)', 'User::show/$1');
$routes->get('user/(:segment)/edit', 'User::edit/$1');
$routes->put('user/(:segment)', 'User::update/$1');
$routes->patch('user/(:segment)', 'User::update/$1');
$routes->delete('user/(:segment)', 'User::delete/$1');
In the following resource User controller class, we'll implement RESTful endpoints.
Index() – This is used to get a list of all users from the database table.
create() – This function is used to submit the database table with new user records.
show() – This function is used to get a single user record from a database table with a given id.
update() – This is used to update the database table with existing user records.
delete() – This function deletes specified user data from the database based on a table id.
app/Controllers/User.php
<?php
namespace App\Controllers;
use App\Models\UserModel;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\RESTful\ResourceController;
class User extends ResourceController
{
use ResponseTrait;
// fetch all user records
public function index()
{
$model = new UserModel();
$data = $model->findAll();
return $this->respond($data);
}
// create new user records
public function create()
{
$model = new UserModel();
$rules = [
'firstname' => 'required',
'lastname' => 'required'
];
if(!$this->validate($rules))
{
return $this->fail($this->validator->getErrors());
}
else
{
$data = [
'firstname' => $this->request->getVar("firstname"),
'lastname' => $this->request->getVar("lastname"),
];
}
$model->insert($data);
$response = [
'message' => 'User Inserted Successfully'
];
return $this->respondCreated($response);
}
//fetch user record from specific id
public function show($id = null)
{
$model = new UserModel();
$data = $model->where(['user_id' => $id])->first();
if($data)
{
return $this->respond($data);
}
else
{
return $this->failNotFound('No User Found with id' . $id);
}
}
// update existing user records
public function update($id = null)
{
$model = new UserModel();
$rules = [
'firstname' => 'required',
'lastname' => 'required'
];
if(!$this->validate($rules))
{
return $this->fail($this->validator->getErrors());
}
else
{
$data = [
'firstname' => $this->request->getVar("firstname"),
'lastname' => $this->request->getVar("lastname"),
];
}
$model->update($id, $data);
$response = [
'message' => 'User Updated Successfully',
'data' => $data
];
return $this->respond($response);
}
// delete existing user records
public function delete($id = null)
{
$model = new UserModel();
$data = $model->find($id);
if($data)
{
$model->delete($id);
$response = [
'message' => 'User Deleted Successfully'
];
return $this->respondDeleted($response);
}
else
{
return $this->failNotFound('No Data Found with id' . $id);
}
}
}
Codes Explanation:
First, we import the UserModel class for database operations in the above class file.
ResourceController:
We extend ResourceController and add the methods that will be used to conduct CRUD operations.
With methods that match the resource routes above, the ResourceController provides a nice starting point for our RESTful API.
ResponseTrait:
We used the API Response trait provided by CodeIgniter above in the User controller to make common response kinds simple, eliminating the need to remember which HTTP status code should be returned for specific response types.
Read All Records:
The index() function returns a list of all records in our user table.
$model is the name of the UserModel class object that was created.
All data will be displayed if $model->findAll(); is appropriately executed.
$this->respond($data) – It's a common response method that returns a status code as a response.
// fetch all user records
public function index()
{
$model = new UserModel();
$data = $model->findAll();
return $this->respond($data);
}
Create New Records:
The create() function populates the database table with new user records.
$model is the name of the newly created UserModel class object.
$rules = [ ]; – This array contains the validation rules for the keys and values. The keys in this case are table fields, and the values are the values we'll use in the postman tool.
The validate() method uses the $rules array, which contains table field validation. Validation is checked with the validate() method.
if (!$this->validate($rules)) { } – It validates key values instead of validation requirements that are left blank. When any of the rules aren't met, the validation responds that the fields' values are required.
To get values from the inputted Postman tool, use the getVar() method inside the $data [] array.
The insert() method will generate a new record in the user table if the data is not blank.
$this->respondCreated() – It will return a status code for the user-created response.
// create new user records
public function create()
{
$model = new UserModel();
$rules = [
'firstname' => 'required',
'lastname' => 'required'
];
if(!$this->validate($rules))
{
return $this->fail($this->validator->getErrors());
}
else
{
$data = [
'firstname' => $this->request->getVar("firstname"),
'lastname' => $this->request->getVar("lastname"),
];
}
$model->insert($data);
$response = [
'message' => 'User Inserted Successfully'
];
return $this->respondCreated($response);
}
Fetch Specific Records:
The show() function retrieves records with certain table ids.
$model is a new object I made. The model of the UserModel class.
$model->where('user_id', $id)->first() – From a specified id value, a single row of data is read. The $data variable is also filled with records.
$this->respond($data) – It will reply with particular id records and a status code.
$this->failNotFound() – It will return a not found response if the id number is not detected.
//fetch user record from specific id
public function show($id = null)
{
$model = new UserModel();
$data = $model->where(['user_id' => $id])->first();
if($data)
{
return $this->respond($data);
}
else
{
return $this->failNotFound('No User Found with id' . $id);
}
}
Update Records:
The update() function updates existing records.
The $model is an object of the UserModel class.
$rules = [ ]; – This array contains the validation rules for the keys and values. The keys in this case are table fields, and the values are the values we'll use in the postman tool.
The validate() method uses the $rules array, which contains table field validation. Validation is checked with the validate() function.
if (!$this->validate($rules)) { } – It validates key values rather than validation requirements that are left blank. When any of the rules aren't met, the validation returns that the fields' values are required.
To get values from the inputted Postman tool, use the getVar() method inside the $data [] array.
Include the $id and $data arrays in the update() method.
The update() method will be operated to update an existing record in the user table if the values are not blank.
$this->respond($data) – It will return with an updated status code.
// update existing user records
public function update($id = null)
{
$model = new UserModel();
$rules = [
'firstname' => 'required',
'lastname' => 'required'
];
if(!$this->validate($rules))
{
return $this->fail($this->validator->getErrors());
}
else
{
$data = [
'firstname' => $this->request->getVar("firstname"),
'lastname' => $this->request->getVar("lastname"),
];
}
$model->update($id, $data);
$response = [
'message' => 'User Updated Successfully',
'data' => $data
];
return $this->respond($response);
}
Delete Records:
The delete() function is used to remove data that has already been saved.
$model is the name of a new UserModel object created.
The delete() method will remove an existing record in the user table if the id value is recognized.
$this->respondDeleted() – It will return with a status code for records that have been removed.
$this->failNotFound() – It will return a not found response if the id number is not detected.
// delete existing user records
public function delete($id = null)
{
$model = new UserModel();
$data = $model->find($id);
if($data)
{
$model->delete($id);
$response = [
'message' => 'User Deleted Successfully'
];
return $this->respondDeleted($response);
}
else
{
return $this->failNotFound('No Data Found with id' . $id);
}
}
Add Routes
The major purpose of defining routes is to activate the methods and functions we created in the controller class; these routes will run the crud operations controller routines.
We've implemented a resource route that creates CRUD operation routes here.
The ‘user’ is our controller or resource.
I commented default Home::index, which opens the default Codeigniter 4 index page.
From the /app/Config folder, open Routes.php. This route must be added to it.
app\Config\Routes.php
//$routes->get('/', 'Home::index');
$routes->resource('user');
Test Application
Because I developed this application on a localhost server, here is my basic URL.
http://localhost/CodeIgniter-4-Rest-API-CRUD/user
To run your application using the CLI, enter the following command in the root directory of your project.
php spark serve
Localhost and port 8080 will be used to run your application. The below URL is your default URL.
http://localhost:8080/user
Let's throw the application to the test. Before you launch your application, make sure the MySQL database server is running.
Here I used use Postman tool.
Fetch All User Records
To display all user records, use the Postman tool and enter the following URL, pick the GET method, and click the Send button.
Method | REST API URL |
---|---|
GET | http://localhost/CodeIgniter-4-Rest-API-CRUD/user |
Add New User Records
To add new user records to the table, type the following URL into the postman tool.
Method | REST API URL |
---|---|
POST | http://localhost/CodeIgniter-4-Rest-API-CRUD/user/create |
Select the POST method, then select the form-data in the Body tab, fill in the keys and values, then hit the Send button.
Here key communicates table fields and value gets parameters values. If the API is successfully executed, new user records will be created.
Take a look at the new user entries that have been added to the table.
Update Existing User Records
The following URL can be used to update existing user records.
Method | REST API URL |
---|---|
POST | http://localhost/CodeIgniter-4-Rest-API-CRUD/user/10 |
Select the POST method, then select the form-data in the Body tab, fill in the keys and values, then hit the Send button.
In the last column, you will use _method in the key and PUT in the value because without both you can not update existing records.
Here key communicates table fields and value gets existing parameters values. If API successfully executes then it will update existing user records.
In the table, there is a 10 Id number record that has been updated.
Delete Existing User Records
To delete particular user records from the table, use the URL below.
Method | REST API URL |
---|---|
DELETE | http://localhost/CodeIgniter-4-Rest-API-CRUD/user/11 |
To erase existing user records, select the DELETE method and click the Send button.
In the table, 11 Id number records have been deleted.
Get Specific User Id Records
To get specific id number records from the table, use the URL below.
Method | REST API URL |
---|---|
GET | http://localhost/CodeIgniter-4-Rest-API-CRUD/user/9 |
To get a specific Id number record, select the GET method and click the Send button.
Learn More:
CodeIgniter 4 CRUD Operation with Ajax
Insert Update Delete In CodeIgniter 4
No comments:
Post a Comment