How can we access dynamic variable {{$guid}} inside pre request in postman? - postman

I can access guid in url or body like {{$guid}} but same doesn't work inside pre-request script.

actually uuid.v4 represent guid in postman
let uuid = require('uuid');
let guid = uuid.v4(); //you can use this variable in wherever you need to use guid in
//pre-request script
console.log(guid);

Related

Postman- How to save token value from Header Authorization

I have to create a series of GET - POST-GET request over Postman.
Here are the steps I am trying to implement:
1) GET - with base64 encoded authorization : through this I will get a token
2) POST - using the token received in Step1.
Now I want to know how can I save the token I am getting from step1 into an environment variable and further call the environment variable in step2.
Please refer to the Image to understand how I am receiving the token from step 1.
Below is how I am trying to save the variable in Tests,(not sure if this is correct)
var jsonData = JSON.parse(Headers);
pm.setEnvironmentVariable("token",jsonData.message.token);
As the reference looks like you're trying to get something from the response body, I'm assuming it looks something like this:
{
"message": {
"token": "qwerty123456"
}
}
In the script, you would use something like this:
var jsonData = pm.response.json();
pm.environment.set("token", jsonData.message.token);
One image, thousand words
Get global variable: {{token}}

How to set basic authorization from environment variable in postman?

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.

Postman and setting up a variable in the body of x-www-form-urlencoded request

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.

Create unique body request in postman for API-test

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.

Retrieve variable value from API response( in xml format) and set it to environment variable in postman

I am testing API in Postman.
I want to fetch variable from postman response which is in XML format and set
that values as the environment variable.
My postman request response is like below.
<bmi version="2.0">
<job id="2031012"></job>
</bmi>
Here BMI and JOB are tags
I want the value of ID to set an environment variable and use it for another
api test as an input parameter.
I use following code in the Test scripts
tests["Status code is 200"] = responseCode.code === 200;
tests["Body matches string"] = responseBody.has("id");
var responseJson = xml2Json(responseBody);
console.log(responseJson);
postman.setEnvironmentVariable("id",responseJson.id);{code'enter code here'}
There is a blog on the postman website showing how to do this, Extracting data from responses and chaining requests
It looks like you are mostly there and just need to retrieve the value, something along the lines of
postman.setEnvironmentVariable("id",responseJson.bmi.job.id);