How to build a simple API endpoint in Drupal 7

7 minute read

When working on a Drupal site I often need to fetch data from the server via an AJAX call. There are some great third party modules for doing this, notably Services, but sometimes a DIY approach is the best solution.

In this tutorial I will go through the steps I take to setup a simple JSON API in a custom module. The endpoint will return an array of nodes that have been created in the last hour. Rather than returning the entire node object we will simply return the nid and title.

To start with we need to create a custom module, the file structure should look something like this:

The module's .info file is very simple and looks like this.

Then inside latest_content.module implement hook_menu() and create the endpoint path.

Now we'll need to create the function that is referenced in the page callback option above. This function is kept intentionally simple to start with so that we can make sure the module is registering a path and returning data as expected. We're using drupal_json_output() here which takes care of setting http headers and encoding data.

Now enable the module and open the path registered in latest_content_menu in a browser. If you've been following along this should be "ajax/latest-content.json".
You should see the following JSON in your browser:

If not, double check that you're module is enabled and that Drupal's caches have been cleared.

The next step is to replace the dummy data with information fetched from the database. To do this we'll be using the db_select() function.

The db_select() function returns a SelectQuery object which can be used to fetch data from the Drupal database. The parameter passed to db_select() is the table we want to query, in this case, it's the node table from the Drupal database. We use the addField() and condition() methods to construct the query and then run it with execute().

The execute() method can be a little confusing at first glance. It returns an object that implements Drupal's DatebaseStatementInterface, the methods for which can be found here. The method I will typically use for simple queries like this is fetchAll() which will return an array of objects.

Putting this together, our callback function now looks like this:

To test this you will need to create a new node before visiting the API endpoint.
On my development machine I can now see the following JSON:

Whilst this example is quite simple it demonstrates how straightforward it is to create a JSON endpoint in Drupal 7.