Undefined variable in postman request - postman

I have a get request with Tests script as below
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("var1", jsonData.var1);
postman.setEnvironmentVariable("var2", jsonData.var2);
However response for the request may or may not include all values eg.
response1
{
"var1": "value1",
"var2": "value2"
}
response2
{
"var2": "value2"
}
I use above data in next Put request. Body of the Put request is like below
{
"var1": "{{var1}}",
"var2": "{{var2}}"
}
The issue I am facing is if previous Get request did not have a value for a property (as in response2) then {{var1}} (i.e. variable name) is getting stored in the database (mysql). I tried removing double quotes around variable in the Put request but that gives me
invalid character '{' looking for beginning of object key string "
error
Can you please suggest best solution for the situation.
Thanks

Related

How to extract the values from the response body in postman and store as variable

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);

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- 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 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}}