Tutorial How to Create RESTful API in CodeIgniter 4 (Complete Guide)

Tutorial How to Create RESTful API in CodeIgniter 4 (Complete Guide)

In this tutorial you will learn how to create a simple RESTful API using CodeIgniter 4.

Not only that,

I will also share about what a RESTful API is and why we need to create a RESTful API.

(Step-by-Step)

Let get started.

 

What is RESTful API?

RESTful API is an implementation of the API (Application Programming Interface).

REST (REpresentational State Transfer) is a communication method architecture that uses the HTTP protocol for data exchange and this method is often applied in application development.

It may sound complicated but it's not.

The goal is to make a system with good performance, fast, and easy to develop, especially in data exchange and communication.

 

Why We Need to Create a RESTful API?

If you look at the traditional architecture of data communication between the client and server it looks like the following picture:

Traditinal Http request

Where the client sends a request to the server via HTTP Request, and the server provides a response via HTTP Response.

The response is given by the server, usually in HTML format.

Imagine if you have to develop your website into a Mobile application such as Android or iOS.

You know both Android and iOS applications don't need HTML as a response from the server.

Because Android and iOS use different programming languages and don't recognize HTML.

Therefore, we need to create a RESTful API.

RESTful API will be a data communication bridge between the client and server.

So, the server no longer sends HTML as a response, but only data.

Yes, only data.

This response in the form of data can be used for various platforms from applications with different programming languages.

The response from the API is usually in JSON or XML format.

However, the most commonly used is JSON.

In this tutorial, we will create a RESTful API with response data in JSON format.

Look at the following image to better understand the architecture of the RESTful API:

RESTful API Architectur

Where clients can be from various platforms, such as web applications, desktop, or mobile applications.

Cool right?

Ok, let's start building a RESTful API.

 

Step #1. Design EndPoint RESTful API

This is important!

Before creating a RESTful API, it's a good idea to define the EndPoint of the RESTful API to be created.

EndPoint is the routes from the API that we will create.

RESTful API using HTTP verbs.

Commonly used HTTP verbs are GET, POST, PUT, and DELETE.

GET to get data from the server or better known as READ, POST to CREATE new data, PUT to UPDATE data, and DELETE to delete data.

Or better known as CRUD (Create-Read-Update-Delete).

In this tutorial, I will share with you how to create a simple RESTful API to retrieve data from the server (GET), create new data to the server (POST), update data to the server (PUT), and delete data to the server (DELETE) from a table in the database, namely the “product” table.

The following is the design of the RESTful API that we will create:

endpoint

 

Step #2. Create a Database and Table

Create a new database with MySQL, you can use tools like SQLyog, PHPMyAdmin or other similar tools.

Here I created a database with the name “restful_db”.

If you create a database with the same name that's even better.

To create a database with MySQL, it can be done by executing the following query:

CREATE DATABASE restful_db;

The SQL command above will create a database with the name “restful_db”.

Next, create a table in the “restful_db” database.

Here I created a table called “product”.

If you create a table with the same name that's even better. 

To create a “product” table, you can do this by executing the following SQL command:

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

Next, insert some data in the “product” table by executing the following query:

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

The SQL command above will input 5 data into the “product” table.

 

Step #3. Installing CodeIgniter 4

Download the CodeIgniter 4 file at the following link, then extract it on your web server.

https://codeigniter.com

If you are using WAMPSERVER, extract it in the folder:

C:/wamp64/www

If you are using XAMPP, extract it in the folder:

C:/xampp/htdocs

In this tutorial, I am using XAMPP.

Then rename to "restfulapi" as shown below:

project folder

Then open a “restfulapi” project with a code editor, here I am using “Visual Studio Code”.

 

Step #4. Connect to Database

Open the "Database.php" file located in the "app/Config" folder, then find the following code:

    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => '',
        'password' => '',
        'database' => '',
        '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,
    ];

Then change it to be like the following:

    public $default = [
        'DSN'      => '',
        'hostname' => 'localhost',
        'username' => 'root',
        'password' => '',
        'database' => 'restful_db',
        '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,
    ];

Furthermore, this is important!

So that you have a good interface for handling errors, find the env file in the root of the project, then rename it to .env and open it.

Then find the following code:

# CI_ENVIRONMENT = production

Then change it to be like the following:

CI_ENVIRONMENT = development

That means you enter development mode, this mode will help you make it easier to track errors as you build your project.

 

Step #5. Create a Model File

Create a model file named "ProductModel.php" in the "app/Models" folder, then type the following code:

<?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 a Controller File

Create a controller file named "Products.php" in the "app/Controllers" folder, then type the following code:

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

    // 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->getPost('product_name'),
            'product_price' => $this->request->getPost('product_price')
        ];
        $data = json_decode(file_get_contents("php://input"));
        
        $model->insert($data);
        $response = [
            'status'   => 201,
            'error'    => null,
            'messages' => [
                'success' => 'Data Saved'
            ]
        ];
        
        return $this->respondCreated($data, 201);
    }

    // update product
    public function update($id = null)
    {
        $model = new ProductModel();
        $json = $this->request->getJSON();
        if($json){
            $data = [
                'product_name' => $json->product_name,
                'product_price' => $json->product_price
            ];
        }else{
            $input = $this->request->getRawInput();
            $data = [
                'product_name' => $input['product_name'],
                'product_price' => $input['product_price']
            ];
        }
        // Insert to Database
        $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);
        }
        
    }

}

CodeIgniter 4 has made it easy for web developers to create RESTful API.

It can be seen in the “Products.php” controller above, by just extending “ResourceController” we can create a “RESTful API”.

Not only that,

We can also easily create responses using the “API ResponseTrait”.

 

Step #7. Routes.php Configuration

The last step that is no less important is to do a little configuration in the “Routes.php” file located in the “app/Config” folder.

Open the "Routes.php" file in the "app/Config" folder, then find the following code:

$routes->get('/', 'Home::index');

Then, change to the following:

$routes->resource('products');

This configuration allows us to access the following EndPoint:

endpoint

 

Step #8. Enable CORS (Cross-Origin Resources Sharing)

This is important!

In order for resources to be accessed outside the domain, we need to enable CORS.

To enable CORS, create a file called "Cors.php" in the "app/Filters" folder.

Then type the following code:

<?php namespace App\Filters;

use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\Filters\FilterInterface;

Class Cors implements FilterInterface
{
    public function before(RequestInterface $request, $arguments = null)
    {
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method == "OPTIONS") {
        die();
        }
    }

    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
      // Do something here
    }
}

Then open the "Filters.php" file in the "app/Config" folder.

Then find the following code:

public $aliases = [
        'csrf'     => \CodeIgniter\Filters\CSRF::class,
        'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
        'honeypot' => \CodeIgniter\Filters\Honeypot::class,
    ];

Then add a "cors" filter as follows:

public $aliases = [
        'csrf'     => \CodeIgniter\Filters\CSRF::class,
        'toolbar'  => \CodeIgniter\Filters\DebugToolbar::class,
        'honeypot' => \CodeIgniter\Filters\Honeypot::class,
        'cors'     => \App\Filters\Cors::class, 
    ];

Next define "cors" in public $globals as follows:

public $globals = [
        'before' => [
            'cors'
            //'honeypot'
            // 'csrf',
        ],
        'after'  => [
            'toolbar',
            //'honeypot'
        ],
    ];

 

Step #9. Testing

To test the API that we have created, there are many tools that can be used.

In this tutorial, I use POSTMAN.

I also recommend you to use POSTMAN.

You can download POSTMAN on the official website:

https://www.getpostman.com/

Download and Install POSTMAN on your computer, then open it.

Run the project by typing the following command in Terminal/Command Prompt:

php spark serve

Like the following picture:

php spark serve

1. Get All Product (GET)

Back to POSTMAN, and type the following URL in the Postman URL field:

http://localhost:8080/products

Select the GET method, then click the Send button, then the results will appear as shown below:

get all products

In the picture above it can be seen that EndPoint for GET all product data is going well.

2. Get Single Product (GET)

Type the following URL in the URL column to get a single product:

http://localhost:8080/products/12

Select the GET method, then click the Send button, then the results will appear as shown below:

get single product

In the picture above, it can be seen that EndPoint for GET single product is going well.

Attention: You may not have a product with id = 12, please adjust it according to the data you have!

3. Create New Product (POST)

Type the following URL in the URL column to create a new product:

http://localhost:8080/products

Select the POST method => Body => form-urlencoded => Enter KEY and VALUE => click Send.

Like the following picture:

Create product

If you get a response with a status of 201 as shown above, the data is successfully stored in the database.

4. Update Product (PUT)

Type the following URL in the URL column to update the product:

http://localhost:8080/products/12

Select the PUT method => Body => form-urlencoded => Enter KEY and VALUE => click Send.

Like the following picture:

update product

If you get a 200 status response as shown above, the data has been successfully updated in the database according to the updated product id.

5. Delete Product (DELETE)

Type the following URL in the URL field to delete the product:

http://localhost:8080/products/13

Select the DELETE method, then click Send.

Like the following picture:

delete product

If you get a 200 status response as shown above, the data has been successfully deleted in the database.

 

Conclusion:

The discussion this time is about how to create a RESTful API using CodeIgniter 4.

RESTful API is an implementation of the API (Application Programming Interface).

RESTful API is a method that separates the backend and frontend which allows data exchange to various clients from different programming languages.

So what are you waiting for, let's coding!

Next Tutorial: How to Consume APIs using Vue.js and Axios.

Download Source Code

Share:



Sponsorship:


Recommended for you


Comments (0)

Leave a Comment