1.

How to create API in PHP?

Answer»

API stands for Application Programming Interface. It defines the functions and variables. Communication between the database via PHP extensions is handled by API.

Now, REST API is the web architecture that uses HTTP PROTOCOL for exchanging data between two functions that means your application or SYSTEM. Now, let us have a look at how to create REST API in PHP by considering the EXAMPLE of accessing data from a database using PHP script.

Step 1 - Create a database: To create a database run the query given below:

CREATE DATABASE phptest;

Step 2 - Create a table: After creating a database, you have to create a table with dummy data. To create a table run the query given below:

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 ;

Step 3 - Create a Database Connection: Create a db.php FILE and paste the below-given database connection in it. Make sure to update these credentials with your database credentials.

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

Step 4 - Create a REST API File: Create an api.php file and copy the following script in it.

<?phpheader("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,"Request is invalid");}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 code will accept the GET request and return output in the JSON format.

Now you can get an output as given below:

Output File

This is how you can create REST API in PHP.



Discussion

No Comment Found