Can I use postman collection variable inside newman? - postman

Using variables from scope: collection inside Postman works fine.
But when I export collection and use it inside Newman it does not work as I expected.
1) Variabes are inside collection json, in the end of file - ok.
2) I use this code:
var obj = {};
obj.categories = pm.variables.get("category_id");
obj.packages = pm.variables.get("package_id");
obj.type = "add";
pm.globals.set("switch_json", JSON.stringify(obj));
console.log("request body: " + pm.globals.get("switch_json"));
in pre-request script to get value of 2 collection variables (category_id, package_id).
3) Inside Postman all works fine, console.log return:
request body: {"categories":"14","packages":"2","type":"add"}
4) Inside Newman console.log return only:
'request body: {"type":"add"}'
Does it mean Newman do not support collection variables?

Collection Variables are stored in the variables tab in collections under Edit. Initial values are shared when you export a collection and not the current values. Newman will access these(initial Values) values.

you shall save your environment (ie. my_environment.json) then, in your newman command use the -e option to use it.
have a look here for newman options
hope this helps
Alexandre

I looked around and around for a way to set a collection variable on the command line, without using an environment file, without finding any answers so I just tested using --env-var and it worked.
In the case of the original question it would look like this:
newman run xxxxxxx --env-var package_id=14

I face the similar issue, but because I need to override the collection variable from command line using --env-var(there is no --collection-var in options) but seems not working, I think because collection variable is narrow than the environment so won't work.
I think your case works because you have different variable name, is it?

Related

Postman - Nested Environment Variables

I'm looking for a way to make environment variables in Postman, that contain other variables. For example: {Server}=localhost;{Port}=9200;{ServerUrl}={Server}:{Port}.
Like in Make...
This way it doesn't seem to work with Postman.
EDIT:
My attempt:
You could do it but I wouldn't recommend it, just seem like you're missing the benefit creating a set of variables and then changing the values of these by selecting a different environment file.
Add this string {{ElasticsearchProtocol}}://{{ElasticsearchServer}}:{{ElasticsearchPort}} as the ElasiticsearchUrl variable, on the environment file.
Or you could add this to the Pre-Request Script:
let ElasticsearchProtocol = pm.environment.get('ElasticsearchProtocol')
let ElasticsearchServer = pm.environment.get('ElasticsearchServer')
let ElasticsearchPort = pm.environment.get('ElasticsearchPort')
pm.environment.set("ElasticsearchUrl", `${ElasticsearchProtocol}://${ElasticsearchServer}:${ElasticsearchPort}`)

How can I use Postman Collection Variables?

When I add environment variables I can use them in my post body with {{varName}}. But this does not work for collection variables (Collection > edit > Variables tab)
With the settings as shown above, if I add {{firstName}} to my body it does not work. How can I access these collection variables in my posts?
Currently if I try to post postman will just hang for a while then give this error
Error: Script execution timed out.↵ at
ContextifyScript.Script.runInContext (vm.js:53:29)
If I use an environment variable or just type in a value it works fine.
Also, you need to make sure to save the request to the belonging collection before you can use it!
It turns out {{varName}} does work. The problem was in my pre-request script. The API I was connecting to requires a checksum on the body so it pre-processes the variables in the body, but it was not setup to handle collection variables. This was causing postman to fail. User error.

Postman API -how to pass environment variable to another request jason body

I have create global variable. Set it as Test as env variaable corresponding quote id were stored in the CreateGLVar
pm.test("Status code is 200", function () {
pm.response.to.have.status(200);});
var jsonData = pm.response.json();
pm.environment.set("CreateGLVar",jsonData.result.quoteID);
script for storing the value in Env variable
May i know how i can use value which is stored in the CreateGLVar for the below script. how i can the quote id from first request from global variable and insert dynamically in the second request( shown below) .
get quote id
enter image description here
Postman uses double curly braces to insert variables, which can also be used in raw request bodies.
In your specific case you can use:
"quoteID": "{{quoteIdVariable}}"
I am using the Postman Chrome extension Version 5.3.1, and this works for me.
Edit: Now that the Chrome extension has been depricated, this still works with the Postman Desktop app
Thanks Aaron.
I got the success when i used the "quoteID": "{{quoteIdVariable}}" in my bind API.my 2 API are working fine when i executed individually.
But I got issue when i executed API's as collection( Quote and Bind API). What i missing here if i executed as collection.
Failed

What are the "local" variables in Postman?

Postman's documentation leaves a lot to be desired. In their Variables page they say:
The following scopes are available to you:
Global
Environment
Local
Data
There's information about the Global and Environment scopes, and I believe the "Data" scope is the data from a collection run. But what are the "local" variables?
Because I'd love to have a variable that is calculated on the fly, used for the request, and then discarded. Both global and environment variables are persistent.
According to the Postman Quick Reference Guide local variables are only available within the request (or collection run) that has set them. So they are used for the request or collection run and then discarded.
When to use:
passing data from the pre-request script to the request or tests or between requests.
The behavior is a bit different in Postman vs Collection Runner / Newman, so make sure you understand how they work before using!
Setting
pm.variables.set('myVariable', MY_VALUE);
Getting
pm.variables.get('myVariable', MY_VALUE);
Removing
Local variables are automatically removed once the tests have been executed / collection run finished.
Local variables are the one you use in your Tests part.
You may even use the 'let' declaration as it is coded in javascript ...
ie:
let jsonData;
jsonData = JSON.parse(responseBody);
or use var for declaration.
var jsonData = JSON.parse(responseBody);
Though, you can erase globals on the fly using
pm.environment/global.unset(<variable>)
see here for details

URL encode Postman variable?

I use Postman for REST API testing and parametrize tests with global variables.
I should put a phone number into GET request: /path/get?phone={{phone}} but leading + sign in the phone number is interpreted as a space.
What is the syntax to URL encode global variables in Postman? Is it possible to run JS encodeURIComponent() on variable in URL?
I am late but still worth it:
Just highlight and right click the part of url you want to encode. Select encodeURIComponent
That's it.
Use the Pre-request scripts (it's next to body) for this:
var encoded = encodeURIComponent({{phone number}});
or
var encoded = encodeURIComponent(pm.environment.get("phone number"));
and to proceed, use:
pm.environment.set("encoded phone number", encoded);
And set your URL to /path/get?phone={{encoded phone number}}
Just a shortcut to Mohhamad Hasham' answer.
You can encode and decode direct in the Params Value field:
The trick is to get your environment variable in the pre-request script and then set it after encoding it
var encoded = encodeURIComponent(pm.environment.get("phone"));
pm.environment.set("encoded phone number", encoded);
This will work as well:
var encoded = encodeURIComponent(pm.request.url.query.get("phone"));
pm.request.url.query.remove("phone");
pm.request.url.query.insert("phone", encoded);
I came across this question looking for an answer to a similar question. For me, the variable was a JSON object. The endpoint I needed to hit was expecting an object list as a query parameter and I have no way to change that to be the request body.
As much as some of the answers helped, I ended up coming up with a combined solution. Also, some of the code given in other answers is outdated as Postman has updated their API over the years, so this uses methods that work on 7.22.1.
pm.environment.set("basicJSON", '[{"key1":"value1","key2":"value2"},{"key1":"value1","key2":"value2"}]')
var encoded = encodedURIComponent(pm.environment.get("basicJSON"))
pm.environment.set("encodedJSON", encoded)
This solution requires that both basicJSON and encodedJSON exist as environment variables. But what was important for me was the ease of editing the object. I didn't want to have to decode/encode constantly to change values, and I didn't want to have to open the environment variables dialogue. Also, it's important to note the single-quotes around the object. Excluding them or using double-quotes would cause Postman to send something like "[object Object]" which is useless to an endpoint expecting actual JSON.
I had similar problem with braces { and } in query parameter.
By turning off the following setting it started working for me.
For the postman version 9.28.4 ==>
You can use 2 methods:
By selecting the part of the url in url bar -> right click -> EncodeURLComponent. (screenshot attached)
You can also use "pre-request script" tab of postman and write the script for the variable manually. (screenshot attached)
The problem with right-click => Encode URI Component is that it destroys the raw value of that parameter. You can use the following pre-request script to overcome this (which also works for cases where you have disabled that param):
// queryParam is of type https://www.postmanlabs.com/postman-collection/QueryParam.html
if ((queryParam = pm.request.url.query.one("name_of_your_query_param")) !== undefined
&& queryParam.disabled !== true) {
queryParam.value = encodeURIComponent(queryParam.value);
}
Click the Params button to open the data editor for URL parameters. When you add key-value pairs, Postman combines everything in the query string above. If your URL already has parameters - for example, if you are pasting a URL from some other source. Postman splits the URL into pairs automatically.
https://www.getpostman.com/docs/v6/postman/sending_api_requests/requests
POSTMAN's documentation on building requests in the section "sending parameters" is helpful here. You can encode path data by simply encoding the URL with a colon, listing the key name of the encoded element, and then a new section will appear below the query parameters allowing you to customize values and add a description, just as we do with query params. Here's an example of encoding the URL for a GET request:
https://somesite-api-endpoint/:record/get
And here's what the display looks like after you add path data. Any value you add in the path variables section will automagically update the URL with your data.