Calling a REST Server using JSON with PHP
Last updated on
30 April 2025
Here is a small module to access a REST server using PHP. The module assumes that you already have services installed with a REST server working and that you've already created some nodes.
This module gets a node and prints the node and body. It's really simple and is just meant as a demo.
File: restget.module
<?php
/**
* Implements hook_menu()
*/
function restget_menu() {
$items['test'] = array(
'title' => 'Test',
'page callback' => 'restget_page',
'access callback' => TRUE,
'type' => MENU_NORMAL_ITEM
);
return $items;
}
/**
* Get the element as object
* @param $uri the URI to get
* @return object
*/
function _get_element() {
// Get the node with nid 31 using JSON format.
$uri = "http://localhost/mysite/api/rest/node/31.json";
$response = file_get_contents($uri);
// This will return an array, if you want an object, use json_decode($response) directly. See the comments below
return drupal_json_decode($response);
}
/**
* Page callback
*/
function restget_page() {
$element = _get_element();
// See the complete object with
// return dprint_r($element);
// If you used drupal_json_decode in _get_element() you'll have an array instead of an object
$output = '<h2>' . $element->title . '</h2>';
$output .= '<p>' . $element->body->und[0]->value . '</p>';
return $output;
}
?>
Be aware that you're not supposed to return HTML inside a function like I do in restget_page, to do that, you're supposed to create a theme function and pass the $output to that theme function, but since this is just a demo module I didn't want to over complicate
Help improve this page
Page status: Not set
You can:
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion