How to create a collection variable from response in postman - postman

Selecting a value and right-clicking enables me to save it as a Global variable.
But there is no option to save it as a collection variable.
In the environments section as well. I can see Globals but my collection is not available.
But as I go through blogs/ articles online I can see some variables that are scoped to a collection.
Can I know a way to achieve this?

Tests tab is all you need
Considering the Stackoverflow GetUser API for Reference.
NOTE: The below-shown response is a part of the original response.
Response:
{
"items": [
{
"user_type": "registered",
"user_id": 12345678,
}
]
}
In the above response let's say we need user_type, and user_id in another API's URL / body / headers.
Before accessing we need to store these variables after receiving the response. This can be done in the Tests tab in postman request.
const jsonData = JSON.parse(responseBody);
const userType = jsonData?.items?.[0]?.user_type;
const userId = jsonData?.items?.[0]?.user_id;
if(userType){
pm.collectionVariables.set("userType",userType)
}
if(userId){
pm.collectionVariables.set("userId", userId)
}
Points to Note:
Postman tests are written in Javascript.
Optional chaining in line 2,3 is to avoid console errors. Possible Scenario: When API fails and returns an error response.
The IF Statements are to avoid null values in case of an Error Response. If statements are not mandatory. In fact without using if statements you will get to know clearly that something went wrong.
How to use collection variables
Once you make a request with the above tests. Postman IntelliSense suggests available collection variables. ( Refer to the image attached )
We are sending the body as a raw JSON in this Test Endpoint. Note that userType is surrounded by double quotes "" whereas userId is not. ( JSON syntax )

Related

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

Getting unexpected '#' error under postman Test tab

I am a learner in postman and do not have much experience in programming/scripting.
Here the issue.
Used POST api request - For getting the access token;
Used POST api request - To create an account;
Used POST api request - To cancel an account with CancellationReason
Need to crosscheck the cancellation details (some fields like cancellationReason) in web application.
In order to avoid manually check, i have used GET request api like below
by passing all the mapped fields (as per web application) in the GET request end url
(i.e. by sending the details in fetch_xml query parameter in the end url) in order to get those required fields returned.
Now i got a successful response with status code.
After that i want to compare the fetched values (from the response body) ... VS.... to the data i passed while cancelling the account (i.e. in POST api request - To cancel the account) and make sure both are same.
After that under Test tab - I have updated query like below, however it throwing an Unexpected '#' error (as the below query contains '#' in middle of the field name)
tests["Verify the CancellationReason matches"] = pm.expect(data._usr_cancellationReason_value#OData.Community.Display.V1.FormattedValue).to.eql("CancellationReason");
Can someone please help me to understand whether i should remove this #symbol or should replace with something else ?
Here is the response body:
{
"#odata.context": "https://hfrdcompanies.integrationdev01.crm3.cs.com/api/data/v9.1/$metadata#hfrd_workorders(_usr_cancellationchannel_value,usr_CancellationChannel,_usr_workorderreason_value,usr_WorkOrderReason,hfrd_workorderid,usr_cancellationuser,_usr_cancellationsource_value,usr_CancellationSource,hfrd_name,usr_CancellationChannel(),usr_AccountReason(),usr_CancellationSource())",
"value": [
{
"#odata.etag": "W/\"2345234523\"",
"_usr_cancellationchannel_value#OData.Community.Display.V1.FormattedValue": "Mobile App",
"_usr_cancellationchannel_value": "acefsdflin89-f9jf07-e969f1-a245nk11-00jnfnafn9799fc2a",
"_usr_Accountreason_value#OData.Community.Display.V1.FormattedValue": "Customer Inactive",
"_usr_Accountreason_value": "bde1234522-d45662-e2711-a84561-0007354a2d5c2a",
"hfrd_Accountid": "89025sf3-c668f-e7811-a4331-00asdhh3ab9bd1c",
"usr_cancellationuser": "Testuser08 ABC",
"_usr_cancellationsource_value#OData.Community.Display.V1.FormattedValue": "MOBILE",
"_usr_cancellationsource_value": "6c23asdf-c562-e411-a841-00asdfa",
"hfrd_name": "FP-WK-1000000642"
}
]
}
I want to validate the bold row

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.