Clue Mediator

Create a REST API in PHP with MySQL

📅September 24, 2020
🗁PHP

In this tutorial, we will explain to you how to create a REST API in PHP with MySQL. Before we start, you might need to know about the REST API and how it works.

What is the REST API & How it works

REST stands for Representational State Transfer, REST API used for creating web services that can be accessed on different applications and created with CRUD (Create, Read, Update, Delete) operations. REST uses HTTP methods like GET, POST, PUT and DELETE to perform operations.

  • GET - To retrieve information.
  • POST - To create a new record.
  • PUT - To update existing records.
  • DELETE - To delete records.

In the REST API, we can get responses in JSON or XML format but we will use the JSON format because it is lightweight and easy to perform the parsing. Here, we will create a REST API to get customer data by passing the customer id and in the next article, we will consume it using a small example in PHP.

Steps to create a REST API in PHP with MySQL

  1. Create database table
  2. Connect database
  3. Create a file for REST API
  4. Rewrite the API URL
  5. Output

1. Create database table

We will create a customer table for a small example and for that we have created a `demo` database in MySQL. Run the following script to create a table in the database.

CREATE TABLE `customers` (
  `customer_id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `customer_name` varchar(255) NOT NULL,
  `customer_email` varchar(255) NOT NULL,
  `customer_contact` varchar(255) NOT NULL,
  `customer_address` varchar(255) NOT NULL,
  `country` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

You can insert some sample records to the table for REST API testing.

2. Connect database

Now, we have to create a `connection.php` file and add the following code to connect the database.

connection.php

<!--?php
	$dbhost = "localhost";
	$dbuser = "root";
	$dbpass = "";
	$db = "demo";
	$con = mysqli_connect($dbhost, $dbuser, $dbpass , $db) or die($con);
?-->

3. Create a file for REST API

In the next step, we will create an `api.php` file at the root level of the directory to create a REST API and add the following code in that file.

api.php

<!--?php<p-->

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;

?>

Now we can make an HTTP GET request and get the customer data by passing the customer id. You can run the following link to get the customer data.

http://localhost/demo/api.php?customer_id=1

Output:

{"status":"true","message":"Customer Details","customers":{"customer_id":"1","customer_name":"Clue Mediator","customer_email":"[email protected]","customer_contact":"9998887776","customer_address":"Address","country":"US"}}

4. Rewrite the API URL

Now, we need to rewrite the above URL using `.htaccess` file because it’s not user friendly.

.htaccess

RewriteEngine On
RewriteRule ^api/([0-9a-zA-Z_-]*)$ api.php?customer_id=$1 [NC,L]

After adding the above code in `.htaccess` file, we can retrieve the customer data by browsing the following URL and get the same output.

http://localhost/demo/api/1

Output

Run the above given URLs in the browser to check the GET API.

Output - 1 - Create a REST API in PHP with MySQL - Clue Mediator

Output - 1 - Create a REST API in PHP with MySQL - Clue Mediator

Output - 2 - Create a REST API in PHP with MySQL - Clue Mediator

Output - 2 - Create a REST API in PHP with MySQL - Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository