How do i convert cpr's get response into a json object? - c++

I was looking for a easy to understand library that make HTTP REST Requests in C++ and then i came across CPR. I was successfully able to get the response from the server but i find it difficult to access the returned JSON object.
API Get Request:
auto r = cpr::Get(cpr::Url{ "https://example.net/api/token" },
cpr::Parameters{ {"username", login}, {"password", password},
{"hwid", "TestChecker"}, {"obt", "1"}});
r.status_code;
r.header["application/json"];
r.text;
I tried to pass r.text into nlohmann::json j = r.text; and access the particular object i wanted like this string xx = j["token"];
As expected, it threw an error.
I'd really appreciate it if anyone could tell me how to achieve what i failed to do.
Edit : Added References
CPR : https://www.codeproject.com/Articles/1244632/Making-HTTP-REST-Request-in-Cplusplus
nlohmann/json : https://github.com/nlohmann/json

I did play around a bit with the code and finally figured it out.
Basically what i wanted to do was to convert a "JSON String" into a JSON Object.
I achieved it by using the method nlohmann::json::parse();
Json j = Json::parse(r.text);
string xx = j["token"];

Related

PowerBI Query WebMethod.Post returns Expression.Error: We cannot convert the value "POST" to type Function

I'm using a website that requires that their API key AND query data be submitted using Webform.Post method. I'm able to get this to work in Python, C# and I'm even able to construct and execute a cURL command which returns a usable JSON file that Excel can parse. I am also using Postman to validate my parameters and everything looks good using all these methods. However, my goal is to build a query form that I can use within Excel but I can't get past this query syntax in PowerBi Query.
For now I am doing a simple query. That query looks like this:
let
url_1 = "https://api.[SomeWebSite].com/api/v1.0/search/keyword?apiKey=blah-blah-blah",
Body_1 = {
"SearchByKeywordRequest:
{
""keyword"": ""Hex Nuts"",
""records"": 0,
""startingRecord"": 0,
""searchOptions"": Null.Type,
""searchWithYourSignUpLanguage"": Null.Type
}"
},
Source = WebMethod.Post(url_1,Body_1)
in
Source
ScreenSnip showing valid syntax
It generates the following error:
Expression.Error: We cannot convert the value "POST" to type Function.
Details:
Value=POST
Type=[Type]
ScreenSnip of Error as it appears in PowerQuery Advanced Editor
I've spend the better part of the last two days trying to find either some example using this method or documentation. The Microsoft documentation simple states the follow:
WebMethod.Post
04/15/2018
2 minutes to read
About
Specifies the POST method for HTTP.
https://learn.microsoft.com/en-us/powerquery-m/webmethod-post
This is of no help and the only posts I have found so far criticize the poster for not using GET versus POST. I would do this but it is NOT supported by the website I'm using. If someone could just please either point me to a document which explains what I am doing wrong or suggest a solution, I would be grateful.
WebMethod.Post is not a function. It is a constant text value "POST". You can send POST request with either Web.Contents or WebAction.Request function.
A simple example that posts JSON and receives JSON:
let
url = "https://example.com/api/v1.0/some-resource-path",
headers = [#"Content-Type" = "application/json"],
body = Json.FromValue([Foo = 123]),
source = Json.Document(Web.Contents(url, [Headers = headers, Content = body])),
...
Added Nov 14, 19
Request body needs to be a binary type, and included as Content field of the second parameter of Web.Contents function.
You can construct a binary JSON value using Json.FromValue function. Conversely, you can convert a binary JSON value to a corresponding M type using Json.Document function.
Note {} is list type in M language, which is similar to JSON array. [] is record type, which is similar to JSON object.
With that said, your query should be something like this,
let
url_1 = "https://api.[SomeWebSite].com/api/v1.0/search/keyword?apiKey=blah-blah-blah",
Body_1 = Json.FromValue([
SearchByKeywordRequest = [
keyword = "Hex Nuts",
records = 0,
startingRecord = 0,
searchOptions = null,
searchWithYourSignUpLanguage = null
]
]),
headers = [#"Content-Type" = "application/json"],
source = Json.Document(Web.Contents(url_1, [Headers = headers, Content = Body_1])),
...
References:
Web.Contents (https://learn.microsoft.com/en-us/powerquery-m/web-contents)
Json.FromValue (https://learn.microsoft.com/en-us/powerquery-m/json-fromvalue)
Json.Document (https://learn.microsoft.com/en-us/powerquery-m/json-document)

Using Postman, unable to reference CSV file for JavaScript test

I am using a REST API with a POST request. I have created a CSV file to load in various inputs and using the Collection Runner to submit my requests and run the associated JavaScript Tests iteratively. I am trying to figure out how I can also have an entry in each row of the CSV to reference for my JavaScript Test in order to make the JavaScript dynamic. I've searched the Postman documentation and forums, as well as Google and Stack Overflow, but I haven't found anything that works. Here is a basic example of what I'm trying to accomplish.
Let's say I have a basic adding API. Here is my Request:
{
"Numbers": {
"Value_1": {{val1}},
"Value_2": {{val2}},
}
}
The CSV file is as follows:
val1,val2,sum
1,1,2
2,2,4
3,3,6
For this example, lets assume that the API returns a response that includes the sum of val1 and val2; something like this:
{
"Numbers": {{sum}},
}
I am able to load val1 and val2 into my request and iterate through the request for each row, but I am having trouble incorporating the sum values (from the same CSV) into the JavaScript Test.
I am trying to do something like the test below where I can reference the sum value from my spreadsheet, but Postman doesn't like my syntax.
pm.test("Adding machine", function () {
var jsonData = pm.response.json();
pm.expect(jsonData.Numbers === {{sum}});
});
Does anyone have any suggestions? Is this even possible to do?
You could use the pm.iterationData().get('var_name') function and create a check like this?
pm.test("Sums are correctly calculated", () => {
pm.expect(pm.response.json().Numbers).to.equal(pm.iterationData.get('sum'))
})

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

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.

How to parse output from sse.client in Python?

I am new to Python and am trying to get my ahead around parsing SSE client code. I am using the SSE Client library. My code is very basic and follows the sample exactly. Here it is:
from sseclient import SSEClient
devID = "xxx"
AToken = "xxx"
sparkURL = 'https://api.spark.io/v1/devices/' + devID + '/events/?access_token=' + AToken
messages = SSEClient(sparkURL)
for msg in messages:
print(msg)
print(type(msg))
The code runs without a problem and I see some blank lines and SSE data coming through. Here is the sample output:
<class 'sseclient.Event'>
{"data":"0 days, 0:54:43","ttl":"60","published_at":"2015-04-09T22:43:52.084Z","coreid":"xxxx"}
<class 'sseclient.Event'>
<class 'sseclient.Event'>
{"data":"0 days, 0:55:3","ttl":"60","published_at":"2015-04-09T22:44:12.092Z","coreid":"xxx"}
<class 'sseclient.Event'>
The actual output above looks like a dictionary, but its type is "sseclient.Event". I am trying to figure out how to parse the output so I can pull out one of the fields and nothing I have tried has worked.
Sorry if this is basic questions, but can someone provide some simple guidance on how I would either convert the entire output to a dictionary or perhaps just pull out one of the fields?
Thank you in advance!
I figured this out. In case anyone else experiences the same problem, here is how I got it to work. The key was using msg.data and not just msg. I then converted the out using the JSON library and am good to go.
messages = SSEClient(sparkURL)
for msg in messages:
outputMsg = msg.data
if type(outputMsg) is not str:
outputJS = json.loads(outputMsg)
FilterName = "data"
#print( FilterName, outputJS[FilterName] )
print(outputJS[FilterName])

SBL-ODU-01007 The HTTP request did not contain a valid SOAPAction header

I am hoping someone can help get me in the right direction...
I am using Powerbuilder 12 Classic and trying to consume a Oracle CRM OnDemand web service.
Using Msxml2.XMLHTTP.4.0 commands, I have been able to connect using https and retrieve the session id, which I need to send back when I invoke the method.
When I run the code below, I get the SBL-ODU-01007 The HTTP request did not contain a valid SOAPAction header error message. I am not sure what I am missing??
OleObject loo_xmlhttp
ls_get_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=login"
try
loo_xmlhttp = CREATE oleobject
loo_xmlhttp.ConnectToNewObject("Msxml2.XMLHTTP.4.0")
loo_xmlhttp.open ("GET",ls_get_url, false)
loo_xmlhttp.setRequestHeader("UserName", "xxxxxxx")
loo_xmlhttp.setRequestHeader("Password", "xxxxxxx")
loo_xmlhttp.send()
cookie = loo_xmlhttp.getResponseHeader("Set-Cookie")
sesId = mid(cookie, pos(cookie,"=", 1)+1, pos(cookie,";", 1)-(pos(cookie,"=", 1)+1))
ls_post_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration/Activity;"
ls_response_text = "jsessionid=" + sesId + ";"
ls_post_url = ls_post_url + ls_response_text
loo_xmlhttp.open ("POST",ls_post_url, false)
loo_xmlhttp.setRequestHeader("COOKIE", left(cookie,pos(cookie,";",1)-1) )
loo_xmlhttp.setRequestHeader("COOKIE", left(cookie,pos(cookie,";",1)-1) )
ls_post_url2 = "document/urn:crmondemand/ws/activity/10/2004:Activity_QueryPage"
loo_xmlhttp.setRequestHeader("SOAPAction", ls_post_url2)
loo_xmlhttp.send()
ls_get_url = "https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=logoff"
loo_xmlhttp.open ("POST",ls_get_url, false)
loo_xmlhttp.send()
catch (RuntimeError rte)
MessageBox("Error", "RuntimeError - " + rte.getMessage())
end try
I believe you are using incorrect URL for Login and Logoff;
Here is the sample:
https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=login
https://secure-ausomxxxx.crmondemand.com/Services/Integration?command=logoff
Rest of the code looks OK to me.
I have run into similar issues in PB with msxml through ole. Adding this may help:
loo_xmlhttp.setRequestHeader("Content-Type", "text/xml")
you need to make sure that the your value for ls_post_url2 is one of the values that is found in the wsdl file. Just search for "soap:operation soapAction" in the wsdl file to see the valid values for SOAPAction.