PHP Web Services: How to Create a Simple Web Service Using PHP

A quick tutorial to explain what a Web Service is and how it can be used. Let see with step by step

What is Web Service ?

The main question arise before starting implementation of web services is what does mean by Web Service and What is the Web Service.Simply we can understand this Web Service by some definitions.

  • Web service is a client server application or application component for communication between client and server.
  • Web service is a software system for inter operable machine to machine communication..
  • Web service provide a common platform that allows to communicate between multiple applications with each other, which built on various programming languages.

Types of Web Services:

There are two types of web services.

1.) SOAP web services.

2.) RESTful web services.

SOAP Web Service:

SOAP stands for Simple Object Access Protocol. It is a XML-based protocol for accessing Web Services.

SOAP is XML based protocol known as platform independent and language independent. By using SOAP, you will be able to interact with other programming language applications.

RESTful Web Service(Also Known as REST API):

RESTful web service is based on representational state transfer (REST) technology. It is an architectural style and an approach for communication used in the development of Web Services.

Some Benefits of REST APIs:

  • REST APIs are fast.
  • No strict specification like SOAP.
  • Consumes less bandwidth and resource.
  • Language and Platform independent.
  • Can be written in any programming language.
  • Executed in any platform.
  • RESTful web services can use SOAP web services.
  • Permits different data format like Plain Text, HTML, XML and JSON.

Creating a Simple REST API:

I am going to create a simple REST API. In this API trying to get employee data based on search by employee id.To read this API i will use CURL method.

Create a form named Employees.php where an input box will get employee id from user.Please find below the code.

<!DOCTYPE html>
<html>
    <head>
        <title>Simple REST API</title>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    </head>
    <body>
    <center>
    <?php
    if(!empty($result)){
        echo "<table>";
        echo "<tr><td>Employee ID:</td><td>$result->employeeid</td></tr>";
        echo "<tr><td>NAme:</td><td>$result->employeeName</td></tr>";
        echo "<tr><td>Age:</td><td>$result->employeeAge</td></tr>";
        echo "<tr><td>Salary:</td><td>$result->employeeSalary</td></tr>";
        echo "<tr><td>Response Code:</td><td>$result->responseCode</td></tr>";
        echo "</table>";
    }
    ?>
        <div class="container">
            <form action="" method="POST">
            <label>Enter Employee ID:</label><br />
            <input type="number" name="employee_id" placeholder="Enter Employee ID" required/>
            <br /><br />
            <button type="submit" name="submit">Submit</button>
            </form>
        </div>
    </center>
    </body>
</html>
In the same page we will put PHP script which will execute after form submitting.
<?php
if (isset($_POST['employee_id']) && $_POST['employee_id']!="") {
$employee_id = $_POST['employee_id'];
$url = "http://localhost/rest_api_example/api/".$employee_id;
$client = curl_init();
curl_setopt_array($client, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => 0,
CURLOPT_SSL_VERIFYPEER => 0
));
    $response = curl_exec($client);
$result = json_decode($response);
}
?>
Above script handling of API Call. Simply passing employee id through API and we will get the response.
Now, We will create the API named API.php where the write code to return employee data against employee id with response code.Please find below the API code.
<?php
header("Content-Type:application/json");
if (isset($_GET['employeeid']) && $_GET['employeeid']!="") {
include('./connection.php');
$db = new dbObj();
$con = $db->getConnstring();
$employeeid = $_GET['employeeid'];
$result = mysqli_query($con,
"SELECT * FROM `employee` WHERE id = $employeeid");
if(mysqli_num_rows($result)>0){
$row = mysqli_fetch_array($result);
$employeeName = $row['employee_name'];
$employeeAge = $row['employee_age'];
$employeeSalary = $row['employee_salary'];
$responseCode = 200;
response($employeeid, $employeeName, $employeeAge,$employeeSalary,$responseCode);
mysqli_close($con);
}else{
response(NULL, NULL, NULL,"No Record Found",200);
}
}else{
response(NULL, NULL, NULL,"Invalid Request",400);
}

function response($employeeid,$employeeName,$employeeAge,$employeeSalary,$responseCode){
$response = array(
      'employeeid' => $employeeid,
    'employeeName' => $employeeName,
    'employeeAge'=> $employeeAge,
    'employeeSalary' => $employeeSalary,
    'responseCode'=> $responseCode
    );
$json_response = json_encode($response);
echo $json_response;
}
?>

Clean URL through htaccess:

Clean URL also known as RESTful URL are user-friendly and do not contain a query string. Rather than they contain only the path of the resource.Please find below the code of htaccess.

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

Note: When you are testing this API example make sure CURL is enabled on your web server or on your localhost.

That’s all.Head to your browser and run this example.

Final Words:

This example simply getting employee data through an API, which can be used through calling that API and we will get all employee data as per required format like JSON, XML or Plain Text.
Thank you for reading this post. we hope you like this Post, Please feel free to comment below, your suggestion. if you face any issue with this code let us know. We’d love to help. Stay tuned !

Author: Hitesh

I am Hitesh from Jamshedpur (India). I have been working as a Web Application Developer from last 4+ years. I love diverse and attention catching web presence for a variety of users. Also I love to learn new things in Web Development.