Codeigniter 4 REST API Tutorial With Example
In this tutorial, we will learn how to create Codeigniter 4 rest API tutorial, you will learn how to create rest API in PHP Codeigniter 4 frameworks.
If you want to exchange data between apps and servers. So that time, you need to rest APIs for exchange data between servers and apps. we will use CodeIgniter 4 Rest API.
So this Codeigniter 4 rest API tutorial will help you to how to create rest API in Codeigniter 4 framework. And how to create, read, update, and delete data from database table using these APIs.
Before you create a rest API and use it in Codeigniter. You can see the architecture of the RESTful API:
Codeigniter 4 Rest API From Scratch
In this tutorial, we will learn how to create REST APIs from the very beginning in very easy ways.
First of all, start your local server and start PHPMyAdmin.
Then use the following command to create a database:
CREATE DATABASE demo;
After that, select your database and run the following SQL query to create a Product table into your database:
CREATE TABLE product( product_id INT(11) PRIMARY KEY AUTO_INCREMENT, product_name VARCHAR(200), product_price DOUBLE )ENGINE=INNODB;
Next, run the following query to insert some data into the product table:
INSERT INTO product(product_name,product_price) VALUES ('Product 1','2000'), ('Product 2','5000'), ('Product 3','4000'), ('Product 4','6000'), ('Product 5','7000');
In this step, we will download the latest version of Codeigniter 4, Go to this link Download Codeigniter 4 fresh new setup and unzip the setup in your local system xampp/htdocs/ . And change the download folder name “demo”.
Next, we will set some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on the text editor.
Set Base URL like this
public $baseURL = 'http://localhost:8080'; To public $baseURL = 'http://localhost/demo/';
In this step, we need to connect our project to the database. we need to go app/Config/Database.php and open database.php file in text editor. After opening the file in a text editor, We need to set up database credentials in this file like below.
public $default = [ 'DSN' => '', 'hostname' => 'localhost', 'username' => 'root', 'password' => '', 'database' => 'demo', 'DBDriver' => 'MySQLi', 'DBPrefix' => '', 'pConnect' => false, 'DBDebug' => (ENVIRONMENT !== 'production'), 'cacheOn' => false, 'cacheDir' => '', 'charset' => 'utf8', 'DBCollat' => 'utf8_general_ci', 'swapPre' => '', 'encrypt' => false, 'compress' => false, 'strictOn' => false, 'failover' => [], 'port' => 3306, ];
So go to app/Models/ and create here one model. And you need to create one model name ProductModel.php and update the following code into your ProductModel.php file:
<?php namespace App\Models; use CodeIgniter\Model; class ProductModel extends Model { protected $table = 'product'; protected $primaryKey = 'product_id'; protected $allowedFields = ['product_name','product_price']; }
Now, Navigate app/Controllers and create a controller name Products.php. Then update the following method into Products.php controller file:
<?php namespace App\Controllers; use CodeIgniter\RESTful\ResourceController; use CodeIgniter\API\ResponseTrait; use App\Models\ProductModel; class Products extends ResourceController { use ResponseTrait; // get all product public function index() { $model = new ProductModel(); $data = $model->findAll(); return $this->respond($data); } // get single product public function show($id = null) { $model = new ProductModel(); $data = $model->getWhere(['product_id' => $id])->getResult(); if($data){ return $this->respond($data); }else{ return $this->failNotFound('No Data Found with id '.$id); } } // create a product public function create() { $model = new ProductModel(); $data = [ 'product_name' => $this->request->getVar('product_name'), 'product_price' => $this->request->getVar('product_price') ]; $model->insert($data); $response = [ 'status' => 201, 'error' => null, 'messages' => [ 'success' => 'Data Saved' ] ]; return $this->respondCreated($response); } // update product public function update($id = null) { $model = new ProductModel(); $input = $this->request->getRawInput(); $data = [ 'product_name' => $input['product_name'], 'product_price' => $input['product_price'] ]; $model->update($id, $data); $response = [ 'status' => 200, 'error' => null, 'messages' => [ 'success' => 'Data Updated' ] ]; return $this->respond($response); } // delete product public function delete($id = null) { $model = new ProductModel(); $data = $model->find($id); if($data){ $model->delete($id); $response = [ 'status' => 200, 'error' => null, 'messages' => [ 'success' => 'Data Deleted' ] ]; return $this->respondDeleted($response); }else{ return $this->failNotFound('No Data Found with id '.$id); } } }
In the above controller method works as follow:
->Index() – This is used to fetch all products.
->create() – This method is used to insert product info into DB table.
->update() – This is used to validate the form data server-side and update it into the MySQL database.
->show() – This method is used to fetch single product info into DB table.
->delete() – This method is used to delete data from the MySQL database.
Now Navigate to App/Configuration folder. And Open the file “Routes.php”, then find the following code:
$Route->get('/', 'home :: index');
Then, change the following:
$Route->resource('product');
This configuration allows us to access the following EndPoint:
Open your terminal and run the following command to start the development server:
php spark serve
I hope it can help you...
is there any method for image crud api?