How to use environment variables for GET method in POSTMAN Tool? - postman

how can I use environment variables for get method in postman, I have customer id's with me but I need to send different customer id's n check the response, but I want to send customer ID's through data driven in postman tool

Imagine there is a customerId in env variables. To send this value in body or as param, just replace the static value with {{customerId}}.
usage:
To update the variable, imagine we have the following response:
{
"success": true,
"data": {
"id": "1234"
}
}
in the test tab update it this way:
var data = JSON.parse(responseBody);
if(data && data.data && data.data.id){
pm.environment.set('customerId', data.data.id)
}

Related

To validate a response item is an instance of a collection variable where the variable is an array in postman

How can I validate a response item is an instance of a collection variable where the collection variable is an array in postman?
Here first I'm making an array from a response from a GET request.
let arr = [];
for (item of response.books) {
arr.push(item.isbn);
}
pm.collectionVariables.set("Books_ISBN", arr);
console.log(arr);
Now I want to evaluate a response data of a POST request with the "Books_ISBN" collection variable.
My POST request response is this
{
"books": [
{
"isbn": "9781449325862"
}
]
}
I'm trying to do that like this but it is showing me error.
var response = JSON.parse(responseBody);
pm.test(pm.expect(response.books[0].isbn).to.be.an.instanceof(Books_ISBN));
Postman uses the Chaijs assertion library internally. to.be.an.instanceof checks if the type is an Array. You want to use the oneOf method(Docs) like this:
const Books_ISBN = pm.variables.get("Books_ISBN");
pm.test("my test", () => {
pm.expect(response.books[0].isbn).to.be.oneOf(Books_ISBN);
});
You also maybe want to look at the postman documentation for writing tests and the documentation on how to use variables in scripts.
Save array, object to as a varible, you should stringify first
pm.collectionVariables.set("Books_ISBN", JSON.stringify(arr));
Variable is not existed in script, you have to get it first, don't forget to parse.
let Books_ISBN = JSON.parse(pm.collectionVariables.get("Books_ISBN"));
pm.test("my test", () => {
pm.expect(response.books[0].isbn).to.be.oneOf(Books_ISBN);
});

Postman parameterized tests with actual values and expected errors for same request

I have request with number of tests cases, same endpoint, different actual values, different expected error messages.
I would like to create parameterized request sending particular value and check particular error message from list with all of the cases.
Request body:
{
"username": "{{username}}",
"password": "{{password}}",
...
}
Response:
{
"error_message": "{{error_message}}",
"error_code": "{{error_code}}"
}
Error message changes due to different cases:
Missed username
Missed password
Incorrect password or username
etc
Now, I have separate request on each case.
Question:
Is there way have 1 request with set of different values, checking
particular error messages/codes?
Create a csv:
username,password,error_message,error_code
username1,password1,errormessage1,errorcode1
username1,password1,errormessage1,errorcode1
Now use this as data file in collection runner or newman.
variable name is same as the column name and, for each iteration you will have corresponding row-column value as the variable value. Eg for iteration1 username will be username1
. As danny mentioned postman has a really rich documentation that you can make use of
https://learning.postman.com/docs/running-collections/working-with-data-files/
Adding another answer on how to run data driven from same request:
Create a environment variable called "csv" and copy the below content and paste it as value:
username,password,error_message,error_code
username1,password1,errormessage1,errorcode1
username1,password1,errormessage1,errorcode1
Now in pr-request add :
if (!pm.variables.get("index")) {
const parse = require('csv-parse/lib/sync')
//Environmental variable where we copy-pasted the csv content
const input = pm.environment.get("csv");
const records = parse(input, {
columns: true,
skip_empty_lines: true
})
pm.variables.set("index", 0)
pm.variables.set("records", records)
}
records = pm.variables.get("records")
index = pm.variables.get("index")
if (index !== records.length) {
for (let i of Object.entries(records[index])) {
pm.variables.set(i[0], i[1])
}
pm.variables.set("index", ++index)
pm.variables.get("index")===records.length?null:postman.setNextRequest(pm.info.requestName)
}
Now you can run data driven for that one particular request:
Eg collection:
https://www.getpostman.com/collections/eb144d613b7becb22482
use the same data as environment variable content , now run the collection using collection runner or newman
Output

