Postman extension had a feature of setting an environment variable from one of the values from response headers or body. It is missing after update. Can someone help here.
You can set the environment variable from response body/header as follows:
From Response Body:
var body = JSON.parse(responseBody);
postman.setEnvironmentVariable("[environmentVariable]", body.variableName);
From Response Header:
var headerName = responseHeaders.headerName;
postman.setEnvironmentVariable("[environmentVariable]", headerName);
For Postman extension on Chrome latest version (by posting time) version 4.8.3 here.
Everthing is working fine regarding setting an environment variable programatically in either Pre-request script section or Tests section.
For more info, check docs here.
This is an old question, I'll leave this here as an update:
to set a variable from response body ( JSON ):
var jsonData = JSON.parse(responseBody);
pm.environement.set("your_var", jsonData["the_value"]);
and to get it from a header:
var value = pm.response.headers.get("the_header");
pm.environement.set("your_var", value);
Related
I am trying to extract the sys_id value and store it as a variable within postman. Currently I am not getting any errors using the following
var data = JSON.parse(responseBody);
pm.environment.set('sys_id', pm.response.json().sys_id);
It is saving the variable, but showing null within the value
Response Body
{
"result": {
"sys_id": "5ae690c11ba421d46557a9b7bd4bcbbf",
}}
Any help will be appreciated!
Without knowing the whole value of the response body - and based on this link, you can try this code - which I tested with another JSON data payload:
Code:
let data = pm.response.json();
pm.environment.set('sys_id', data.result.sys_id);
console.log(pm.variables.get("sys_id"));
Managed to resolve it with the following code:
var responseData = JSON.parse(responseBody);
postman.setEnvironmentVariable("sys_id", responseData.result.sys_id);
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:
How can I set the value of a HTTP header to contain the stdout output of a program or a batch file?
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.
You can do something similar to this from Pre-request Scripts at the collection level.
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);
});
}
I want to set basic Authorization in Postman using environment variable. Because I have different authorization username and password for the different API calls.
I set my postman according to below:
In Authorization Tab: I've selected No Auth
In Header Tab: Key=Authorization Value= Basic{{MyAuthorization}}
In Body Tab:
{
"UserName": "{{UserName}}",
"ServiceUrl": "{{ServiceUrl}}"
}
//which set it from the envitonment variable
In Pre-request Tab:
// Require the crypto-js module
var CryptoJS = require("crypto-js");
// Parse the `username` and `password` environment variables
let credsParsed = CryptoJS.enc.Utf8.parse(`${pm.environment.get('admin')}:${pm.environment.get('admin')}`);
// Base64 encoded the parsed value
let credsEncoded = CryptoJS.enc.Base64.stringify(credsParsed);
// Set the valuse as an environment variable and use in the request
pm.environment.set('MyAuthorization', credsEncoded);
console.log(credsEncoded);
In Test Tab:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("LoginInfoID", jsonData.First.LoginInfoID);
Then I've sent the request and got unauthorized.
After that, I've set auth type to basic auth with username and password
it's working fine and I got what I wanted from the response.
Another way which worked for me:
Set up environment variables for 'username' and 'password', and save
In the Authorization tab of the request, select Basic Auth
In the Username field, enter {{username}}
For the Password field, click "Show Password", and enter {{password}}
Hope this helps others :)
You could use cryptp-js in a Pre-request Script with a very crude solution like this:
// Require the crypto-js module
var CryptoJS = require("crypto-js");
// Parse the `username` and `password` environment variables
let credsParsed = CryptoJS.enc.Utf8.parse(`${pm.environment.get('username')}:${pm.environment.get('password')}`);
// Base64 encoded the parsed value
let credsEncoded = CryptoJS.enc.Base64.stringify(credsParsed);
// Set the valuse as an environment variable and use in the request
pm.environment.set('authCreds', credsEncoded);
You could add your credentials to a set of different environment files, under the key username and password.
In the request, just set the Header like this:
You can also set those at the Collection / Sub-folder level so you're not repeating yourself in each request.
It's one way you could achieve this but there will be other ways too.
So I'm trying to use chained request with Postman, where the first request will pass the data to the next request and I would use that data as a body. I was able to that, however there is an issue if there is x-www-form-urlencoded type of request involved because Postman will convert this:
Request body:
{{data}}
Into this:
{{data}: ""
Is there maybe a way to tell Postman not to add a colon in case variable is set as a body ?
Turns out there is no direct solution for this issue, so I had to find a way around. What I did was, create environment variables and then hard code key names and values that are expected in the request body:
Step1: Request1 - (Tests tab)
function setEnvironmentVars(obj) {
for(var prop in obj) {
postman.setEnvironmentVariable(prop, obj[prop]);
}
}
setEnvironmentVars(data);
postman.setNextRequest("Request2");
So instead of passing the data object to Request2, I am creating env variable for each property in the data object, which will be accessible directly. This is executed automatically after the Request 1 completes.
Step2: Request2 (Body tab)
In the Request 2, I set the request type to x-www-form-urlencoded and then bulk edited the body with keys and env vars as values:
VAR1:{{VAR1}}
VAR2:{{VAR2}}
This solution for works very well, as the key names are always the same.
I want to create test request on postman with unique email property in the request body.
{
...
"email": "{{email_string}}.com",
...
}
I've set email_string with static string in enviroment, but is there any way that I can set email_string dynamically before request occured?
You can use Postman's built in support for the Faker library direct in the request body:
{
...
"email": "{{$randomEmail}}",
...
}
or, in a pre-request script:
pm.environment.set('user-email', pm.variables.replaceIn('{{$randomEmail}}'));
As an alternative to the previous answer, you could use the sendRequest function to get the value from a 3rd party API that is designed to return randomised data.
This can be added to the Pre-Request Script tab:
pm.sendRequest("https://randomuser.me/api/", (err, res) => {
// Get the random value from the response and store it as a variable
var email = res.json().results[0].email
// Save the value as an environment variable to use in the body of the request
pm.environment.set("email_address", JSON.stringify(email))
})
You could potentially create lots of randomised data using this API but it is a 3rd party API so you won't have any control over this changing. If you only need this in the short term, i'm sure it will be fine.
Something also worth remembering is that Postman comes with Lodash built-in so that gives you the ability to use any of that modules functions, to reduce down some of the native JS code.
There is tab in postman application named "pre-request script" near to "Test" tab. You can use this tab to set your environment variables.
Here is the trick:
var text = "";
var possible = "abcdefghijklmnopqrstuvwxyz";
for (var i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
postman.setEnvironmentVariable('email_string', text + '#' + text);
I think this script could help you to set a random value in your environment.