3

Is there a way to control the output in the drupal services? Example, if a argument that is required, it not provided in the call, I get the following output as a JSON array.

Missing required argument title

I'd like to either override this output, or instead of returning a json object, just return plain text.

Is this possible to do?

3

You most certainly can.

If you open up the docs folder in the services module you can see the function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) in the file services.alter.api.php

<?php
/**
 * Allows alteration of error data before the status code or message are returned.
 *
 * @param array $error_alter_array
 *   An associative array with the following keys:
 *     - 'code': the HTTP status code.
 *     - 'header_message': the message returned as part of the error response
 *       (for instance, "404 Not found").
 *     - 'body_data': data that was passed to the thrown exception.
 * @param array $controller
 *   The current controller definition.
 * @param array $arguments
 *   Arguments passed to the current controller.
 *
 * @see RESTServer->handleException()
*/
function hook_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {

}

Example output would be:

Array (
  [code] => 401
  [header_message] => 401 Unauthorized : Missing required argument username
  [body_data] => Missing required argument username
)

So you could alter it like,

function MYMODULENAME_rest_server_execute_errors_alter(&$error_alter_array, $controller, $arguments) {
 $error_alter_array['code'] = 500;
 $error_alter_array['header_message'] = '500 Come on man, send that username';
 $error_alter_array['body_data'] = 'Come on man, send that username';
}

Note: You do not need to return anything because it is alter by reference and two, make sure you clear cache after adding this function to a module.

  • Feel free to upvote the answer too :) – Kyle Browning Oct 15 '14 at 19:47

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.