How do I save the response body from one request and use it in another request with some changes in Postman

I have a GET request to OKTA to retrieve some information that uses some variables etc. It returns a body. I have a second request of type PUT where I manually paste the BODY and make a change to one variable. I am trying to determine if I can remove the manual process of pasting in the response body from the 1st GET request onto the second PUT request.
As an example, I have a URL:
GET https://{{myurl}}/api/v1/apps/{{instanceid}}
This returns some dyanmic JSON data in the payload like so
"blah":{ some more blah
},
"signOn": {
"defaultRelayState": null,
"ssoAcsUrlOverride": ""
"audienceOverride": null,
"recipientOverride": null
}
what I am hoping to do is:
PUT https://{{myurl}}/api/v1/apps/{{instanceid}}
{replay entire body from 1st request with the modification of
"ssoAcsUrlOverride": "{{some var that points to a new url}},
}
I have looked at some articles that show:
Using Tests to send a GET request with a static body and replaying that exact body. In this case, I am looking to modify a parameter not replay as=is
I tried this thread here (In postman, how do I take a response body and use it in a new request within Tests
postman-how-do-i-take-a-response-body-and-use-it-in-a-new-request-within-tes) but I get an error stating that responseBody is not defined
First of all, let's validate the JSON response first. Here is the valid JSON with some dummy data.
{
"blah": "some more blah",
"signOn": {
"defaultRelayState": "1",
"ssoAcsUrlOverride": "www.google.com",
"audienceOverride": "true",
"recipientOverride": "yes"
}
}
1) Save first request's response into a environment variable req_body as follows,
var jsonData = pm.response.json();
pm.environment.set("req_body", jsonData);
2) In the PUT request, take another environment variable replace_this_body in body.
3) Get the value of E'variable req_body we had set in the first request in Pre-request script. Then change the value of it and set current request's body variable.
var requestBody = pm.environment.get("req_body");
requestBody.signOn.ssoAcsUrlOverride = "https://www.getpostman.com";
pm.environment.set("replace_this_body", JSON.stringify(requestBody));
Finally, you will get updated request data into PUT request!

Postman - Use part of the response data from one test in another test

I require help to execute a postman test which requires a response output from another test. I have checked with various forums but a solution is not available for this particular scenario.
Example
Test 1 response:
{
"items": [
{
"email": "archer+qa01#gmail.com",
"DocumentName": "tc",
"type": "URL",
"url": "https://localhost:8443/user/terms?statusno=a5f2-eq2wd3ee45rrr"
}
]
}
Test 2:
I need to use only the a5f2-eq2wd3ee45rrr part of the response data from Test 1, this can be seen in the url value above. I need to use this value within Test 2
How can I make this work with Postman?
Not completely sure what the response data format is from the question but if it's a simple object with just the url property, you could use something simple like this:
var str = pm.response.json().url
pm.environment.set('value', str.split('=', 2)[1])
This will then set the value you need to a variable, for you to use in the next request using with the {{value}} syntax in a POST request body or by using pm.environment.get('value') in one of the test scripts.
Edit:
If the url property is in an array, you could loop through these and extract the value that way. This would set the variable but if you have more than 1 url property in the array it would set the last one it found.
_.each(pm.response.json(), (arrItem) => {
pm.environment.set('value', arrItem[0].url.split('=', 2)[1])
})
If you get JSON response and then send JSON in body, I would do the following:
1) In test script(javascript):
var JsonBody = pm.response.json();
var strToParse = JsonBody.url;
var value = strToParse.slice(indexOf("?status=")+"?status=".length);//parse string
//manually but you can google for a better solutions.
pm.environment.get("varName" , value)
2) You can use it! In scripts like: pm.environment.get("varName"), and everywhere else using {{varName}}

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.