Creating you own API endpoint using Services
/**
* Implements of hook_services_resources().
*/
function mymodule_services_services_resources() {
$api = array(
'frontpage' => array(
'operations' => array(
'retrieve' => array(
'help' => 'Retrieves front page',
'callback' => '_mymodule_services_frontpage_retrieve',
'access callback' => 'user_access',
'access arguments' => array('access content'),
'access arguments append' => FALSE,
'args' => array(
array(
'name' => 'fn',
'type' => 'string',
'description' => 'Function to perform',
'source' => array('path' => '0'),
'optional' => TRUE,
'default' => '0',
),
array(
'name' => 'nitems',
'type' => 'int',
'description' => 'Number of latest items to get',
'source' => array('param' => 'nitems'),
'optional' => TRUE,
'default' => '0',
),
array(
'name' => 'since',
'type' => 'int',
'description' => 'Posts from the last number of days',
'source' => array('param' => 'since'),
'optional' => TRUE,
'default' => '0',
),
),
),
),
),
);
return $api;
}
/**
* Callback function for blog retrieve
*/
function _mymodule_services_frontpage_retrieve($fn, $nitems, $timestamp) {
// Check for mad values
$nitems = intval($nitems);
$timestamp = intval($timestamp);
return _mymodule_services_blog_items($nitems, $timestamp);
}
/**
* Gets frontpage blog posts
*/
function _mymodule_services_blog_items($nitems, $timestamp) {
// Compose query
$query = db_select('node', 'n');
$query->join('node_revision', 'v', '(n.nid = v.nid) AND (n.vid = v.vid)');
$query->join('comment', 'c', 'c.nid = n.nid');
$query->join('users', 'u', 'n.uid = u.uid');
$query->fields('v', array('timestamp', 'title'));
$query->addField('u', 'name', 'author');
$query->addField('n', 'nid');
$query->addField('n', 'title');
$query->addField('n', 'uid');
$query->addField('n', 'created');
$query->addField('n', 'changed');
$query->addField('u', 'picture');
$query->addExpression('COUNT(c.cid)', 'comments');
$query->condition('n.type', 'blog', '=');
$query->groupBy('n.nid');
// How many days ago?
if ($timestamp) {
$query->condition('v.timestamp', time() - ($timestamp * 60 * 60 * 24), '>');
}
$query->orderBy('v.timestamp', 'DESC');
// Limited by items?
if ($nitems) {
$query->range(0, $nitems);
}
$items = $query->execute()->fetchAll();
return $items;
}
Tags: