Multiple API calls in single synthetics

Hi,

My usecase is that I have to call a API to get accessToken and use that in the header of the next API call. How can I do that in synthetic

Regards,
Santhosh

Hi @Santhosh.Karupakula - Have a look at my sample API synthetic script. It has a maintenance window function in it that you can remove.

1 Like

Hi @Santhosh.Karupakula, alternative to @stefan_garnham 's great example of using promises for asynchronous control flow, you can also make multiple HTTP requests to APIs using the callbacks functions of preceding requests to have asynchronous control flow as well. A fellow Synthetics explorer shared an example of a similar use case, where they make one call to an API to fetch a token, which is then used in a subsequent API request:

Oauth2 Synthetics API Test?

1 Like

@Santhosh.Karupakula I wrote up a quick Synthetics API example using native JS promises, that might also be helpful here:

  1. Perform initial API call to retrieve value to be used as header.
  2. Perform second API call using this retrieved value as a "mycustomheader" HTTP header.
  3. Logs response from second API call.
//function that makes initial API request to retrieve value to be used as header, later on.
function getHeaderValue() {
    return new Promise(function(resolve, reject) {
        var options = {
            method: 'GET',
            url: 'http://httpbin.org/get'
        }
        $http(options, function(error, response, body) {
            if (error) {
                reject(error)
            }
            var jsonResponse = JSON.parse(body);

            //resolve promise with value to be used as header value
            resolve(jsonResponse.origin);
        });
    });
}

//function that makes second API request, taking custom header value as argument
function makeAPIrequest(customHeaderValue) {
    return new Promise(function(resolve, reject) {
        var options = {
            method: 'GET',
            url: 'http://httpbin.org/headers',
            headers: {
              'mycustomheader': customHeaderValue
            }

        }
        $http(options, function(error, response, body) {
            if (error) {
                reject(error)
            }

            //resolve promise with response body to be logged
            resolve(body);
        });
    });
}

//Main promise chain
getHeaderValue()
.then(makeAPIrequest)
.then(function(apiResponse) {
  console.log(apiResponse);
}).catch(function(error) {
  console.log(error);
})
3 Likes

Hi Michel_L,

We did try this approach is working great for us. Thank you for the help.

Regards,
Santhosh

1 Like

It doesn’t appear that this code will fail the synthetic check if there is an error. From my Promise testing with $http you have to be the request when you make the assert falsey. And you you do that you get a Promise unhandled reject and the script doesn’t fail.

Do you know if your script example will actually fail the check?