REST web service is best suitable for Web. Representational State Transfer (REST) is an architectural style that specifies constraints, such as the uniform interface, that if applied to a web service induce desirable properties, such as performance, scalability, and modifiability. In the REST architectural style, data and functionality are considered resources and are accessed using URIs, typically links on the Web.

Why we ever need REST web services? Most modern applications integrate data from sources other than user forms. One standard approach to integrating data from outside sources is to use a RESTful endpoint to accept JSON data. Custom approach for developing REST web services works well if you want to integrate existing custom applications (or CMS such as Drupal or WordPress) and some third party application. This post will document how to program your own REST API to accept JSON via POST.

File Structure

├── Controllers
│   ├── dbconnect.php
│   ├── api
│   │   ├── Contact.php (user defined controllers)
│   │   └── MyController.php
├── index.php
└── Rest.php

Define URI

First step to develop REST API server requires defining URI format. For simplicity, I leave it to default GET and POST method implementation. All the rules are defined in Rest.php. A URL request first comes to index.php and it then forwards that request for further handling and authentication to Rest.php. Following the format of the default URI for calling the REST APIs.


Its better to accept arguments in your URI in order to provide a more dynamic API that can serve all your POST needs. Our function will be responsible for validating the request, accepting a PHP input stream, returning status codes, decoding the JSON and processing the data into database before returning a response code of success.


For minimum validation consider validating the request as a POST, authenticating a specific user, or key and performing data validation for data type and data structure (field and object validation).

When authenticating a user, or key, one option is to pass the information via the header userpwd.

Curl request with userpwd:

curl --user username:password -X POST -d @file.txt --header "Content-Type: application/json"

In order to check for the username and password from the example above use PHP’s $_SERVER[‘PHP_AUTH_USER’] and $_SERVER[‘PHP_AUTH_PWD’]. If you are only validating on a key you can pass the key as the username and validate the username in your application.

In this case, we are passing the authentication username and apikey as arguments. That will be validated with database in checkAuth() function in Rest.php.

public function checkAuth() {
 $users=mysql_query("select * from users where name='$name'");

 while($row = mysql_fetch_array($users))
    return true;
    return false;
In this function above, we have taken two authentication arguments from API caller i.e. name (username) and apikey. These two values can the authenticated with database or any config file to check that the requested user is authorized to call these APIs.

Processing the JSON

Once the authentication is successful, the request moves to the called method. PHP provides a method to obtain stream inputs by using file_get_contents and requesting “php://input”. File_get_contents streams the input and processes it into a string. Once the input is returned as a string use PHPs json_decode to return the string as an associative array.

 $received_json = file_get_contents("php://input",  TRUE);
 $json = drupal_json_decode($received_json, TRUE);

Note: Consider detecting if json_decode returns null or false.

Once validation has passed and your JSON is available, iterate and save the object to Drupal.

class contact{
  public function post(){
    $json = file_get_contents('php://input');
    $obj = json_decode($json,true);
    $name= $obj["first_name"];
    $result=mysql_query("select * from users");
    $result = mysql_fetch_array($result);
    return $result;

After completing the payload a notice of success to inform the application it’s POST was a success.

Calling the REST API Function

Finally, your REST API server is ready to be called. Calling an API function requires the function name and an array of correctly formatted values and keys so that JSON can decode it at the receiving end. Following is a sample code we used in calling our REST API contact function.

$data = array("first_name" => "falak", "last_name" =>"nawaz","email"=>"");

function apicall($method,$data_string){
$api_url  = 'http://localhost/rest';
$username = $_POST['username'];

$service_url = "$api_url/?RESTurl=test&method=$method&name=$username&apikey=$key";
//curl_setopt($curl, CURLOPT_HTTPHEADER,$headers );
$curl = curl_init($service_url);
curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS,json_encode($data_string));
$curl_response = curl_exec($curl);
return json_decode( $curl_response);

Download the complete source code: Download

Programming your own RESTful endpoint is simple, is light on code count and provides flexibility.

Rate our Script:

Like our script? Rate it at HotScripts > Hot Scripts

Tagged with: PHPRESTSource Code

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>


Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Related News Feeds

Set your Twitter account name in your settings to use the TwitterBar Section.