How to create REST API in PHP

API aka “application program interface“. It is not challenging as it sounds, creating a REST API in PHP is very straightforward if you know a basic PHP and MySQL. In this article, I will show how you can create a simple login API. Let’s start then how to create REST API in PHP. I have created a repository on Github of this project. At the end of the article, I will add the GitHub link.

Before we hit the code part lets see what are prequisites , so you need apache server and mysql server or XAMPP which have both. So I am assuming you have installed XAMPP on your machine if not you can follow my these articles to install – Windows , Ubuntu , MacOS.

Lets cut to the chase and start the code. So first of all lets setup database. Create a database with the name ‘CodeKilla‘. Next, add the following query to create a Table with columns in the CodeKilla database.

CREATE TABLE users (
    id int NOT NULL AUTO_INCREMENT,
    username varchar(255) NOT NULL,
    password varchar(255) NOT NULL,
    PRIMARY KEY (id)
);

Now add few rows in users table.

INSERT INTO users (username,password) VALUES ('abc','123456');
INSERT INTO users (username,password) VALUES ('xyz','123456789');

Now the coding part begins, create a folder inside htdocs and these files with the following code.

dbConfig.php

This is the file in which we will keep our database credential and connect with the database. I am going to use object-oriented mysqli throughout this article.

 $servername = "localhost";
 $username = "username";
 $password = "password";
 $dbname = "codekilla";

 $conn = new mysqli($servername, $username, $password , $dbname);

  if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

Start your XAMPP server and verify that your connection with the database is established or not. In your browser open “http://localhost/yourFolderName/dbconfig.php”, if you don’t see any error that means you are now connected with the database.

login.php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");

include 'dbConfig.php';
$data = json_decode(file_get_contents("php://input"));
// $data will recieve data we sent from postman as an array
$sql = "SELECT * FROM users WHERE username='$data->username' AND password='$data->password'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    echo json_encode($row);
} else {
    echo json_encode(array('status' => 'failed', 'msg' => 'Username or password is incorrect'));
}
return;

Lets me explain here what is happening in the code. Well, it’s pretty straightforward we are making calls to select queries with where condition. The first line header() is important because of CORS problems and the second line header() explains the incoming data’s content type. Moving next "include 'dbConfig.php' " is understandable that we are including our database connection file in this file.

Now we are firing Select query and with the result of the select query, we are checking how many rows it returned. If the returned row is greater than 0 we are fetching data using fetch_assoc() and then return it by encoding with json_encode(). json_encode() converts PHP array into JSON format.

To test our REST API we need the POSTMAN or any similar tool. I am going to use the POSTMAN. You can see in below picture I am making POST request call to URL "http://localhost/APICodekilla/login.php"

with right credential
with wrong credential

See, that was a pretty easy article ” How to create REST API in PHP “. I hope this article helped you create your first REST API using PHP. If something still bothers you feel free to leave the comment in below comment box.

Now you have read and followed the article, if something still bugging you can get this code here at Github. Clone the repository and explore it.

Leave a Reply

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