Postman- How to save token value from Header Authorization - postman

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

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

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

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

Pass dynamic value to url in Postman

I have 2 requests
1st Request
After did my first request, I get the response where I can parse for a taskId
In my test tab, I will then parse and store it like this
let taskId = pm.response.json().body.result[0].data.task
console.log(taskId)
I can see taskId printing in my console as 938
2nd Request
I require making a GET with this dynamic URL with the taskId that I got from the first one
http://localhost:3000/fortinet/monitor/{{taskId}}
So I set the above URL , set the HTTP verb to GET
in my Pre-request Script tab, I did this
let taskId = pm.globals.get("taskId")
Result
ReferenceError: taskId is not defined
Image Result
How can I debug this further?
The most suggested way is to use :key as in
http://localhost:3000/fortinet/monitor/:taskId
See the colon before taskId. The reason being, URI values sometimes many not be environment dependent. So, based on the usecase, you can use like I said or {{taskId}}
You have to set variable, but you are doing it wrong.
try this:
pm.globals.set("taskID", pm.response.json().body.result[0].data.task)
more you can read here:
https://learning.postman.com/docs/postman/variables-and-environments/variables/
Please note, that URL which ends with resource identified like https://example.com/:pathVariable.xml or https://example.com/:pathVariable.json will not work.
You can go with https://example.com/:pathVariable with Accept: application/json header.
For passing dynamic value, first you have to set it in environment or global variable in Tests tab because tests runs after request and you will get response value after request sent, but because you get response in json you have to first parse it, so what you can write in Tests tab is as follows:
var jsonData = JSON.parse(responseBody);
postman.setEnvironmentVariable("taskId", jsonData.token); // OR
postman.setGlobalVariable("taskId", jsonData.token);
Then you can use taskId as {{taskId}} wherever you want in url parameters or in request body or form data wherever.
If you want to know in detail how to extract data from response and chain it to request then you can go to this postman's official blog post which is written by Abhinav Asthana CEO and Co Founder of Postman Company.