How to get to request parameters in Postman? - javascript

I'm writing tests for Postman which in general works pretty easily. However, I now want to access some of the data of the request, a query parameter to be exact.
You can access the request URL through the "request.url" object which returns a String. Is there an easy way in Postman to parse this URL string to access the query parameter(s)?

The pm.request.url.query.all() array holds all query params as objects.
To get the parameters as a dictionary you can use:
var query = {};
pm.request.url.query.all().forEach((param) => { query[param.key] = param.value});

I have been looking to access the request params for writing tests (in POSTMAN). I ended up parsing the request.url which is available in POSTMAN.
const paramsString = request.url.split('?')[1];
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
console.log(params); // this is object with request params as key value pairs
edit: Added Github Gist

If you want to extract the query string in URL encoded format without parsing it. Here is how to do it:
pm.request.url.getQueryString() // example output: foo=1&bar=2&baz=3

pm.request.url.query returns PropertyList of QueryParam objects. You can get one parameter pm.request.url.query.get() or all pm.request.url.query.all() for example. See PropertyList methods.

It's pretty simple - to access YOUR_PARAM value use
pm.request.url.query.toObject().YOUR_PARAM

Below one for postman 8.7 & up
var ref = pm.request.url.query.get('your-param-name');

I don't think there's any out of box property available in Postman request object for query parameter(s).
Currently four properties are associated with 'Request' object:
data {object} - this is a dictionary of form data for the request. (request.data[“key”]==”value”) headers {object} - this is a dictionary of headers for the request (request.headers[“key”]==”value”) method {string} - GET/POST/PUT etc.
url {string} - the url for the request.
Source: https://www.getpostman.com/docs/sandbox

Bit late to the party here, but I've been using the following to get an array of url query params, looping over them and building a key/value pair with those that are
// the message is made up of the order/filter etc params
// params need to be put into alphabetical order
var current_message = '';
var query_params = postman.__execution.request.url.query;
var struct_params = {};
// make a simple struct of key/value pairs
query_params.each(function(param){
// check if the key is not disabled
if( !param.disabled ) {
struct_params[ param.key ] = param.value;
}
});
so if my url is example.com then the array is empty and the structure has nothing, {}
if the url is example.com?foo=bar then the array contains
{
description: {},
disabled:false
key:"foo"
value:"bar"
}
and my structure ends up being { foo: 'bar' }
Toggling the checkbox next to the property updates the disabled property:

have a look in the console doing :
console.log(request);
it'll show you all you can get from request. Then you shall access the different parameters using request., ie. request.name if you want the test name.
If you want a particular element in the url, I'm afraid you'll have to use some coding to obtain it (sorry I'm a beginner in javascript)
Hope this helps
Alexandre

Older post, but I've gotten this to work:
For some reason the debugger sees pm.request.url.query as an array with the items you want, but as soon as you try to get an item from it, its always null. I.e. pm.request.url.query[0] (or .get(0)) will return null, despite the debugger showing it has something at 0.
I have no idea why, but for some reason, it is not at index 0, despite the debugger claiming it is. Instead, you need to filter the query first. Such as this:
var getParamFromQuery = function (key)
{
var x = pm.request.url.query;
var newArr = x.filter(function(item){
return item != null && item.key == key;
});
return newArr[0];
};
var getValueFromQuery = function (key)
{
return getParamFromQuery(key).value;
};
var paxid = getValueFromQuery("paxid");
getParamFromQuery returns the parameter with the fields for key, value and disabled. getValueFromQuery returns just the value.

Related

Query string with fetch javascript

I'm working on a project and i want to define url object that will be passed to fetch ex.
https://t1.testing.com/test/api/v1/blog?pagingindex=0&pagingresults=10
const url_object = {
url: `https://t1.testing.com/test/api/v1/blog`,
url_params: {
method: "POST",
pagingindex: 0,
pagingresults: 10
}
};
and when i call fetch(url_object.url, url_object.url_params) i get an error. How can i incorporate this into fetch? So i need to allow user to define method and query string that will be passed. Thanks in advance!
You can have your cake and eat it too -- easily convert dictionary style objects to query parameters with no fuss:
var url = new URL('https://example.com/');
url.search = new URLSearchParams({blah: 'lalala', rawr: 'arwrar'});
console.log(url.toString()); // https://example.com/?blah=lalala&rawr=arwrar
The object you have labeled url_params is described by the MDN documentation as:
An options object containing any custom settings that you want to apply to the request.
It then goes on to list the properties you can include there.
pagingindex and pagingresults are not among them.
The query string is part of the URL. If you want to put data there, then put it in the URL.
const url_object = {
url: `https://t1.testing.com/test/api/v1/blog?pagingindex=0&pagingresults=10`,
url_params: {
method: "POST"
}
};
You may wish to use the URL object to construct the URL (it will handle escaping for you).

How to store data in an array that is stored in a variable?

Following is my problem:
I am testing a system now, that has multiple ID's in every request. There are 2 ID's I want to store in an array and let them run again a response later.
Following is the Body I recieve
{
"id" = 1234;
"Name" = "Meier"
}
So, I store the ID normally with
var body = JSON.parse(responseBody);
postman.setEnvironmentVariable("ID", body.id);
with that I can store 1 ID in the variable, but can't put a second one in it. For that I would have to duplicate the request, set a second variable, change code everytime the needed cases are changed.
What I want to know now is: How can I store multiple ID's in a Environment Variable to compare them with a response at the end of the collection?
I'm not entirely familiar with postman, but if I'm understanding correctly and you want to store up the Id's from the response then you could use something like -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if(storedIds) {
storedIds.push(body.id)
} else {
storedIds = [body.id]
}
postman.setEnvironmentVariable("ID", storedIds);
Edit
From my own googling, it appears you cannot store arrays in environment variables in postman. Therefore you could try doing something like this -
var body = JSON.parse(responseBody);
var storedIds = postman.getEnvironmentVariable("ID");
if (storedIds) {
storedIds = storedIds.concat(',' + body.id)
} else {
storedIds = body.id
}
postman.setEnvironmentVariable("ID", storedIds);
Then when you want to read it back out to loop over it or whatever you want to do you can use
var idsArray = postman.getEnvironmentVariable("ID").split(',')
which will split the string up to give you an array.

