json path for response - API Restassured - api

Below is the response i get for post call.
How to get quoteId and fee amount value using Json from the below response.
{
"data": {
"quoteId": "Lid123",
"loanTerm": "48.0",
"lenderRate": "4.5",
"customerRate": "4.499999999999904",
"fees": [
{
"feeType": "EstablishmentFee",
"feeAmount": "450"
}
],
"periodPaymentInclGSTAmount": "6416.5"
}
}
Thank you in advance

You can use jsonpath() method to extract value from json.
Response res = ...
String quoteId = res.jsonPath().getString("data.quoteId");
String feeAmount = res.jsonPath().getString("data.fees[0].feeAmount");
System.out.println(quoteId); //Lid123
System.out.println(feeAmount); //450

String id = JsonPath.from(reponseBody).getString("data.quoteId");
String EstablishmentFee = JsonPath.from(reponseBody).getString("data.fees.feeAmount");

Related

How can i exclude Keys in Object which are null to be returned in Json

i am wondering if there is a way to prevent a response to return keys in object that are null or null equivalent. I have for example a Response envelope and then the data payload and a sample response looks like this.
{
"success": true,
"errorCode": "",
"message": "JWT Token succesfull created",
"data": {
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJuYW1lIjoidXNlcmlkIiwiU2NvcGUiOlsiQVRUQ1NSIiwiQVRUTFNSIl0sIm5iZiI6MTU4NDc0MjIzMiwiZXhwIjoxNTg0NzQzOTcyLCJpc3MiOiJodHRwOi8vc29hcGFwaS5wZ3RlbC5uZXQiLCJhdWQiOiJodHRwOi8vbG9jYWxob3N0OjU3NDY0In0.dWuETKdlfX4VzwWEP5XafZOpnFmSSCchQHUHi5GZ99E",
"expiration": "0001-01-01T00:00:00",
"scope": null
}
}
In this case expiration and scope are null expiration is a DateTime field.
Here is how i get to this response
Dim myResponse As New jsonResponse
myResponse.success = True
meResponse.errorCode = ""
myResponse.message = "JWT Token succesfull created"
Dim authCheck As New JSONWebTokenUtil
Dim accessList As New List(Of String)
accessList.Add("Sample1")
Dim Token = authCheck.GenerateJSONWebToken("userid", accessList, )
Dim myToken As New tokenResponse
myToken.token = Token
myResponse.data = myToken
Return myResponse
So since in the above case i dont set the scope or experation its null. Is there a way to be part of the out put if null or do i need to check each value and remove it if its null
I would try the following, from vb.net when you recive the json response, add the response to a string variable the with the replace's string method try to change the null value to a new value. I hope this be useful. Thank you. :)

How to compare a input value to value in results

This is my input
{
"AccountId": "9834e8cb-275a-4bff-b362-f216e9653686",
"ContactId": "9834e8cb-275a-4bff-b362-f216e9653686",
"AuthenticationDetails": {
"AuthenticationId": "{{clientId}}",
"AuthenticationType": "Token"
}
}
This is my output
{
"orderedByContactId": "36b8e4da-94fd-4680-a2d3-6b128e4b2584",
"orderedForContactId": "9834e8cb-275a-4bff-b362-f216e9653686"
}
I need to create a test (postman) to ensure that the output value ("orderedForContactId") matches the input value ("ContactId"). Can someone help me out?
Existing tests are in the following format:
pm.test("Response should contain orderedForContactId",function(){
let jsonRespData = pm.response.json();
pm.expect(jsonRespData).to.have.property('orderedForContactId');
});
Use this as your test script
pm.test("Response should contain orderedForContactId",function(){
var requestJson= JSON.parse(pm.request.body.raw);
var contactId = requestJson.ContactId.toString();
var responseJson = pm.response.json();
var orderedForContactId = responseJson.orderedForContactId;
pm.expect(orderedForContactId ).to.equal(contactId);
});
I changed the input to be
{
"AccountId": "9834e8cb-275a-4bff-b362-f216e9653686",
"ContactId": "{{ContactId}}",
"AuthenticationDetails": {
"AuthenticationId": "{{clientId}}",
"AuthenticationType": "Token"
}
}
And added the ContactId to the environment file.
Then I created the test below:
pm.test("Input ContactId should equal orderedForContactId",function(){
let jsonRespData = pm.response.json().orderedForContactId;
pm.expect(jsonRespData).to.equal(pm.environment.get("ContactId"))
});

how to parameterize string along with variable name in input json file

def userName = 'ABC'
def input json = {
"integration": {
"serviceData": {
"integrationService": {
"name": "fld_<tenantID>_stage00.integrations:<integrationName>"
},
"gitComments": "Commit made by: ABC"
}
}
}
In the above json I need to parameterize the user name 'ABC'
If I send
"gitComments": "#(userName)"
It is checking 'ABC' which is fine
But I need to prefix the String "Commit made by: " And then #(userName) in the input json.
Thanks in Advance
https://github.com/intuit/karate#rules-for-embedded-expressions
* def gitComments = 'Commit made by: ' + userName
* def json = { gitComments: '#(gitComments)' }

How to pass the request object as query string in Power Query Formula Language

