postman: save response on a global variable - postman

With PostMan, how can save the follow response:
[
{
"id": "6254c754-5a97-43fd-9b48-c428b9bd69e5",
"name": "fdsfds",
"description": "fdzf",
"type": 0,
"createDate": "2018-08-01T17:49:29.071+01:00",
"lastUpdateDate": "2018-08-01T17:49:29.071+01:00",
"lastUpdateUser": null,
"variables": null,
"instructions": null
}
]
on a variable? For example the id?
var jsonData = pm.response.json();
console.log(jsonData.id);
pm.globals.set("variable_key", jsonData.id);

to set the environment variable "authkey" from response
var obj = pm.response.json()["token"];
pm.environment.set("authkey", obj);

You can't save JS Objects directly in a global variable but you can use JSON library to convert your object to string and save, like the following code:
// create the JS Object
var obj = {
foo: "bar",
some_number: 91
}
// convert the obj to string and save in the globals
pm.globals.set("my_obj", JSON.stringify(obj));
// get obj from globals and parse to JS Object again
var obj_from_globals = JSON.parse(pm.globals.get("my_obj"));
// print int he console
console.log(obj_from_globals);
You should expect this in your console:

I think i resolve this with:
var jsonData = pm.response.json();
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
var seqDelete = jsonData[key].id;
console.log(seqDelete);
}
}
pm.globals.set("seqDelete", seqDelete);
This isn´t totally correct.
If i have multidimension array, this only gets one ID value

This is the response that I work with:
{id: "myId", version: "2.0", name: "test"…}
This is how I set the id value from the response into my global variable "appId":
var requestJson = JSON.parse(request.data);
console.log(requestJson)
postman.setGlobalVariable("appId", requestJson.id);
Result:

Related

How to properly set an API call in QML using XMLHttpRequest

I am building a small weather API as exercise to use QML and properly operate an API call using OpenWeather and you can see there a typical API response.
The problem I am having is that I can't get the API call to work. After setting a minimal example with some cities that you can see below, right next to the city it should appear the symbol of the weather, but it does not happen. The list of the icon can be found here. Source code of the MVE can be found here for completeness.
The error from the compiler: qrc:/main.qml:282: SyntaxError: JSON.parse: Parse error
This is what is happening
This is what is expected
Typical API JSON response can be found both here and below:
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "stations",
"main": {
"temp": 282.55,
"feels_like": 281.86,
"temp_min": 280.37,
"temp_max": 284.26,
"pressure": 1023,
"humidity": 100
},
"visibility": 16093,
"wind": {
"speed": 1.5,
"deg": 350
},
"clouds": {
"all": 1
},
"dt": 1560350645,
"sys": {
"type": 1,
"id": 5122,
"message": 0.0139,
"country": "US",
"sunrise": 1560343627,
"sunset": 1560396563
},
"timezone": -25200,
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
Below a snippet of code related to the API call:
main.qml
// Create the API getcondition to get JSON data of weather
function getCondition(location, index) {
var res
var url = "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}"
var doc = new XMLHttpRequest()
// parse JSON data and put code result into codeList
doc.onreadystatechange = function() {
if(doc.readyState === XMLHttpRequest.DONE) {
res = doc.responseText
// parse data
var obj = JSON.parse(res) // <-- Error Here
if(typeof(obj) == 'object') {
if(obj.hasOwnProperty('query')) {
var ch = onj.query.results.channel
var item = ch.item
codeList[index] = item.condition["code"]
}
}
}
}
doc.open('GET', url, true)
doc.send()
}
In order to solve this problem I consulted several sources, first of all : official documentation and the related function. I believe it is correctly set, but I added the reference for completeness.
Also I came across this one which explained how to simply apply XMLHttpRequest.
Also I dug more into the problem to find a solution and also consulted this one which also explained how to apply the JSON parsing function. But still something is not correct.
Thanks for pointing in the right direction for solving this problem.
Below the answer to my question. I was not reading properly the JSON file and after console logging the problem the solution is below. code was correct from beginning, only the response needed to be reviewed properly and in great detail being the JSON response a bit confusing:
function getCondition() {
var request = new XMLHttpRequest()
request.open('GET', 'http://api.openweathermap.org/data/2.5/weather?q=London&units=metric&appid=key', true);
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
if (request.status && request.status === 200) {
console.log("response", request.responseText)
var result = JSON.parse(request.responseText)
} else {
console.log("HTTP:", request.status, request.statusText)
}
}
}
request.send()
}
Hope that helps!
In your code, your url shows this: "api.openweathermap.org/data/2.5/weather?id={city id}&appid={your api key}". You need to replace {city id} and {your api key} with real values.
You can solve it by providing an actual city ID and API key in your request URL

Postman : How to retrieve a value of a variable inside an array (which is not available in the response body) to parameterize as a global variable

