REST API Search Implementation in PHP

by Vincy. Last modified on July 6th, 2023.

In this tutorial, we will implement search using PHP REST API. I have created a RESTful web service in PHP to search the database table data based on the keyword passed in the query string. In a previous tutorial, we have seen how to create a RESTful web service in PHP.

In this example, I have used the same mobile database we saw in the previous REST example interacting with MySQL. In this database table, I search for the list of mobile names containing the keyword sent in the URL query string. I used a RESTHandler class to call DAO to perform the database search.

View Demo

After getting the results, the API will return the response in JSON format. The JSON resultant data can be read, parsed, and handled in the end-user application from where the API is invoked.

RESTful Web Service to Search MySQL Data

This code shows a service class handling REST calls. It calls Mobile DAO to execute the search query by using the search keyword passed as GET data. The DAO will return the array of results to the REST handler.

REST-API-Search-Output

The REST handler will create a response array by generating mobile names based on the search keyword. The response array will be encoded in the format of the requested content type. In this example, I am sending a JSON response.

The below code shows the REST handler and the Mobile DAO files used to perform the search on the database. It calls the searchMobile() function to generate the search query by using the search keyword. After executing the query, it will return the filtered database row data to the REST handler to create a JSON response using json_encode().

<?php
require_once("SimpleRest.php");
require_once("Mobile.php");
		
class MobileRestHandler extends SimpleRest {

	function searchMobile() {	

		$mobile = new Mobile();
		$rawData = $mobile->searchMobile();

		if(empty($rawData)) {
			$statusCode = 404;
			$rawData = array('error' => 'No mobiles found!');		
		} else {
			$statusCode = 200;
		}

		$requestContentType = 'application/json';
		$this ->setHttpHeaders($requestContentType, $statusCode);
		
		$result["output"] = $rawData;
				
		if(strpos($requestContentType,'application/json') !== false){
			$response = $this->encodeJson($result);
			echo $response;
		}
	}
	
	public function encodeJson($responseData) {
		$jsonResponse = json_encode($responseData);
		return $jsonResponse;		
	}
}
?>
<?php
require_once("dbcontroller.php");
/* 
A domain Class to demonstrate RESTful web services
*/
Class Mobile {
	private $mobiles = array();
	/*
		you should hookup the DAO here
	*/
	public function searchMobile(){
		if(isset($_GET['name'])){
			$name = $_GET['name'];
			$query = "SELECT * FROM tbl_mobile WHERE name LIKE '%" .$name. "%'";
		} else {
			$query = "SELECT * FROM tbl_mobile";
		}
		$dbcontroller = new DBController();
		$this->mobiles = $dbcontroller->executeSelectQuery($query);
		return $this->mobiles;
	}	
}
?>

View DemoDownload

Status code 404 vs. 204 vs 200

When dealing with REST API, we must be critical of the status code passed as the response. Since we never know what kind of application will consume our API. It might be an Android mobile application or even another web service. Our response code should convey an appropriate meaning of the situation, as the API consumer can take action accordingly.

In this example, there is a question of what status code should be sent back when no data is found for the query.

I am using the REST URL format as ‘/restapi/mobile/list?name=value’

This URL conforms to the REST standard, do not whine about the query string in the URL. This is acceptable according to REST standards.

When the server receives the URL hit, it searches the database for the value passed and does not find any data. In this situation, should we respond with 404 HTTP status? I take a stand that lets me respond with HTTP status 200 and an empty (null) response. The REST resource is found, but the data requested is not available.

The rationale behind this decision is to differentiate that when the server is unavailable, DB is unavailable; when the URL is incorrect, I will send a 404 status code. I want to differentiate that you have hit the server successfully with the correct URL, but the query condition you have sent does not have any matching data, so you get an empty response.

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

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

↑ Back to Top

Share this page