How to build a Postman url query with Pre-request Scripts - postman

I'm trying to use a pre-request script to build out a request object based on data pulled from a CSV file. The problem is that the request seems to be set in stone prior to the pre-request script being run. That would seem to make this a mid-request script almost rather than a pre-request.
My code is as follows:
if(ipList === undefined) ipList = "1.2.3.4,2.3.4.5,123.234.345.465";
let ips = ipList.split(',');
let queryArray = [];
for( i=0; i<ips.length; i++){
queryArray.push({ "key": "ip", "value": ips[i] });
}
console.log(queryArray);
pm.request.url.query = queryArray;
console.log(pm.request);
When I hardcode a url query variable in the request to equal 4.3.2.1, the pm.response.url object like this:
pm.request.url.query[0] = {key:"ip", value:"4.3.2.1"}
Note that the url.query[0] part of the object matches the parameter in the actual get request.
When I change the value of pm.request.url.query to equal the new query array, however as you can see here, the query array is set correctly, but the parameters are not appended to the request URL.
So unless I'm doing something wrong, it appears that the request is immutable even to the pre-request scripts.
So my question is this:
Is there a way to modify the url params of a request prior to making the request?
BTW: I know that is might seem odd to have multiple params with the same key in a query, but that's the way this API works and hard coding multiple ip addresses in the query works just fine.

You could just assign a new value to pm.request.url.
Here I had some query params already in the URL, which I had to edit:
const urlSplit = request.url.split('?');
const paramsString = urlSplit[1]; // the second part actually represents the query string we need to modify
const eachParamArray = paramsString.split('&');
let params = {};
eachParamArray.forEach((param) => {
const key = param.split('=')[0];
const value = param.split('=')[1];
Object.assign(params, {[key]: value});
});
params.bla = params.bla + 'foobar';
newQueryString = Object.keys(params).map(key => key + '=' + params[key]).join('&');
pm.request.url = urlSplit[0] + '?' + newQueryString;
In the end, I just constructed a new URL, using the first part of the previous one & the query string with the edited bla parameter.

This seemed to work for me--it didn't change what the UI shows the query string is, but it changed what the actual request was (looking at the console log)
pm.request.url.addQueryParams(["a=1", "b=2"])
pm.request.url.query.remove("b")
I have some parameters called "script_loginAs" etc... named such that people on my team know the parameter is evaluated and not sent.

Related

Adding a cookie to DocumentRequest

Using AngleSharp v 0.9.9, I'm loading a page with OpenAsync which sets a bunch of cookies, something like:
var configuration = Configuration.Default.WithHttpClientRequester().WithCookies();
var currentContext = BrowsingContext.New(configuration);
// ....
var doc = context.OpenAsync(url, token);
This works fine and I can see the cookies have been set. For example, I can do this:
var cookieProvider = currentContext.Configuration.Services.OfType<ICookieProvider>().First() as MemoryCookieProvider;
And examine it in the debugger and see the cookies in there (for domain=.share.state.nm.us)
Then I need to submit a post:
var request = new DocumentRequest(postUrl);
request.Method = HttpMethod.Post;
request.Headers["Content-Type"] = "application/x-www-form-urlencoded";
request.Headers["User-Agent"] = userAgent;
//...
Which eventually gets submitted:
var download = loader.DownloadAsync(request);
And I can see (using Fiddler) that it's submitting the cookies from the cookieProvider.
However, I need to add a cookie (and possible change the value in another) and no matter what I try, it doesn't seem to include it. For example, I do this:
cookieProvider.Container.Add(new System.Net.Cookie()
{
Domain = ".share.state.nm.us",
Name = "psback",
Value = "somevalue",
Path = "/"
});
And again I can examine the cookieProvider in the debugger and see the cookie I set. But when I actually submit the request and look in fiddler, the new cookie isn't included.
This seems like it should be really simple, what is the correct way to set a new cookie and have it included in subsequent requests?
I think there are two potential ways to solve this.
either use document.Cookie for setting a new cookie (would require an active document that already is at the desired domain) or
Use a Filter for getting / manipulating the request before its send. This let's you really just change the used cookie container before actually submitting.
The Filter is set in the DefaultLoader configuration. See https://github.com/AngleSharp/AngleSharp/blob/master/src/AngleSharp/ConfigurationExtensions.cs#L152.

Postman accessing the stored results in the database leveldb

So I have a set of results in Postman from a runner on a collection using some data file for iterations - I have the stored data from the runner in the Postman app on Linux, but I want to know how I can get hold of the data. There seems to be a database hidden away in the ~/.config directory (/Desktop/file__0.indexeddb.leveldb) - that looks like it has the data from the results there.
Is there anyway that I can get hold of the raw data - I want to be able to save the results from the database and not faff around with running newman or hacking a server to post the results and then save, I already have 20000 results in a collection. I want to be able to get the responseData from each post and save it to a file - I will not execute the posts again, I need to just work out a way
I've tried KeyLord, FastNoSQL (this crashes), levelDBViewer(Jar), but not having any luck here.
Any suggestions?
inline 25024 of runner.js a simple yet hack for small numbers of results I can do the following
RunnerResultsRequestListItem = __WEBPACK_IMPORTED_MODULE_2_pure_render_decorator___default()(_class = class RunnerResultsRequestListItem extends __WEBPACK_IMPORTED_MODULE_0_react__["Component"] {
constructor(props) {
super(props);
var text = props.request.response.body,
blob = new Blob([text], { type: 'text/plain' }),
anchor = document.createElement('a');
anchor.download = props.request.ref + ".txt";
anchor.href = (window.webkitURL || window.URL).createObjectURL(blob);
anchor.dataset.downloadurl = ['text/plain', anchor.download, anchor.href].join(':');
anchor.click();
it allows me to save but obviously I have to click save for now, anyone know how to automate the saving part - please add something here!

Store Data from Postman request in variables to use in tests

Im currently trying to get used to POSTMAN and i was wondering if there is a way to store variables from my request JSON Body via Pre Request in some environment variable so ican resuse it in the tests for response value cheks
This is how my json File might look like
{
"text" : "myText",
"attachments": {
"text": "myText2",
"anotherText" : "myText3"
}
So i want to get all Values, store them in a variable before sending my request, and then test if they match the expected value in my response
(example: myText2 gets mapped to green, myText3 gets mapped to red and so on)
That would make it possible to write one test for several request
Thanks a lot!
You can write the following in your script:
let body = JSON.parse(pm.request.body);
_.forEach(body, (value, key) => pm.environment.set(key, JSON.stringify(value)));
This will set each key and it's associated value as an environment variables.
Note you'll need to JSON.parse the value in the test script before using it for testing.
For eg in your test script you'll need to do something like this:
let attachments = JSON.parse(pm.environment.get('attachments'));
pm.test('All attachments are of correct value', function () {
// ...write your test here using the `attachments` variable
});

Get an automatic list of ExpressJS params

I am trying to get a list of all of the parameters in a path from a get request.
app.get('/*',function(req, res) {
console.log(req.params[0]);
res.send('testing');
});
However, when I go to the url localhost/test/test1, the params[0] object is 'test/test1'.
Is there any way to make it split the url in to params without doing '/*/*'. I want to be able to put in as many values as I need without worrying about naming or counting them.
The ideal input/output would be:
URL: localhost/arg1/arg2/arg3
params[0] = 'arg1'
params[1] = 'arg2'
params[2] = 'arg3'
Thanks.
A simple split will work:
var splitParams = params[0].split('/');

Add cookie for Xdebug in Paw

I debug my API using Xdebug and PHPStorm's debugging features. For this to work, the client needs a cookie named XDEBUG_SESSION.
When using Postman, I used to use a Chrome extension to add this cookie, and Postman's cookie interception feature to get this to work in Postman (since it's a sandboxed app).
However, I cannot create cookies in Paw. So, as a workaround, I modified the API response cookie to have the key as XDEBUG_SESSION and value as PHPSTORM, and debugging worked fine. However, this is not ideal as I would also like to set the expiry date to something far in the future (which I can't in Paw).
So, my questions are:
Is there a way to add custom cookies in Paw?
If not, is there a way to to edit the expiry date for an existing cookie (considering that name, value, domain and path are editable)?
Are there any other alternatives to achieve my objective?
I just managed to achieve this exact thing to debug my APIs with Paw (2.1.1).
You just have to Add a Header with the name Cookie and a value of Cookies picked from the dropdown that will appear. You then have to insert a Cookie named XDEBUG_SESSION with a value of PHPSTORM inside the Cookies value of the header just created.
To be more clear, you can see it in the screenshot below:
I messed around with it to see if I could create an extension. I wasn't able to, and the below does not work but thought I'd share in case anyone knows the missing pieces.
First off, there is no extension category (generator, dynamic value, importer) that this functionality falls into. I tried to make use of the dynamic value category but was unsuccessful:
CookieInjector = function(key, value) {
this.key = "XDEBUG_SESSION";
this.value = "PHPSTORM";
this.evaluate = function () {
var f = function (x,y) {
document.cookie=this.key+"="+this.value;
return true;
}
return f(this.key, this.value);
}
// Title function: takes no params, should return the string to display as
// the Dynamic Value title
this.title = function() {
return "Cookie"
}
// Text function: takes no params, should return the string to display as
// the Dynamic Value text
this.text = function() {
return this.key+"="+this.value;
}
}
// Extension Identifier (as a reverse domain name)
CookieInjector.identifier = "com.luckymarmot.PawExtensions.CookieInjector";
// Extension Name
CookieInjector.title = "Inject Cookie Into Cookie Jar";
// Dynamic Value Inputs
CookieInjector.inputs = [
DynamicValueInput("key", "Key", "String"),
DynamicValueInput("value", "Value", "String")
]
// Register this new Extension
registerDynamicValueClass(CookieInjector);
The main thing stopping this from working is I'm not sure how the request is built in PAW and not sure how to attach the cookie. I've looked through the documentation here: https://luckymarmot.com/paw/doc/Extensions/Reference/Reference, and can't find what I need.