1

I am creating a custom web service. In this, as soon as service call, data should be store into database. I am using Hook_service_resource() function. How can i implement insertion into database using services. I created my_module.install file and prepare database schema. BUT i actually don't know how to use query in hook_service_resource() function.

2
  1. Create a Custom Drupal Module

Create these empty files in the new directory:

my_module.info
my_module.module
my_module.install
my_module.resource.inc
my_module.services.inc

Place this code in the my_module.info file:

name = My Module
description = My custom Drupal module.
package = Other
core = 7.x
dependencies[] = services
dependencies[] = rest_server

Place this code in the my_module.module file:

<?php

/**
 * Implements hook_ctools_plugin_api().
 */
function my_module_ctools_plugin_api($owner, $api) {
  if ($owner == 'services' && $api == 'services') {
    return array(
      'version' => 3,
      'file' => 'my_module.services.inc'
    );
  }
}

Place this code in the my_module.services.inc file:

<?php

function my_module_services_resources() {
  $resources = array(
    'my_module_resources' => array(
      'actions' => array(
        'insert_into_database' => array(
          'help' => t('Insert Database Example.'),
          'file' => array(
            'type' => 'inc',
            'module' => 'my_module',
            'name' => 'my_module.resource',
          ),
          'callback' => 'my_module_insert_into_db',
          'args' => array(),
          'access arguments' => array('access user profiles'),
          'access arguments append' => FALSE,
        ),
      ),
    ),
  );
  return $resources;
}

Place this code in the my_module.resource.inc file:

<?php

function my_module_insert_into_db() {
  $id = db_insert('example_table') // Table name no longer needs {}
->fields(array(
  'title' => 'Example',
  'uid' => 1,
))
->execute();
  if ($id) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}

Change the access arguments as per your permissions settings..

Call the service

http://www.example.com/?q=serviceendpoint/my_module_resources/insert_into_database.json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for?Browse other questions tagged or ask your own question.