How to Set Variable from Request in Postman - testing

I am trying to write some tests for Postman. Many of the requests require an API key that gets returned by an initial GET request.
To set something hard-coded that is not dynamic, it looks like the test code is of the form
let variable = pm.iterationData.get("variable");
console.log("Variable will be set to", variable);
How do I set a return value as a global variable and then set that as a header parameter?

#Example if you setting ApiToken that is dynamic.
Under Tests tab in postman.
Put the following code.
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("Token", jsonData.token);
Under specific environment put variable name as "Token" and current value will be set automatically.
access the variable using {{variable_name}}
#Example: {{token}}

You can specify that variable value in the request Headers by using the {{var_name}} syntax. Instead of any hardcoded value that you may have been using.
You would previously have had to set the value using the pm.globals.set()syntax.

If you do not have the SDK active (monthly payment required to Postman). You can retrieve the values through __environment and __globals.
//Use of environment
postman.setEnvironmentVariable("my_value", "This is a value");
//...
let myValueVar = postman.__environment["my_value"];
console.log("Variable value is:", myValueVar);
//shows: Variable value is: This is a value
//Use of Globals
postman.setGlobalVariable("my_value2", "This is a value of globals");
//...
let myValueVar2 = postman.__globals["my_value2"];
console.log("Variable value is:", myValueVar2);
//shows: Variable value is: This is a value of globals
Also you can see your globals variables in Environments->Globals of your Posmant client.

Related

How to get value from response body by using environment variable

This is my response body, I want to get the value of status by using an environment variable.
{
"success":[
{
"code":"200",
"message":"Success",
"details":"Station was retrieved successfully."
}
]
}
i can get value of status code as: jsonData.success.code,
But instead of this, I'm doing it like,
I m setting an environment variable named 'sh' n I gave value as "code"...
pm.environment.set("sh","code");
var s = pm.environment.get("sh")
jsonData.status.success[0].s
By doing like this I'm not able to get the path...Any solutions?
Thanks in advance.
It's hard to tell what your actual response body is but this should probably work:
let statusCode = pm.response.json().success[0].code
pm.environment.set("statusCode", statusCode)
Ensure that you create an environment file before running the request.

Postman Test script - Set Env variable with response header query param

I am trying to set an env variable with a query param received in the response.
i am sending a POST request and in the response I am getting a resource id i need to use in the next request (therefore need to add it as an env variable).
the response Header:
location →
https://mmmmmmmm.nnnnnnnn.xxxxxx/oauth-signin?client_id=bbbnnnmmmm-bbnn-46ba-a287-nnhhyyy&redirect_uri=https://mmm.nnnn.nnnn/galaxy-backend/redirect/oauth/token&response_type=code&state=kYIL97&protocol=berlin-v13&consent_id=5d1372ebfb0b3a09b2ea4ddb&scope=accounts.accountDetails.read+accounts.transactions.read+accounts.balances.read
i am trying to retrieve the value form the query param 'consent_id' and set it in env variable.
my env variable is named 'ConsentId'.
i tried:
pm.environment.set('ConsentId', JSON.stringify(pm.response.header.getQueryString("consent_id")));
No luck.
Would appreciate help with how to write it so the script will get the field from the a url param in the header and place it in the env variable.
To get ConsentId parameter value in Location response header and set it as environment variable in Postman:
var key = 'consent_id';
var regex = new RegExp('[?&]' + key + '(=([^&#]*)|&|#|$)');
var redirectURL = postman.getResponseHeader('Location');
var matchResult = regex.exec(redirectURL);
var consentId = decodeURIComponent(matchResult[2].replace(/\+/g, ' '));
pm.environment.set('ConsentId', consentId);
BTW, to make above code work well, "Automatically follow redirects" option should be turned off:
Note: I failed to extract Location header from pm.response.headers, that's why postman.getResponseHeader() is used in above code.

In a Postman pre-request-script, how can I read the actual value of a header that uses a variable