I am trying to pull data from an API in power bi using power query formula language.
My code is:
let
obj= "{ ""dataset"": ""mydataset"",""queries"": [ { ""type"": ""single_measurement"", ""measure"": { ""aggregator"": ""unique_count"", ""column"": ""visitor_id"" } } ], ""start"":1451638800000,""end"":1468430640000,""max_groups"":1000,""group_by"":[""extrhike""]}",
authKey = "Token js+JG/FaGiZcFZPVAsAXmN+d20000",
url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query?query=obj",
GetJson = Json.Document(Web.Contents(url,[Headers = [#"Authorization"=authKey, #"Content-Type"="application/json"]]))
in
GetJson
I want to pass the data request object(obj) as a query string like following
https://myhostaddress.cloudapp.azure.com/api/v1/query?query={ "dataset": "mydataset","queries": [ { "type": "single_measurement", "measure": { "aggregator": "unique_count", "column": "visitor_id" } } ], "start":1451638800000,"end":1468430640000,"max_groups":1000,"group_by":["extrhike"]}
I am unable to pass obj as a querystring value in power query.I am getting following error
DataFormat.Error: Invalid URI: The hostname could not be parsed.
Details:
https:// myhostaddress.cloudapp.azure.com/api/v1/query?query=obj
How do I pass the request object(obj) as query string in Power Query Formula Language.
Thanks in advance
Have you tried passing in your query parameters with the Query argument of Web.Contents ?
For e.g
let
Url = "https:// myhostaddress.cloudapp.azure.com"
Request = Json.Document(Web.Contents(url,
[Headers =
[#"Authorization"=authKey,
#"Content-Type"="application/json"],
RelativePath = "/api/v1/query",
Query = [
<insert record here of your query object>
]
]
An example of the Query record might be:
Query = [#"Argument 1" = "Foo", #"Argument 2" = "Bar", limit = "1000", skip="500"]
You can read about the options here: https://msdn.microsoft.com/en-us/library/mt260892.aspx
You need to add the strings together. It should be url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query?query=" & obj,.
Try to use this
It POSTs content instead of GETting query
let
obj = "{ ""dataset"": ""mydataset"",""queries"": [ { ""type"": ""single_measurement"", ""measure"": { ""aggregator"": ""unique_count"", ""column"": ""visitor_id"" } } ], ""start"":1451638800000,""end"":1468430640000,""max_groups"":1000,""group_by"":[""extrhike""]}",
authKey = "Token js+JG/FaGiZcFZPVAsAXmN+d20000",
url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query",
GetJson = Json.Document(Web.Contents(url,[
Headers = [#"Authorization"=authKey, #"Content-Type"="application/json"],
Content = Text.ToBinary(obj)
]))
in
GetJson
You also may use this
It escapes obj to percent-string and appends to "query" parameter
let
obj= "{ ""dataset"": ""mydataset"",""queries"": [ { ""type"": ""single_measurement"", ""measure"": { ""aggregator"": ""unique_count"", ""column"": ""visitor_id"" } } ], ""start"":1451638800000,""end"":1468430640000,""max_groups"":1000,""group_by"":[""extrhike""]}",
authKey = "Token js+JG/FaGiZcFZPVAsAXmN+d20000",
url = "https:// myhostaddress.cloudapp.azure.com/api/v1/query?query="&Uri.EscapeDataString(obj),
GetJson = Json.Document(Web.Contents(url,[Headers = [#"Authorization"=authKey, #"Content-Type"="application/json"]]))
in
GetJson

MobileFirst - Invoking Java SQL Adapter adapter procedure

I am following the Java SQL Adapter tutorial for MobileFirst Platform 7.
I'm trying to Get User with userId = "bjones", but I don't know how to set the params {userId} into the procedure /adapters/UserAdapter/{userId}.
function loadUsers(){
busyIndicator.show();
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/", WLResourceRequest.GET);
resourceRequest.setQueryParameter("userId", "bjones");
resourceRequest.send().then(
loadUsersSuccess,
loadUsersFailure
);}
function loadUsersSuccess(result){
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
WL.Logger.debug(JSON.stringify(result));
if (result.responseJSON.length>0)
displayFeeds(result.responseJSON);
else
loadUsersFailure();}
function loadUsersFailure(result){
WL.Logger.error("Feed retrieve failure");
busyIndicator.hide();
WL.SimpleDialog.show("Banking Application", "Service not available. Try again later.",
[{
text : 'Reload',
handler : WL.Client.reloadApp
},
{
text: 'Close',
handler : function() {}
}]
);}
My request is
localhost:10080/JavaAdapters/adapters/UserAdapter/?userId=bjones
but the JSON response contains all user stored in my database
Image for response
In addition, how about the REST call type #PUT, with Path param "userId" and body params: "firstName", "lastName", "password", in order to update an user
From the tutorial the adapter endpoint is /{userId} which means the userId is not a query param but it is part of the url. You need to update your loadUsers function so that it appends the userId at the end of the url, so in your example the fullpath will be /adapters/UserAdapter/bjones
function loadUsers(){
busyIndicator.show();
var usedId = "bjones";
var resourceRequest = new WLResourceRequest("/adapters/UserAdapter/"+userId, WLResourceRequest.GET);
resourceRequest.send().then(loadUsersSuccess,loadUsersFailure);
}
UPDATE:
function loadUsersSuccess(result) {
WL.Logger.debug("Feed retrieve success");
busyIndicator.hide();
WL.Logger.debug(JSON.stringify(result));
// if responseJSON is not null user data was returned
if (result.responseJSON != null) {
displayFeeds(result.responseJSON);
} else{
loadUsersFailure();
}
}
there are basically two type of URL with Parameters:
1. Path parameter:
/adapters/UserAdapter/users/{userId}
2. Query Parameter:
/adapters/UserAdapter/users?userId={userId}
java adapter with query parameter:
#GET
#Produces("application/json")
#OAuthSecurity(enabled = false)
#Path("/users")
public String getuserById(#QueryParam("userID") String userId)
{
System.out.println(userId);
}
java adapter with path parameter:
#GET
#Produces("application/json")
#OAuthSecurity(enabled = false)
#Path("/users/{userId}")
public String getuserById(#PathParam("userId") String userId)
{
System.out.println(userId);
}
I hope, second example answers your question in java adapter.