Search code examples
postman-pre-request-script

How to run a GET and a POST request from pre request tab of another request in postman?


I am in a situation where I need to run a request (lets say request C) based on the responses of request A and B. Here A is a GET & B is a POST request. Now I have tried to use pm.sendRequest twice in pre-request tab of C. But the problem I am facing mainly is, B is running ahead of A all the time. That means POST is running before GET. As a result I am unable to successfully run request C.

Here is a sample of my pre request script:

const getOTP = {
  method: 'GET',
  url: `${pm.environment.get('base_url')}/${pm.environment.get('common_path')}/otp-login?msisdn=${pm.environment.get('msisdnWhite')}`,
  header: {
      'User-Agent': 'something..',
      'Accept-Language' : 'en'
  },
  
};
setTimeout(15000)

const postOTP={
    method : 'POST',
    url : `${pm.environment.get('base_url')}/${pm.environment.get('common_path')}/otp-login`,
    header: {
        'Content-Type':'application/json',
        'Accept-Language':'en'
    },
    body:{
        mode : 'application/json',
        raw: JSON.stringify(
            {
               "msisdn":"123456789",
                "otp":"0000"
                } )
    }
};


 pm.sendRequest(getOTP, (err, response) => {
  const jsonResponse = response.json();
  pm.environment.set("GETOTP",jsonResponse.result)
  console.log(jsonResponse);
 });

 pm.sendRequest(postOTP, (err, response) => {
  const jsonData = response.json();
      pm.environment.set("access_token",jsonData.access_token)
});

Solution

  • It seems you need to run request A, wait for the response, then run request B, and wait for the response again.

    To do this you could trigger the sendRequest() for B in the callback of the A request.

    For example:

    // send GET request A
    pm.sendRequest (getOTP, (err, response) => {
    
        // here you are in the callback of the request A
        // this runs after the response of the request A
        const jsonResponse = response.json ();
        pm.environment.set ("GETOTP", jsonResponse.result)
        console.log (jsonResponse);
    
    
        // send POST request B
        pm.sendRequest (postOTP, (err, response) => {
            // here you are in the callback of the request B
            const jsonData = response.json ();
            pm.environment.set ("access_token", jsonData.access_token)
        });
    });
    
    

    I saw you set a setTimeout(15000), I guess it's to wait for the answer of A. You shouldn't use setTimeout for this purpose, so please delete it.

    That said you need to know that if you wanted the setTimeout() to be useful you need it between the two sendRequest() functions. It doesn't do much right now, between the two variables declarations.