Please wait...
Drupal 7, Services

Drupal: Alter API response with Services API

This post relates to my previous post concerning an inherited API built with Drupal 7 Services module. In this example, I want to add some data to the response, but only for specific resources. I don’t want to alter the Entity Field Query that actually grabs the response data, because it works in an abstract way for every content type. Forcing it to behave differently based on which type is requested would make the API more difficult to maintain or refactor if needed in the future.

Services API to the rescue! Specifically, hook_services_request_postprocess_alter(). This hook fires after the request has been processed and takes as one of it’s parameters the $result object that contains the API response. This means that we can manipulate the response just before sending it back to the consumer. i.e. - We can add some data to the response AFTER the EFQ has pulled in the data and BEFORE the response has been returned by Services.

In this example, let’s say I want to send back a string of data along with the response, but only for ‘widget’ requests. It’s a silly example, I know, but my real-world example is a bit too complex for a blog entry, so this example will simply serve to show how to add data to the response object.

Now when the response comes back, it’ll look something like:

And that’s basically it. Play around with the result object from within hook_services_request_postprocess_alter(), and you’ll start to see loads of possibilities for adding or removing data to/from the response object.