REST API Search Implementation in PHP

In this tutorial, we are going to implement search using PHP REST API. I have created a RESTful web service in PHP to do the search on the database table data based on the keyword passed in the Querystring.  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 as we have seen in 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 Querystring. I used an RESTHandler class to call DAO to perform the database search. After getting the results, the API will return the response in the JSON format. 

View Demo

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. The REST handler will create response array by generating the array of mobile name 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 JSON response.

The below code shows the REST handler and the Mobile DAO files used to perform the search on the database. It calls 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 response in JSON format by 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;
	}	
}
?>

PHP REST API Output after Search

REST-API-Search-Output

View DemoDownload

Status code 404 vs 204 vs 200

When dealing with REST API, we need to 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 an another web service. Our response code should convey an appropriate meaning of the situation as the API consumer can take actions accordingly.

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

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

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

When the URL hit is received by the server, it searches the database for the value passed and does not find any data. At this situation, should we respond with 404 HTTP status? I take a stand that let me respond with HTTP status 200 and 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 not available, DB is not available, when the URL is not right, I will be sending 404 status code. I want to differentiate that, you have hit the server successfully with the right URL, but the query condition you have sent does not have any matching data and so you get the empty response.

This PHP code tutorial was published on March 30, 2017.

↑ Back to Top