Blog/ Creating the simplest headless Drupal 7 site

By neerav.mehta Tue, 08/11/2015 - 00:55 2 Comments

In What is headless Drupal post, you learned what exactly is headless Drupal. You also understood the two ways a headless Drupal application can be developed. You got to know of the advantages and disadvantages of both the approaches. In this post, you will create the simplest headless Drupal application possible in less than 15 minutes. By the end of this post, you will have a simple HTML page. On loading this page, JS will send a request to Drupal. Drupal will generate a random number and send it back to the JS. JS will render it on the HTML page. The final rendered HTML will look like the screenshot shown below.

This blog post provides complete instructions and you shouldn't need to refer any other material. But if you do not want to copy / paste file contents from this blog post, then all the material is provided in the headless Drupal git repo. Once you clone this repo, files for this blog post are saved in 01-random-service directory.

1) Create HTML file.

The HTML file created in this step is saved in 01-random-service directory of the headless Drupal git repo. If you want to use this file, then copy it into your Drupal root folder. Otherwise follow the steps below.

In your Drupal root, create a file named "headless-random.html". Open this file and enter the following:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random Number</title>
</head>
<body>
<h1>Random Number</h1>

<div id="random-number"></div>
</body>
</html>

Open this file in your browser. You will see a simple HTML page with title "Random Number" and nothing else.

Now let's add JS to it so that when the page loads, it sends a request to Drupal at the URL /headless-random-service to provide a random number. If the request is successful, then the random number is inserted in the #random-number in the HTML. On the other hand, if there is any error, JS will show the error in an alert box and show the message "Could not fetch data from back-end.". Add the following JS to the HTML file just before </body> tag.

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        $.ajax('headless-random-service', {
            success: function(data) {
                $('#random-number').html(data);
            },
            error: function(jqXHR) {
                $('#random-number').html('Could not fetch data from back-end.');
                alert(jqXHR.statusText);
            }
        })
    });
</script>

The complete HTML file after adding the JS will be:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Random Number</title>
</head>
<body>
<h1>Random Number</h1>

<div id="random-number"></div>
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $.ajax('headless-random-service', {
            success: function (data) {
                console.log(data);
                $('#random-number').html(data);
            },
            error: function (jqXHR) {
                $('#random-number').html('Could not fetch data from back-end.');
                alert(jqXHR.statusText);
            }
        })
    });
</script>
</body>
</html>

Open the HTML page in your browser. You will see an error in the alert message saying that the page was not found. Below the title on the HTML page, you will see the message "Could not fetch data from back-end.". This is happening because we haven't created a back-end service in Drupal to accept the request on /headless-random-service page and return a random number. Let's do that now.

2) Create API Service in Drupal

The module created in this step is present in the folder 01-random-service in the headless Drupal git repo. If you want to use this module, copy the entire contents of the headless_random_service folder to sites/all/modules/custom folder of Drupal. Otherwise, follow the steps below.

We need to create an API in service in Drupal that accepts a request on the URL /headless-random-service and returns a random number. Let's create a module named "headless_random_service" for this purpose in sites/all/modules/custom folder. In this module folder, create headless_random_service.info file with the following content:

name = Headless Random Service
description = Creates a service to return random number.
package = Headless
core = 7.x
files[] = headless_random_service.module

Create headless_random_service.module file and add a service on /headless-random-service URL using hook_menu().

/**
 * Implements hook_menu().
 */
function headless_random_service_menu() {
  $items = array();

  $items['headless-random-service'] = array(
    'title' => 'Headless Random Service',
    'description' => 'Service to return a random number.',
    'access callback' => TRUE,
    'page callback' => 'headless_random_service_page',
  );

  return $items;
}

Now when a request is received on /headless-random-service URL, it will execute the function headless_random_service_page(). Let's define it in the headless_random_service.module file.

/**
 * Page callback for returning a random number.
 */
function headless_random_service_page() {
  echo rand();
  exit;
}

Note that in the headless_random_service_page() function, we are using echo() function to print a random number and then exiting PHP. The reason is that we need to return this number as a plain text and not as HTML. If we had used "return rand();" instead, the whole HTML page would have been returned. A simple echo() function worked in our case becuase we are returning a number. On the other hand, if we were returning an object or an array, it needs to be converted into a proper JSON format before returning. Drupal provides drupal_json_output() function for that. We will use it when we enhance this simple application in a later blog post.

At this point, headless_random_service.module should have the following content:

<?php

/**
 * @file
 *
 * Creates a service that returns a random number.
 */

/**
 * Implements hook_menu().
 */
function headless_random_service_menu() {
  $items = array();

  $items['headless-random-service'] = array(
    'title' => 'Headless Random Service',
    'description' => 'Service to return a random number.',
    'access callback' => TRUE,
    'page callback' => 'headless_random_service_page',
  );

  return $items;
}

/**
 * Page callback for returning a random number.
 */
function headless_random_service_page() {
  echo rand();
  exit;
}

Go to Drupal's module administration page /admin/modules and enable this "Headless Radom Service" module.

Open the URL /headless-random-service in your browser and you should see a random number. If you keep refreshing this page, you will see a different number every time.

 

Now open your old HTML file in your browser. You should see random number returned by Drupal in that file now and every time you refresh the HTML page, you will see a new number returned by Drupal.

Congratulations! You just created your first headless Drupal site. Agreed, this site was very simplistic. In the next post, we will build upon this foundation to add more features to it.

Bonus:

If you want to see how the HTML page and Drupal back-end interact, open the HTML page in Chrome. Right-click and click on "Inspect Element".

In the developer console that opens, click on Network tab and then refresh the HTML page. You will see 3 requests emanating from the browser. First one is for "headless-random.html" page which renders our HTML file. Next browser requests jQuery. The last request is to /headless-random-service URL that our JS embedded in the HTML sends.

If you click on headless-random-service request, you will see the details about this request. Under the Header tab, you will see the full URL to which the request was sent. In my case, it is http://localhost/headless/headless-random-service.

Click on the Response tab and you'll see the actual response returned by Drupal. Our JS embedded in the HTML page takes this response and inserts it in #random-number div in the HTML. As a result, the number returned by Drupal should match the random number you are seeing in the HTML page.

If you found this post to be helpful, please mention it by writing a comment below.

By Kalaung Tone (not verified) Wednesday, August 12, 2015 - 15:46 Permalink

Thanks, i really interested in headless drupal. Your post helps me and I'm waiting for next wonderful headless drupal tutorials.

By george (not verified) Saturday, November 14, 2015 - 13:48 Permalink

This is a great blog. Keep it coming. I am reading them all. Thank you so much. You rock !!

 
Ready to get started?REQUEST A QUOTE