2

I need to make requests to an API that accepts authentication tokens and I want to be able to use a dynamically generated token by running cmd.exe /c GenerateToken.bat instead of having to run my program and then manually paste the value in Postman every time.

I imagine something that looks like this:

enter image description here

How can I set the value of a HTTP header to contain the stdout output of a program or a batch file?

sashoalm
  • 75,001
  • 122
  • 434
  • 781
  • I don't think it's possible. You need to change batch script to js code then run in Pre-req tab. – lucas-nguyen-17 Nov 02 '21 at 11:24
  • I'm wondering about a cgi-like server on localhost. Then I could use https://stackoverflow.com/questions/45362308/use-authentication-token-in-follow-up-requests-in-postman?rq=1 – sashoalm Nov 02 '21 at 11:26
  • 1
    yes, build a node js server or anything like this, public an API to retrieve token, then use `pm.sendRequest` inside Pre-request. It's a good workaround. – lucas-nguyen-17 Nov 02 '21 at 11:30
  • 2
    I think what you need is described here https://community.postman.com/t/is-it-possible-to-execute-an-external-program-from-postman/5693/2 – Muhammed Kılıç Nov 06 '21 at 21:50

2 Answers2

2

Short answer is, you can't. This is deliberate, both pre-request and test scripts (the only way, other than a collection runner, to make your environment dynamic) run in the postman sandbox, which has limited functionality.

More information of what is available is in the postman-sandbox Github repository page and in postman docs (scroll to the bottom to see what libraries you can import)

You do have a few options, as described in comments - postman allows sending requests and parsing the response in scripts, so you can automate this way. You do need a server to handle the requests and execute your script (simplest option is probably a small server suporting CGI - I won't detail it here as I feel it's too big of a scope for this answer. Other options are also available, such as a small PHP or Node server)

Once you do have a server, the pre-request script is very simple:

const requestOptions = {
    url: `your_server_endpoint`,
    method: 'GET'
}
pm.sendRequest(requestOptions, function (err, res) {
    if (err) {
        throw new Error(err);
    } else if (res.code != 200) {
        throw new Error(`Non-200 response when fetching token: ${res.code} ${res.status}`);
    } else {
        var token = res.text();
        pm.environment.set("my_token", token);
    }
});

You can then set the header as {{my_token}} in the "Headers" tab, and it will be updated once the script runs.

Not a real meerkat
  • 5,604
  • 1
  • 24
  • 55
1

You can do something similar to this from Pre-request Scripts at the collection level.

prerequest

This is available in postman for 9 different authorization and authentication methods.

this is a sample code taken from this article, that show how to do this in Pre-request Scripts for OAuth2

// Refresh the OAuth token if necessary
var tokenDate = new Date(2010,1,1);
var tokenTimestamp = pm.environment.get("OAuth_Timestamp");
if(tokenTimestamp){
  tokenDate = Date.parse(tokenTimestamp);
}
var expiresInTime = pm.environment.get("ExpiresInTime");
if(!expiresInTime){
    expiresInTime = 300000; // Set default expiration time to 5 minutes
}
if((new Date() - tokenDate) >= expiresInTime) 
{
   pm.sendRequest({
      url:  pm.variables.get("Auth_Url"), 
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'Content-Type': 'application/x-www-form-urlencoded',
        'Authorization': pm.variables.get("Basic_Auth")
      }
  }, function (err, res) {
        pm.environment.set("OAuth_Token", res.json().access_token);
        pm.environment.set("OAuth_Timestamp", new Date());
        
        // Set the ExpiresInTime variable to the time given in the response if it exists
        if(res.json().expires_in){
            expiresInTime = res.json().expires_in * 1000;
        }
        pm.environment.set("ExpiresInTime", expiresInTime);
  });
}
user16930239
  • 6,319
  • 2
  • 9
  • 33