Drupal 7 as a Web Service Using PHP

Drupal is an open source content management system (CMS) and as such, can be useful as a back-end supporting system for other applications, mobile, web or any other. In order to connect between various applications and the Drupal system, we need to construct some kind of web service functionality. This will enable us to easily send and retrieve information to and from the Drupal site.
In this two part tutorial I will describe how to create a simple XML based web service using Drupal 7, however this can be easily done on other Drupal versions like Drupal 6.

Part 1: Create an access point to the Drupal system

Every web service needs some point of entry that will enable external systems a connection to the back-end system. Creating this kind of access point on the Drupal platform is done using the hook_menu() function.
First, it is best to create your own module where you will write your custom PHP code. Let's call this module "mymodule". So the file be named "mymodule.module" and inside that file, we will implement the hook_menu() function like so:

include_once('ws.inc');
/**
  * Implements hook_menu().
  */
function mymodule_menu() {
  $items = array();
  $items['ws'] = array(
    'title' => 'MyModule API',
    'description' => 'MyModule API',
    'page callback' => 'mymodule_execute_ws_call',
    'access callback' => 1,
    'access arguments' => array('access content'),
    'file' => 'ws.inc',
    'type' => MENU_CALLBACK,
  );
  return $items;
}

 
The above code will enable external applications to access the Drupal system using a simple HTTP GET or POST call to the "http://www.domain.com/ws" URL. Once this URL is called, the request will be processed by a function named "mymodule_execute_ws_call" which is located in the "ws.inc" file. This leads us to the next part of this tutorial: How to handle HTTP requests.

Part 2: How to handle HTTP requests

Inside a file named "ws.inc" we will introduce a function called "mymodule_execute_ws_call". This function will check the request arguments and look for a parameter named "op". According to the value of that parameter, the function will parse the request for the remaining required parameters and execute the designated logic.
For example, the external application will call "http://www.domain.com/ws?op=TEST&name=World" and the return XML will be:

<?xml version="1.0" encoding="UTF-8"?>
<XmlResponse>
  <TEST>Hello World!</TEST>
</XmlResponse>

 
The code for this function will be something like this:

/**
  * Execute Web Service Call
  */
function mymodule_execute_ws_call() {
  // Start building XML
  $response = "<?xml version="1.0" encoding="UTF-8"?><XmlResponse>"
  if (!isset($_POST["op"]) && !isset($_GET["op"])) {
    // Return an error xml
    $response .= "<Error>Missing operation argument</Error>";
  }
  else {
    // Get "op" parameter from POST or GET requests
    $op = strtoupper($_POST["op"]);
    if (!isset($op)) {
      // Get name from GET request
      $op = strtoupper($_GET["op"]);
      $name = $_GET["name"];
    }
    else {
      // Get name from POST request
      $name = $_POST["name"];
    }
    if (!isset($name)) {
      // Return error XML
      $response .= "<Error>Name missing</Error>";
    }
    else {
    // Do something according to "op" argument
      switch ($op) {
        case "TEST":
          // Create TEST XML response
          $response .= "<TEST>Hello " . &name . "!</TEST>";
          break;
      }
    }
  }
  // Finish XML
  $response .= "</XmlResponse>";
  // Make sure the response is understood as XML
  header('Content-Type: text/xml');
  // Send response back
  echo $response;
}

 
This is a very simple example of how to parse parameters from GET or POST requests using PHP and how to return an XML response. Obviously, a more generic solution is needed if we want the Drupal web service we built here to handle numerous types of requests (different "op" argument values). This can be done by building a generic PHP class that represents an XML response, but that is for another tutorial ;)

Comments

It's works but $_POST is empty

Hook_menu works for me. But $_POST is empty. Why?

$_POST is available only when

$_POST is available only when reaching the page after submitting a form ("POST" method request). If you simply put the page URL in your browser, it is a "GET" method request, not "POST" so you will only have data in $_GET.

$_POST not a method in https services

I think $_POST just use for form action, and it not able to use for http request. I mean if we want to catch the response from POST method in web services, we use the http_get_request() functionality from PHP.

Add new comment

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
CAPTCHA

This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

Image CAPTCHA