Scripts / Create Data Masks for an API php
Description

When interacting with a database-backed API, DreamFactory will by default return all fields associated with each record. You'll often want to restrict access to certain data due to for instance internal compliance or regulatory needs.

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, removing the employee_id and birth_date fields 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"
}

Some information might however be sensitive and therefore subject to restrictions. Modifying the query would ensure that the emp_id and birth_date fields were removed from the query:

/api/v2/mysql/_table/employees?fields=first_name,last_name,gender,hire_date

However, the organization might desire to completely restrict the possibility of such fields being returned. One easy way to implement this restriction is through data masking. Once implemented, the record will look like this, regardless of what API query is used:

{
  "first_name": "Steve",
  "last_name": "Smith",
  "gender": "M",
  "hire_date": "1986-06-26"
}
Code
$responseBody = $event['response']['content'];

foreach ($responseBody['resource'] as $n => $record) {
    unset($record["employee_id"]);
    unset($record["birth_date"]);
    $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?