Scripts / Restructuring an API response php
Description

Sometimes an API client expects data to be returned using a rigid data structure, and updating the client to suit new requirements is either difficult or even impossible. Using DreamFactory's event-driven scripting engine you can easily reformat API responses so suit any expectation.

The script presented in this example would be attached to an API endpoint as a post-process event handler. It will intercept the response body, and iterate over the records contained therein, placing the first_name and last_name fields under a new name field before returning the modified response to the client. For instance, here's an example original record returned from a table containing employee information:

{
  "emp_id": "111AD87BY",
  "birth_date": "1953-09-02",
  "first_name": "Steve",
  "last_name": "Smith",
  "gender": "M",
  "hire_date": "1986-06-26"
}

After applying the post-process event handler script, the record will look like this:

{
  "emp_id": "111AD87BY",
  "birth_date": "1953-09-02",
  "name": {
    "first_name": "Steve",
    "last_name": "Smith",
  }.
  "gender": "M",
  "hire_date": "1986-06-26"
}
Code
$responseBody = $event['response']['content'];

foreach ($responseBody['resource'] as $n => $record) {
    $record["name"] = $record["first_name"] . " " . $record["last_name"];
    unset($record["first_name"]);
    unset($record["last_name"]);
    $responseBody['resource'][$n] = $record;
}

$event['response']['content'] = $responseBody;

Need API Advice?

Our team has advised thousands of companies around the world on API projects. Go to market faster by talking to the API experts.

jeanie

Ready to get started?