Create and Consume Simple REST API in PHP

What is REST?

In this blog, we will Generate and consume simple REST API in PHP. REST enables you to access and work on web-based services. So, before proceeding further, let me explain what REST is and how it works.

What is REST?

REST stands for Representational State Transfer, and REST is an architectural style that describes a set of constraints imposed for developing and consuming web services through the standard protocol (HTTP). It is easy to implement, simple, and stateless web service. Another web service is also available, SOAP, which is for the Simple Object Access Protocol, created by Microsoft.

This is more widely used in web and mobile applications than SOAP. REST can provide output data in multiple formats such as Extensible Markup Language (XML), JavaScript Object Notation (JSON), Command Separated Value (CSV), and many others while SOAP described output in Web Services Description Language (WSDL).

How Does REST API Work

REST requests are related to (Create, Read, Update, Delete) CRUD operations in the database, REST uses GET, POST, PUT, and DELETE applications. 

Let me differentiate them into CRUD.

POST is used to create a new record that is similar to Create

GET is used to retrieve information that is similar to Read

PUT is used to update a file which is identical to Update

DELETE is used to delete the record that is identical to Delete

How to Create and Consume Simple REST API in PHP

The JSON format is the most common output format of the REST API. 

We will use the JSON format to consume our simple REST API.

Now, We will develop an online transaction payment REST API for our example. We will use the GET request to retrieve information.

1. Make REST API in PHP

2. Consume REST API in PHP

1. Create REST API in PHP

Follow these steps to create a REST API, 

1. Make a Database and Table with Dummy Data

2. Create a Database Connection

3. Make a REST API File

1. Create a Database and Table with Dummy Data

To create a database, run the following query.

CREATE DATABASE allsweb;


Note:
We have already attached the SQL file of this table with dummy data, download the complete zip file of this tutorial.

To make a table, run the following query. 

CREATE TABLE IF NOT EXISTS `transactions` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`order_id` int(50) NOT NULL,
`amount` decimal(9,2) NOT NULL,
`response_code` int(10) NOT NULL,
`response_desc` varchar(50) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `order_id` (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;

2. Create a Database Connection

Just create a db.php file and paste the following database connection in it. Make sure that you update these credentials with your database credentials.

// Enter your Host, username, password, database below.
$con = mysqli_connect("localhost","root","","allphptricks");
    if (mysqli_connect_errno()){
 echo "Failed to connect to MySQL: " . mysqli_connect_error();
 die();
 }

 3. Create a REST API File

Create an api.php file and paste the following script in it.

<?php
header("Content-Type:application/json");
if (isset($_GET['order_id']) && $_GET['order_id']!="") {
 include('db.php');
 $order_id = $_GET['order_id'];
 $result = mysqli_query(
 $con,
 "SELECT * FROM `transactions` WHERE order_id=$order_id");
 if(mysqli_num_rows($result)>0){
 $row = mysqli_fetch_array($result);
 $amount = $row['amount'];
 $response_code = $row['response_code'];
 $response_desc = $row['response_desc'];
 response($order_id, $amount, $response_code,$response_desc);
 mysqli_close($con);
 }else{
 response(NULL, NULL, 200,"No Record Found");
 }
}else{
 response(NULL, NULL, 400,"Invalid Request");
 }
 
function response($order_id,$amount,$response_code,$response_desc){
 $response['order_id'] = $order_id;
 $response['amount'] = $amount;
 $response['response_code'] = $response_code;
 $response['response_desc'] = $response_desc;
 
 $json_response = json_encode($response);
 echo $json_response;
}
?>

The above tutorial will accept the GET request and return output in the JSON format.

We have created all these files in folder name rest, and now you can get the transaction information by browsing the following URL.

http://localhost/rest/api.php?order_id=15478959

So you will get the following output.

The above URL is not user-friendly, therefore we will rewrite URL through the .htaccess file, copy-paste the following rule in .htaccess file.

RewriteEngine On    # Turn on the rewriting engine
 
RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?order_id=$1 [NC,L]

Now you can get the transaction information by browsing the following URL.

http://localhost/rest/api/15478959

Hence, you will get the following output.

2. Consume REST API in PHP

To consume a REST API, follow these steps:

1. Create an Index File with HTML Form

2. Fetch Records through CURL

1. Create an Index File with HTML Form

<form action="" method="POST">
<label>Enter Order ID:</label><br />
<input type="text" name="order_id" placeholder="Enter Order ID" required/>
<br /><br />
<button type="submit" name="submit">Submit</button>
</form>


2. Fetch Records through CURL

if (isset($_POST['order_id']) && $_POST['order_id']!="") {
 $order_id = $_POST['order_id'];
 $url = "http://localhost/rest/api/".$order_id;
 
 $client = curl_init($url);
 curl_setopt($client,CURLOPT_RETURNTRANSFER,true);
 $response = curl_exec($client);
 
 $result = json_decode($response);
 
 echo "<table>";
 echo "<tr><td>Order ID:</td><td>$result->order_id</td></tr>";
 echo "<tr><td>Amount:</td><td>$result->amount</td></tr>";
 echo "<tr><td>Response Code:</td><td>$result->response_code</td></tr>";
 echo "<tr><td>Response Desc:</td><td>$result->response_desc</td></tr>";
 echo "</table>";
}
    ?>

Now you can do anything with these output data; you can insert or update it into your database if you are using the REST API of any other service provider. Usually, in the case of online transactions, the service provider provides a status of payment via API. So, you can check either payment is made successfully or not. They also offer a complete guide to it.
Therefore, make sure CURL is enabled on your web server or your localhost when you are testing demo.
I try my best to explain this tutorial as simple as possible.
If you found this tutorial helpful, share it with your friends and developers group.

Also, read our previous blog- Simple Shopping Cart using MySQL and PHP

Exit mobile version