I'm trying to get a value of a variable inside an array to store it as a global variable for reuse on collection runner. The issue is this variable data is not exposed on any response data.
$scope.loadWorkAreasAndMenu = function (callback) {
$('.modal-backdrop').hide();
var workSpaceIdQs = GetParameterValues('WorkSpaceId');
var workspaceId = null;
if (workSpaceIdQs != undefined && workSpaceIdQs.trim().length != 0) {
workspaceId = workSpaceIdQs;
}
var jsonMenu = JSON.stringify({
slotToken: window.top.Token,
workspaceId: workspaceId,
viewPortType: currentViewport
});
var serviceData = {
serviceName: "GetWorkAreasAndMenu",
serviceInputs: LZString.compressToEncodedURIComponent(jsonMenu)
};
var config = {
headers: {
'Content-Type': "application/json"
}
};
I need to capture the variable "serviceInputs" but the issue is it is not exposed in any the response data. How we could retrieve this value during runtime execution itself ?

Extracting global variable value from brackets

I am sending a POST request, which I'm getting in the response an attribute named "value" that its value is a number with brackets. I need to use the number without the brackets for my next API request.
Here is what I get in the response of my request:
{
"additionalAttributes": {
"map": [
{
"key": "RESULT_IDS",
"value": "[26913648997439042205288611421953968843]"
}
]
}
Here is what I've updated in Tests tab of the request in order to save it as a global variable:
tests["Status code is 200"] = responseCode.code === 200;
if (responseCode.code === 200) {
try {
var campaign_data = JSON.parse(responseBody),
campaignValue = campaign_data.additionalAttributes.map[0].value;
} catch(e) {
console.log(e);
}
postman.setGlobalVariable("campaignValue",campaignValue);
}
Can you explain please how can I have the value 26913648997439042205288611421953968843 without the brackets saved into a global variable?
Many thanks.
You can use the integrated lodash lib of the Postman sandbox:
var campaignValueRaw = campaign_data.additionalAttributes.map[0].value;
var campaignValue = _.trimRight(_.trimLeft(campaignValueRaw, '[') , ']');

Fetch ID value from given JSON

How can I get the value of id from given sample below..
{ "photoId": { "id": "CAoSLEFGMVFpcE5tbW82VTNhZ210ZDlLQ0J4dTEtNk5nZlNTV25CeXhzTHJxZ3Rk" } }
I am getting this value from
$response_meta = curl_exec($curl_meta);
I want the result
CAoSLEFGMVFpcE5tbW82VTNhZ210ZDlLQ0J4dTEtNk5nZlNTV25CeXhzTHJxZ3Rk
and store in avriable.
You will be able to access it the following way.
$response_meta['photoID']['id']
Just use the $response_meta.photoId.id or $response_meta['photoId']['id']
var $response_meta = { "photoId": { "id": "CAoSLEFGMVFpcE5tbW82VTNhZ210ZDlLQ0J4dTEtNk5nZlNTV25CeXhzTHJxZ3Rk" } };
console.log($response_meta.photoId.id);
console.log($response_meta['photoId']['id']);
Here is a plunker: Get the id from the object
I did by this way
first set
CURLOPT_RETURNTRANSFER => true,
$response_meta = curl_exec($curl_meta);
$response_json = json_decode($response_meta, true);
$response_result = var_dump($response_json['photoId']['id']);
It gave me the result
string(64) "CAoSLEFGMVFpcE9pNkhOUmI0X2ZSQTJaUkM0ZFVMa1U4Q25hWEUwbEtKY3VGNm9J"

Sending JSON data in the body of an Alamofire Request

I'm trying to make an api call to submit some data using Alamofire (version 4.0). The trouble i'm having is that when making the call I get a response from the server that the JSON data was not in a valid format.
Is there a way to check if the data data is being serialized correctly in Alamofire?
I have tried many of the solutions currently on StackOverflow and cannot find a solution. Thanks for your help.
This should be the format of the request body:
{
"reference_id": "Test001",
"data": {
"type": "step",
"data": {
"2015-08-02": 8574
}
}
}
My Swift code:
let params: [String:Any] = [
"reference_id": "someName",
"data": [
"type" : "step",
"data": [
"2015-08-02": 8574
]
]
]
print(params)
if let userToken = userToken {
let request = Alamofire.request(url+"API.php?Action=SaveHealthData", method: .post, parameters: params, encoding: JSONEncoding.default).responseString(completionHandler: { response in
print(response)
})
}
The error I'm getting is:
Warning: json_decode() expects parameter 1 to be string, array given in /var/www/html/API/SaveHealthData.php on line 8
{"error":"data not in valid json format"}
Here is the solutions of your problem,
var dataDict : [String : Any] = [:];
dataDict["type"] = "Step"
dataDict["data"] = ["2015-08-02": 8574];
let params: [String:Any] = ["reference_id": "someName",
"data": String.toJSonString(data: dataDict)];
Here toJSonString is an extension of String
static func toJSonString(data : Any) -> String {
var jsonString = "";
do {
let jsonData = try JSONSerialization.data(withJSONObject: data, options: .prettyPrinted)
jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
} catch {
print(error.localizedDescription)
}
return jsonString;
}
Happy Coding