Scripts / Chaining APIs Using DreamFactory php
Description

It's often useful to break APIs down into discrete, highly focused tasks which can then be chained together to perform a more complicated task. This is easily accomplished using DreamFactory thanks to the scripted service feature.

The example presents two separate scripted PHP APIs. The parent API is configured to randomly return either a 200 or 400 status code, simulating the fact that sometimes APIs fail. The second API calls the parent API, and if the status code is 200 it proceeds to call yet another API (in this case a MySQL API which returns records from a table). If anything but a 200 status code is returned, the second API will return a 500 status code.

Code
/*
  * Parent API
  */ 

$outcome = array_rand([1,2]);

if ($outcome == 1) {
    
    $event['response'] = [
        'status_code' => 400, 
        'content' => [
            'success' => false,
            'message' => "Required parameter not found in request."
        ]
    ];

} else {
    
    $event['response'] = [
        'status_code' => 200, 
        'content' => [
            'success' => true,
            'entity_id' => 99,
            'message' => "Value found."
        ]
    ];
    
}

return;

/*
  * Dependent API
  */ 
$api = $platform['api'];
$get = $api->get;
$options = [];

// Define the parent API
$url = "parent/";

// Call parent API
$result = $get($url);

// Check status code
if ($result['status_code'] == 200) {
    
    // If parent API call returns 200, call a MySQL API
    $url = "mysql/_table/employees";
    $event['response'] = $get($url, $payload, $options);

// Something went wrong with parent API call, so throw 500 status code
} else {
    
    $event['response'] = [
        'status_code' => 500, 
        'content' => [
            'success' => false,
            'message' => "Could not complete call."
        ]
    ];
    
}

return;

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?