CodeIgniter 4 Rest Api CRUD Example

Codeigniter 4 rest api crud example; In this tutorial, i will show you how implement restful apis in codeigniter 4 app.

Before proceeding with this example tutorial, you need to know what is Rest Ful Apis and what are their uses in any app.

API is the acronym for Application Programming Interface, which is a software intermediary that allows two applications to talk to each other. Each time you use an app like Facebook, send an instant message, or check the weather on your phone, you’re using an  API. And when you want to exchange data between apps and servers. So at that time, you need to rest API for exchanging data between server and apps.

And simply and in word, you can say that An API (Application Programming Interface) is a set of functions that allows applications to access data and interact with external software components, operating systems, or microservices. To simplify, an API delivers a user response to a system and sends the system’s response back to a user.

Codeigniter 4 rest api crud example, I will make a crud restful CRUD of a product. With which you can perform CRUD (Create, read, update and delete) operations from the database. And as well as, with the help of this tutorial you will learn how to make crud apis in codeigniter 4 app and test it in postman app.

Codeigniter 4 REST API Tutorial with Example

  • Step 1 – Install Codeigniter 4 Application
  • Step 2 – Basic App Configurations
  • Step 3 – Create Database and Table
  • Step 4 – Setup Database Credentials
  • Step 5 – Create Model Class
  • Step 6 – Create Controller Class
  • Step 7 – Setup Routes
  • Step 8 – Start Development server

Step 1 – Install Codeigniter 4 Application

First of all, you need to ownload the latest version of Codeigniter 4. So, visit this link https://codeigniter.com/download Download Codeigniter 4 app and unzip the setup in your local system xampp/htdocs/ .

Note that, please change the download folder name “demo”.

Step 2 – Basic App Configurations

Now, you need to some basic configuration on the app/config/app.php file, so let’s go to application/config/config.php and open this file on text editor.

Set Base URL like this

public $baseURL = 'http://localhost:8080';
To
public $baseURL = 'http://localhost/demo/';

Step 3 – Create Database and Table

Create a database and table by executing the following SQL query:

CREATE DATABASE demo;

CREATE TABLE product(
product_id INT(11) PRIMARY KEY AUTO_INCREMENT,
product_name VARCHAR(200),
product_price DOUBLE
)ENGINE=INNODB;

INSERT INTO product(product_name,product_price) VALUES
('Product 1','2000'),
('Product 2','5000'),
('Product 3','4000'),
('Product 4','6000'),
('Product 5','7000');

Step 4 – Setup Database Credentials

To connect your codeigniter 4 app to the database. So, visit app/Config/ directory and open Database.php. Then add the databasae details like below into database.php file:

public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'test',
        'password' => '4Mu99BhzK8dr4vF1',
        'database' => 'demo',
        'DBDriver' => 'MySQLi',
        'DBPrefix' => '',
        'pConnect' => false,
        'DBDebug'  => (ENVIRONMENT !== 'development'),
        'cacheOn'  => false,
        'cacheDir' => '',
        'charset'  => 'utf8',
        'DBCollat' => 'utf8_general_ci',
        'swapPre'  => '',
        'encrypt'  => false,
        'compress' => false,
        'strictOn' => false,
        'failover' => [],
        'port'     => 3306,
	];

Step 5 – Create Model Class

Create ProductModel.php file. So, visit app/Models/ directory and create ProductModel.php.Then add the following code into it:

<?php namespace App\Models;
 
use CodeIgniter\Model;
 
class ProductModel extends Model
{
    protected $table = 'product';
    protected $primaryKey = 'product_id';
    protected $allowedFields = ['product_name','product_price'];
}

Step 6 – Create Controller Class

Create Products.php file. So, visit app/Controllers directory and create

Create Products.php file. So, visit app/Controllers directory and create FetchDataController.php.Then add the following code into it:

.php.Then add the following code into it:

<?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);
        }
         
    }
 
}

FetchController crud controller’s methods will work as follows:

  • Index() – This is used to fetch all product.
  • 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.

Step 7 – Setup Routes

To define a route, So, visit app/Config/ directory and open Routes.php file. Then add the following routes into it:

// CRUD RESTful Routes
$Route->get('/', 'home :: index');

$Route->resource('product');

Note that, the routes will be fetch and display data on view.

Step 8 – Start Development server

Execute the following command into command prompt or terminal to start the codeigniter 4 application:

php spark serve

Then visit your web browser and hit the following url on it:

http://localhost/demo/

OR

http://localhost:8080/

Next, Open the postman app to call above created APIs as follow:

1: Get all products info from DB table, you can call get all product info api in postman app as follow:

http://localhost:8080/products
codeigniter 4 api in postman app

2: And if you want to get single product info, you can use the as follow in postman app:

http://localhost:8080/products/10
codeigniter 4 get single data from db using api

3: For insert new product info into DB table, you can call create apis as follow:

http://localhost:8080/products
codeigniter 4 insert data into db using api

4: For update info into DB table using the update api, you can call update info api as follow:

codeigniter 4 update all data into db table using api

5: For delete product info using codeigniter api, you can call delete api as follow:

Conclusion

Codeigniter 4 ajax get data from database; In this tutorial, you have larned how to get data from database in codeigniter 4 using ajax and as well as how to display data.

Recommended CodeIgniter 4 Tutorial

  1. How to Install / Download Codeigniter 4 By Manual, Composer, Git
  2. How to Remove Public and Index.php From URL in Codeigniter 4
  3. Codeigniter 4 Form Validation Example Tutorial
  4. How to add jQuery Validation on Form in Codeigniter 4 Example
  5. Codeigniter 4 Ajax Form Submit Validation Example
  6. Codeigniter 4 File Upload Validation Example
  7. Image Upload with Validation in Codeigniter 4
  8. Codeigniter 4 Image Upload Preview Using jQuery Example
  9. Codeigniter 4 Ajax Image Upload Preview Example
  10. How to Upload Multiple Images in Codeigniter 4
  11. Codeigniter 4 Multiple Image Upload with Preview
  12. Codeigniter 4 Pagination Example; Create Pagination in Codeigniter
  13. Simple Codeigniter 4 CRUD with Bootstrap and MySQL Example
  14. Codeigniter 4 CRUD with Datatables Example
  15. CodeIgniter 4 Server Side DataTable Example

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *