CodeIgniter 4 Consume External REST APIs

CodeIgniter 4 REST API Client

In this tutorial I will show you how to call or consume external REST APIs in CodeIgniter 4 framework. REST is an acronym that stands for Representational State Transfer. I had shown how to build REST API CRUD Example earlier but here I am going to show an example on CodeIgniter 4 consume REST APIs.

I am not going to consume the REST APIs which I built using CodeIgniter, but I am going to consume REST APIs which are already available online for testing purpose.

I will use CURL to call the REST URL resources (REST APIs). CURL is a command line tool for transferring data using various network protocols.

call external rest apis in codeigniter 4

Prerequisites

CodeIgniter 4.3.3, CURL, PHP 7.4.23

Project Directory

It’s assumed that you have setup PHP and CodeIgniter in your system.

Now I will create a project root directory called codeigniter-consume-rest-api.

Now move all the directories and files from CodeIgniter framework into the project root directory.

I may not mention the project root directory in subsequent sections, and I will assume that I am talking with respect to the project root directory.

CURL Helper

I will create a helper function for CURL operations on various HTTP methods – GET, POST, PUT, etc. – for calling REST APIs.

The following code is written into a file app/Helpers/Curl_Helper.php. The helper file is created with the naming convention as <file_name>_Helper.php.

<?php

function perform_http_request($method, $url, $data = false) {
    $curl = curl_init();

    switch ($method) {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
			}
			
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
			
            break;
        default:
            if ($data) {
                $url = sprintf("%s?%s", $url, http_build_query($data));
			}
    }

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); //If SSL Certificate Not Available, for example, I am calling from http://localhost URL

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

In the above helper function I have used switch case to segregate operations according to the HTTP methods.

I have set SSL verification to false for https protocol because I am not using any valid certificate at client side and more over I am calling from my localhost over non-secured http protocol. If you are calling http-based REST API URLs then you don’t need to set this option on your localhost.

Controller Class

Here is the controller class that will call external REST APIs for performing operations and fetching data from the server.

The following code is written into a file app/Controllers/Home.php.

<?php

namespace App\Controllers;

class Home extends BaseController {
	
    public function index() {
		helper(['curl']);
		
		$rest_api_base_url = 'https://reqres.in';
		
		//GET - list of users
		$get_endpoint = '/api/users';
		
		$response = perform_http_request('GET', $rest_api_base_url . $get_endpoint);
		
		$data['users'] = $response;
		
		//GET - single user
		$get_endpoint = '/api/users/2';
		
		$response = perform_http_request('GET', $rest_api_base_url . $get_endpoint);
		
		$data['user'] = $response;
		
		//POST - create new user
		$post_endpoint = '/api/users';
		
		$request_data = json_encode(array("name" => "Soumitra", "job" => "Blog Author", "avatar" => "https://roytuts.com/about/"));
		
		$response = perform_http_request('POST', $rest_api_base_url . $post_endpoint, $request_data);
		
		$data['new_user'] = $response;
		
		//PUT - update user
		$put_endpoint = '/api/users';
		
		$request_data = json_encode(array("name" => "Soumitra", "job" => "Roy Tutorials Author", "avatar" => "https://roytuts.com/about/"));
		
		$response = perform_http_request('PUT', $rest_api_base_url . $put_endpoint, $request_data);
		
		$data['update_user'] = $response;
		
		//View
        return view('consume_rest_api', $data);
    }
	
}

I have loaded the required helper file using helper() function.

In the above controller function (index()), I have shown examples on GET, POST and PUT methods.

The base URL for all REST endpoints is same only individual endpoint for each operation is different.

I have fetched list of users as well as single user using HTTP GET method from the external REST API.

For POST and PUT methods, I have sent the data in JSON format using jsong_encode(). The POST method has been used for creating a new user and PUT method has been used for updating the existing user.

Using CodeIgniter 4’s cURL Service

If you want to use CodeIgniter 4’s cURL service then you don’t need to create the above helper file and you can directly use the cURL service methods to invoke the external REST APIs.

I have disabled (not recommended) SSL certificate verification from localhost in the cURL call otherwise you will see the following error while calling SSL based REST APIs:

SSL certificate problem: unable to get local issuer certificate

The above index() function can be written as follows in the controller class:

//CodeIgniter 4 cURL
public function index() {
	$rest_api_base_url = 'https://reqres.in';
	
	// Instance
	$curl = \Config\Services::curlrequest(['baseURI' => $rest_api_base_url]);		
	
	//GET - list of users
	$get_endpoint = '/api/users';
	
	$response = $curl->get($get_endpoint, ['verify' => false]); //disable SSL: verify => false 
	
	$data['users'] = $response->getBody();
	
	//GET - single user
	$get_endpoint = '/api/users/2';
	
	$response = $curl->get($get_endpoint, ['verify' => false]); //disable SSL: verify => false 
	
	$data['user'] = $response->getBody();
	
	//POST - create new user
	$post_endpoint = '/api/users';
	
	$request_data = json_encode(array("name" => "Soumitra", "job" => "Blog Author", "avatar" => "https://roytuts.com/about/"));
	
	$response = $curl->post($post_endpoint, ['json' => ["name" => "Soumitra", "job" => "Blog Author", "avatar" => "https://roytuts.com/about/"], 'verify' => false]); //disable SSL: verify => false 
	
	$data['new_user'] = $response->getBody();
	
	//PUT - update user
	$put_endpoint = '/api/users/707';
	
	$request_data = json_encode(array("name" => "Soumitra", "job" => "Roy Tutorials Author", "avatar" => "https://roytuts.com/about/"));
	
	$response = $curl->put($put_endpoint, ['json' => ["name" => "Soumitra", "job" => "Roy Tutorials Author", "avatar" => "https://roytuts.com/about/"], 'verify' => false]); //disable SSL: verify => false 
	
	$data['update_user'] = $response->getBody();
	
	//View
	return view('consume_rest_api', $data);
}

View

The view file is responsible for displaying data to the end users. Here I am not parsing the JSON data which are coming as responses from the REST APIs and I am displaying in the same format to the end users.

The following piece of code is written into the file app/Views/consume_rest_api.php.

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Consume REST API in CodeIgniter 4</title>
	<meta name="description" content="The small framework with powerful features">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<link rel="shortcut icon" type="image/png" href="/favicon.ico"/>

</head>
<body>
	<h1>Consume REST API in CodeIgniter 4</h1>
	
	<h3>GET - List Of Users</h3>
	<?php
		echo $users;
	?>
	
	<h3>GET - Single User</h3>
	<?php
		echo $user;
	?>
	
	<h3>POST - Create New User</h3>
	<?php
		echo $new_user;
	?>
	
	<h3>PUT - Update User</h3>
	<?php
		echo $update_user;
	?>
</body>
</html>

Deploying the Application

I am not going to use any external server but CLI command to run the application. Make sure you start the MySQL database server before you start your application. If you want to use external server to run your application, you can use, for example, Apache HTTP Server. Execute the following command on your project root directory to run your application.

php spark serve

Your application will be running on localhost and port 8080.

Testing – Call External REST APIs

Browse the URL http://localhost:8080 in the browser and you will see the following output in the browser:

codeigniter 4 call rest apis

Hope you got an idea how to call external REST API in CodeIgniter 4.

Source Code

Download

Leave a Reply

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