I have a variable called token with a specific value myTokenValue
I try to make a call that includes that variable in a header, tokenHeader:{{token}}
I also have a pre-request-script that needs to change the request based on the value of the token header, but if I try to read the value pm.request.headers.get('tokenHeader') I get the literal value {{token}} instead of the interpolated myTokenValue
How do I get this value without having to look at the variable directly?
You can use the following function to replace any Postman variables in a string with their resolved values:
var resolveVariables = s => s.replace(/\{\{([^}]+)\}\}/g,
(match, capture) => pm.variables.get(capture));
In your example:
var token = resolveVariables(pm.request.headers.get('tokenHeader'));
Basically I was missing a function to interpolate a string, injecting variables from the environment
There are some workarounds:
write your own function, as in this comment by pomeh
function interpolate (value) {
return value.replace(/{{([^}]+)}}/g, function (match, $1) {
return pm.variables.get($1);
});
}
use Postman's own replaceSubstitutions, as in this comment by codenirvana
function interpolate (value) {
const {Property} = require('postman-collection');
let resolved = Property.replaceSubstitutions(value, pm.variables.toObject());
}
Either of these can be used as
const tokenHeader = interpolate(pm.request.headers.get('tokenHeader'));
but the second one is also null safe.

Set response headers

I need to set some response headers within server.onPreHandler ext method.
There are 2 scenarios, where I need this happen when user sends an API request to my route end point.
1) In success scenario, I need to set headers and let process continue further down life cycle
2) In error scenario (where user has not provided a required field), I need to set headers and return immediately to user with appropriate error info.
In both of these scenarios, I would like to set response headers.
In the 2nd scenario above, I am able to invoke reply.response('error') and then set response header to it using response.header('x', 'value'). However, in the 1st scenario, where before calling reply.continue() I am trying to set header using request.response.header('x', 'value), I get response null error.
Please help
Thanks
Ramesh
I'm able to change response headers like this. Have you tried this way?
// at your onPreResponse ext body
const response = request.response;
if (request.response.isBoom) {
response.output.headers['x'] = 'value';
} else {
response.header('x', 'value');
}

Custom Cookie variable + Prestashop

Prestashop
I am stuck we one problem for cookie. In prestashop 1.4.7 I create a custom cookie variable using setcookie but when i am try to access and assign it on front-controller, I am not getting cookies set value.
here is my script:
page: checkpostcode.php
include(dirname(__FILE__).'/config/config.inc.php');
include(dirname(__FILE__).'/init.php');
global $cookie;
setcookie("is_postcode_checked", 1, time()+600, "/", "", 1); // Set the cookie in basepath
On frontcontroller.php page :
I am access it using $_COOKIE and assign it into smarty array.
'is_postcode_checked' => $_COOKIE['is_postcode_checked'] // Getting null value for cookie
page: checkpostcode.tpl
{$cookie->_get(postcode_checked_msg)} // here get the is_postcode_checked value but
but I am not able to get is_postcode_checked variable value.
In prestashop 1.5, global are deprecated.
To set something in the cookie :
In a controller :
$this->context->cookie->__set($key,$value);
Other file :
$context = Context::getContext();
$context->cookie->__set($finger_print,$result);
You can access to your value with :
In a controller
$this->context->cookie->key
Other file :
$context = Context::getContext();
$context->cookie->key;
You should use Prestashop's own cookie class entirely rather than using the PHP setcookie() function. The class uses the "magic methods" __get(), __set(), __unset() and __isset() which should allow you to do this easily.
Try in your "page" code (not sure how you're executing this since it doesn;t look like an additional page controller):
global $cookie;
$cookie->is_postcode_checked = 1;
$cookie->write(); // I think you'll need this as it doesn't automatically save
...
And in your FrontController override:
global $cookie;
if (isset($cookie->is_postcode_checked))
$is_postcode_checked = $cookie->is_postcode_checked;
else
$is_postcode_checked = 0;
You can assign the variable $is_postcode_checked to a corresponding smarty variable to use in your template.
If you want to fetch the cookie from Prestashop cookie class, you should store it in this class too.
Use die() function in your controller, to find out is that cookie set
It is better, as Paul said, to use only global $cookie class to store and getting data.