Scripts / Validating Existence of API Payload Parameters php
Description

Using the /_table/{table_name} endpoint it's easy to insert a new record into a database backed by a DreamFactory generated database API. By default the underlying database constraints will serve as a validation backstop, meaning if a required (not nullable) field is not provided, the database will throw an error and DreamFactory will in return return a 500 status code to the client.

You might however wish to customize both the validation logic and error response. This is accomplished using DreamFactory's scripting engine. Specifically, you can add custom logic to the POST endpoint's pre-process event handler, meaning the custom code will execute before the destination data source is contacted.

Code
$payload = $event['request']['payload'];

if(!empty($payload['resource'])){
    foreach($payload['resource'] as $record){
        if(!array_key_exists('first_name', $record)){
            throw new \Exception('First name field missing.');
        }
    }
}

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?