Parsing a JSON object with Javascript, just won't work

I'm using this code to get a JSON file stored in the same folder.
var schedtotal = 0;
var requestURL11 = 'schedtotal.json';
var request11 = new XMLHttpRequest();
request11.open('GET', requestURL11);
request11.responseType = 'json';
request11.send();
request11.onload = function() {
window.superHeroes11 = request11.response;
populateHeader11(superHeroes11);
}
function populateHeader11(jsonObj) {
window.schedtotal = jsonObj.total;
console.log("populateHeader function has activated");
console.log(jsonObj);
}
The file looks like this:
{"total": 3}
It's valid JSON. I'm trying to extract the value of total using the same exact method that I've used successfully for all the other JSON parsings in the rest of the file (which I have not included here).
When populateHeader11 is called, it doesn't change schedtotal to equal total. It remains at its original setting of 0. The console log returns from the function as having activated and also returns the JSON file so I know it can access it at least.
I've tried changing .jsonObj.total to .jsonObj['total'] and it didn't change anything.
Previous times I've screwed around with this, it has sometimes returned an error saying it can't get 'total' from null. Now it just doesn't return anything in its current state. What is going on?
You need to parse the JSON string into an object before you try and access the total field.
var jsonString = "{\"total\": 3}";
var jsonObj = JSON.parse(jsonString);
console.log(jsonObj.total);

Json stringify then parse from URL

I seem to be having an issue in stringify'ing then pasing from a url object
I simply stringify my object and set the location (with angulars $location) like so
currentUrl = {"module1" : {"is" : true} }
$location.search(JSON.stringify(currentUrl));
So this parses to the url just fine, however when I try to grab it from the url i get this back
console.log($location.search());
---
Object {{"module1":{"is":true}}: true}
How do I parse this back into an object so I can use it? If I do
JSON.parse($location.search());
I get a syntax error. I maybe because of how search returns the object? I am a bit confused here, could use some help. Thanks!
So I put it in the url with
$location.search(JSON.stringify(currentUrl));
What are the steps I need to take to get it back into this form :
{"module1" : {"is" : true} }
Edit -
It just appears it's setting the json object as the key in the location like
{ "mystrigifiedobject": true }
Edit2 :
based off the first edit, I was able to solve it (assming it's set in the locations object key) like so :
currentUrl = $location.search();
currentUrl = JSON.parse(Object.keys(currentUrl));
console.log(currentUrl);
This just feels a little weird though, am I doing something wrong here?
$location.search() returns the parsed search items from the url path as an object. This means this kind of url:
?a=b&c=d
will result in this object:
{ a: 'b', c: 'd' }
When you call this function:
currentUrl = {"module1" : {"is" : true} }
$location.search(JSON.stringify(currentUrl));
your path will look like this:
?%7B%22module1%22:%7B%22is%22:true%7D%7D
and the parsed object returned from $location.search will look like this:
{{"module1":{"is":true}}: true}
not that this is an object with one entry and the key is your JSON
So what you need to do in order to get your object back is this:
var parsedObject = $location.search();
var yourObject = JSON.parse(Object.keys(parsedObject)[0]);
see this jsfiddle: http://jsfiddle.net/HB7LU/11633/
But please note: you should encode your string when putting it in a url:
$location.search(encodeURIComponent(JSON.stringify(currentUrl)));
$routeParams provides access to both routing template values and query string values (as a string).
function ctrl($routeParams) {
var yourValueAsString = $routeParams.yourKey;
}
function ctrl2($location) {
$location.search('yourKey', JSON.stringify(...));
}
A better alternative would be to switch to using the UI Router which deals with this better.

How to insert data, in key value pairs, into HTML

I have returned a form with some key value pairs populated. Depending on user interaction I want to insert some of them into my HTML. I have found some answers using AJAX but could not workout how to access the key value pairs via javascript. I do not want to use jquery yet as I want understand how javascript and the DOM works first. Below is an idea of what I want to do
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
while ($urls as $url) {
if (urlitem == $url->item) {
document.getElementById("urlanchor").innerHTML .= $url->urlanchor;
}
}
</script>
I know "$urls as $url" etc is PHP but I thought it was the easiest way to explain what I need to do.
I use PHP to generate the function call but I am unable to get it to display here it (pieces of code do not display)
Like so?
<script>
function changeanchor(urlitem) {
document.getElementById("urlanchor").innerHTML = "";
for (i in urls) {
var url = urls[i];
if (urlitem == url.item) {
document.getElementById("urlanchor").innerHTML += url.urlanchor;
}
}
</script>
urls was never defined so this code won't execute unless urls stores a bunch of url objects with those properties.
In order to create a url object that acts like the one you try to use, either use JSON to pipe it to the JavaScript or make an object:
var urls = [
{
'item': 100,
'urlanchor': 'foo'
}, {
'item': 200,
'urlanchor': 'bar'
}
];
are you asking about the setting key value pair data in a dome object then,
$('body').data('foo', 52);
link for help:-
http://api.jquery.com/data/

Categories

Resources