Consume a REST API in PHP
Today we’ll show you how to consume a REST API in PHP. In the previous article, we have explained about how to create a REST API in PHP.
Here we will try to consume the previously created REST API with a small example in PHP.
Steps to consume a REST API in PHP
- Create a REST API
- Create a HTML form
- Include jQuery and Bootstrap library
- Use AJAX method to pass data
- Make API call and retrieve data using PHP cURL
- Output
1. Create a REST API
First, create a REST API before starting an example. Refer to the following article to create a REST API with MySQL.
Create a REST API in PHP with MySQL
2. Create a HTML form
Let’s create an HTML form where we will add the dropdown list and bind the customer list from the database to that dropdown. By selecting the customer from the dropdown to make an API call and get more details.
customer.php
<?php
include('connection.php');
$query = "SELECT * FROM `customers`";
$result = mysqli_query($con, $query);
$customerData = mysqli_fetch_all($result, MYSQLI_ASSOC);
?>
<html>
<head>
<title>Retrieve customer data from database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row m-5">
<div class="col-md-4">
<form action="" method="POST">
<h5>Consume a REST API in PHP - <a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></h5>
<select name="customer_id" class="form-control mt-3" id="customer_id">
<option value="0">Select Customer</option>
<?php foreach($customerData as $customer) { ?>
<option value="<?php echo $customer['customer_id']?>"><?php echo $customer['customer_name']?></option>
<?php } ?>
</select>
<button type="submit" class="btn btn-primary mt-3" id="datasubmit">Submit</button>
</form>
<div id="result" class="mt-4">
</div>
</div>
</div>
</body>
</html>
3. Include jQuery and Bootstrap library
If you noticed that we have already included the jQuery and Bootstrap library in the HTML page. The jQuery will be used to work with Ajax call and the bootstrap library is added to the form for styling.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
4. Use AJAX method to pass data
Here, we will call an Ajax method to pass the selected customer id from the dropdown. Add the following code to the `customer.php` file.
<script>
$(document).ready(function () {
$("#datasubmit").on("click", function (e) {
e.preventDefault();
var customer_id = $("#customer_id").val();
$.ajax({
url: "getData.php",
type: "POST",
data: { customer_id: customer_id },
success: function (data) {
$("#result").html(data);
}
});
});
})
</script>
5. Make API call and retrieve data using PHP cURL
Now, we will create a `getData.php` file to get the customer records based on the customer id and return the customer details.
getData.php
<?php
include('connection.php');
if (isset($_POST['customer_id']) && $_POST['customer_id']!="") {
$customer_id = $_POST['customer_id'];
// path of the REST API URL
$url = "http://localhost/demo/api/".$customer_id;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
if(!$result) {
echo "No data found";
exit;
}
echo "<h3>Customer Details</h3>";
echo "<b>Name: </b>". $result->customers->customer_name."<br>";
echo "<b>Email: </b>". $result->customers->customer_email."<br>";
echo "<b>Contact: </b>". $result->customers->customer_contact."<br>";
echo "<b>Address: </b>". $result->customers->customer_address."<br>";
echo "<b>Country: </b>". $result->customers->country."<br>";
exit;
}
?>
6. Output
After combining the all code together, your project structure should look like below.
Project Structure - Consume a REST API in PHP - Clue Mediator
.htaccess
RewriteEngine On
RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?customer_id=$1 [NC,L]
api.php
<?php
header("Content-Type:application/json");
include('connection.php');
if (isset($_GET['customer_id']) && $_GET['customer_id']!="") {
$customer_id = $_GET['customer_id'];
$query = "SELECT * FROM `customers` WHERE customer_id=$customer_id";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);
$customerData['customer_id'] = $row['customer_id'];
$customerData['customer_name'] = $row['customer_name'];
$customerData['customer_email'] = $row['customer_email'];
$customerData['customer_contact'] = $row['customer_contact'];
$customerData['customer_address'] = $row['customer_address'];
$customerData['country'] = $row['country'];
$response["status"] = "true";
$response["message"] = "Customer Details";
$response["customers"] = $customerData;
} else{
$response["status"] = "false";
$response["message"] = "No customer(s) found!";
}
echo json_encode($response); exit;
?>
connection.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "demo";
$con = mysqli_connect($dbhost, $dbuser, $dbpass , $db) or die($con);
?>
customer.php
<?php
include('connection.php');
$query = "SELECT * FROM `customers`";
$result = mysqli_query($con, $query);
$customerData = mysqli_fetch_all($result, MYSQLI_ASSOC);
?>
<html>
<head>
<title>Retrieve customer data from database</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="row m-5">
<div class="col-md-4">
<form action="" method="POST">
<h5>Consume a REST API in PHP - <a href="https://www.cluemediator.com" target="_blank">Clue Mediator</a></h5>
<select name="customer_id" class="form-control mt-3" id="customer_id">
<option value="0">Select Customer</option>
<?php foreach($customerData as $customer) { ?>
<option value="<?php echo $customer['customer_id']?>"><?php echo $customer['customer_name']?></option>
<?php } ?>
</select>
<button type="submit" class="btn btn-primary mt-3" id="datasubmit">Submit</button>
</form>
<div id="result" class="mt-4">
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function () {
$("#datasubmit").on("click", function (e) {
e.preventDefault();
var customer_id = $("#customer_id").val();
$.ajax({
url: "getData.php",
type: "POST",
data: { customer_id: customer_id },
success: function (data) {
$("#result").html(data);
}
});
});
})
</script>
getData.php
<?php
include('connection.php');
if (isset($_POST['customer_id']) && $_POST['customer_id']!="") {
$customer_id = $_POST['customer_id'];
// path of the REST API URL
$url = "http://localhost/demo/api/".$customer_id;
$client = curl_init($url);
curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
$response = curl_exec($client);
$result = json_decode($response);
if(!$result) {
echo "No data found";
exit;
}
echo "<h3>Customer Details</h3>";
echo "<b>Name: </b>". $result->customers->customer_name."<br>";
echo "<b>Email: </b>". $result->customers->customer_email."<br>";
echo "<b>Contact: </b>". $result->customers->customer_contact."<br>";
echo "<b>Address: </b>". $result->customers->customer_address."<br>";
echo "<b>Country: </b>". $result->customers->country."<br>";
exit;
}
?>
Run the `customer.php` file in the browser to check the output.
Output - Consume a REST API in PHP - Clue Mediator
That’s it for today.
Thank you for reading. Happy Coding..!!