Create custom RESTful API endpoint with JSON output in Drupal

Gulab Bisht
Aug 28, 2018 · 2 min read

RESTful API endpoints in Drupal can allow you to expose the content of Drupal website to other external resources. These endpoints can be used for fetching data with an AJAX call or simply a web service.

For making complex RESTful web services in Drupal, Services module is the best option to go for but if you looking for a simple endpoint in Drupal, which outputs JSON response then going with a custom solution will be the best bet.

Create API endpoint with JSON response in Drupal

To create a simple API endpoint in Drupal to serve a JSON put you need to create a custom callback

* Implements hook_menu().
function mymodule_menu() {
$items['api/mymodule'] = array(
'access callback' => true,
'page callback' => 'mymodule_json',
'delivery callback' => 'drupal_json_output',

return $items;

A noticeable point in this callback is the “delivery callback” argument which runs the output through drupal_json_output function.

* Callback function to return the data.
function mymodule_json() {
$data = ['cat', 'dog', 'mouse', 'elephant'];

return $data;

Now if you navigate to the callback url ‘api/mymodule’ to see the output then you will see the following result


Now you can see that this output is exposed as a JSON and can be consumed by other platforms or an AJAX callback to consume data.

The same approach can be used to expose a node or a user as a JSON output.

Originally posted on Drupixels:

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade