I am trying to automate a task that adds a field to the request body in my PUT request.
Basically the first thing i do is a GET request to see what the request body looks like:
{
“jobName-0”: “/uscm-claims-training/job/boley-dynamic-secrets”,
“isTag-0”: “false”,
“triggers-0”: “add;prmerged;push;manual;delete;”,
“token-0”: “”,
“buildParameters-0”: “”,
“branchRegex-0”: “”,
“pathRegex-0”: “”
}
Now that i have that information I want to add a field (see below) while retaining all other values from the GET request so I want to add basically: this field: "jenkinsServer-0": “USCM-CLAIMS-TRAINING”,
Is there a way to add a field to this? Each GET request has different values so I can’t just use the same body for each project.
All you need to do is write the following in the test script:
// Get the response as JSON
let response = pm.response.json();
// Add the key to the object
response["jenkinsServer-0"] = “USCM-CLAIMS-TRAINING”;
// Set the whole response to a variable after stringifying it
pm.globals.set('jobResponse', JSON.stringify(response));
Now, in the request body of your PUT request, just write the following:
{{jobResponse}}
This should help you out.
Let me know if you have any doubts.
Thanks for the response sivcan that is very helpful.
On the line below if i wanted to replace “USCM-CLAIMS-TRAINING” with a variable i am using in my GET URL: called {{projectKey}} is there a way to do so? It does not seem to accept {{projectKey}}
One more question if you don’t mind. I’m not very proficient at Javascript, but i’ve got some data being returned with multiple jobNames as seen below:
Is there an easy way I can add the jenkinsServer property after each jobName? This one has 3, but some projectKeys have more than 20.
You can build an array and achieve that.
The script around that would be:
// We need the latest lodash, so importing it.
_ = require('lodash');
// Get the response as JSON
let response = pm.response.json();
// Based on the index of the array, we'll assign the value
// Right now, all three values are same but I am assuming
// you might want to change that too, you can either hard code that
// or build a logic around that.
// Number of jobNames
let jobNameCount = _.countBy(_.keys(response), (k) => k.includes('jobName')).true,
// Fill an array with length of jobNameCount and all the values as 'USCM-CLAIMS-TRAINING'
uscms = _.fill(Array(jobNameCount), 'USCM-CLAIMS-TRAINING'),
// This will be like this -> uscms = ['USCM-CLAIMS-TRAINING', 'USCM-CLAIMS-TRAINING', 'USCM-CLAIMS-TRAINING']
// We'll populate this object, so declaring it here
jenkinsServers = {};
_.forEach(uscms, (uscm, index) => {
jenkinsServers[`jenkinsServer-${index}`] = uscm;
});
// Add all the new jenkins servers to the response object
response = _.assign(response, jenkinsServers);
// Set the whole response to a variable after stringifying it
pm.globals.set('jobResponse', JSON.stringify(response));
I haven’t tested the script, but I think it should work.