Extract a part of text value from response and store it in a variable by using junit/reassured? - rest-assured

I need to test an api endpoint where response of the endpoint will be like this
Response:
{
"items": [
{
"url": "http://www.localhost.com:8080/user?id=19909090"
}
]
}
I want to store the id value that is 19909090 to a variable. Can you please suggest some solution to achieve this ?

You can use JsonPath to read the value of url.
For example:
String url = from(json).get("$.items[0].url");
And then use java.net.URI to extract the query parameter value.
For example:
URI uri = URI.create(url);
String[] params = uri.getQuery().split("=");
// prints out 19909090
System.out.println(params[1]);

Related

iOS Swift How to get value of any key from json response

I am getting a response from an API
["response": {
record = {
title = "Order Add";
usercart = 5345;
};
}, "status": success, "message": تم إضافة السجل بنجاح]
I got the Value for status Key from the code
let statusCode = json["status"].string
Now i want the value for the key usercart in string value
I am using this code but getting any response.
let order_id = json["response"]["record"]["usercart"].string
Please help me to get this value.
As you are using SwiftyJSON and you are trying to get usercart value as a string but the usercart is Int.
So if you want this in string formate you should need to use .stringValue instead of .string else you can use .int or .intValue in form of int.
json["response"]["record"]["usercart"].stringValue
The json you are getting from server is wrong. Instead it should be -
["response": {
"record" : {
"title" : "Order Add",
"usercart" : 5345
};
}, "status": success, "message": تم إضافة السجل بنجاح]
There is nothing like = in json
Also if server response cannot change I would suggest reading this whole thing as string and then using search in string, though it is very bad approach.
if you are using SwiftyJSON then use this to get value
json["response"]["record"]["usercart"].stringValue

Quicktype option parameter handling

I have an optional parameter in my web-service response which can or can not return null. What will be the best what to manage those?
As if I pass null in creator lets say for this structure:
{
"email": "test#test.com",
"profilePicture": null,
"firstTime": true,
"preference1": {
"$id": "26",
"$values": []
},
"Preference2": {
"$id": "27",
"$values": []
}
}
Now profilePicture is set to JSONNull and next time when I actually get profile URL it will not parse that and my response data to LNUser is nil. If I set this variable to String and null received response get set to nil.
You need
let profilePicture:URL?
quicktype needs an exhaustive set of examples, so make sure one of your samples includes a non-null value. Like this: https://app.quicktype.io?share=ldXiDP9cIKB1Q7CPJ7Id

Use JSONAssert on part of JSON with RESTAssured

I am able to retrieve JSON from a service using RESTAssured.
I would like to use the JSONPath capability to extract JSON and then compare it using JSONAssert.
Here's my example:
#Test
public void doAPITestExample() throws JSONException {
// retrieve JSON from service
Response response = RestAssured.given().get("http://localhost:8081/mockservice");
response.then().assertThat().statusCode(200);
String body = response.getBody().asString();
System.out.println("Body:" + body);
/*
{"datetime": "2018-06-21 17:48:07.488384", "data": [{"foo": "bar"}, {"test": "this is test data"}]}
*/
// able to compare entire body with JSONAssert, strict=false
Object data = response.then().extract().path("data");
System.out.println("Response data:");
System.out.println(data.getClass()); // class java.util.ArrayList
System.out.println(data.toString());
// JSONAssert data with strict=false
String expectedJSON = "{\"data\":[{\"foo\": \"bar\"}, {\"test\": \"this is test data\"}]}";
JSONAssert.assertEquals(expectedJSON, response.getBody().asString(), false);
// How do I extract JSON with JSONPath, use JSONAssert together?
}
Approach 1 - using JSONPath to get JSONObject
How do I get JSONPath to return a JSONObject that can be used by JSONAssert?
In the code example:
Object data = response.then().extract().path("data");
This returns a java.util.ArrayList. How can this be used with JSONAssert to compare to expected JSON?
Approach 2 - parse extracted data with JSONParser
If I do data.toString(), this returns a string that cannot be parsed due to lack of quote handling for string values with spaces strings:
String dataString = response.then().extract().path("data").toString();
JSONArray dataArray = (JSONArray) JSONParser.parseJSON(dataString);
Result:
org.json.JSONException: Unterminated object at character 24 of [{foo=bar}, {test=this is test data}]
Approach 3 - Using JSON schema validation
Is is possible to extract just the data property from the JSON and run that against JSON Schema on just that part?
Note: the entire JSON that is returned is quite large. I just want to validate the data property from it.
What would an example of doing a JSON schema validation look for just the data property from the JSON?
Thanks;
You can use the method jsonPath in your response object.
Example:
// this will return bar as per your example response.
String foo = response.jsonPath ().getString ("data[0].foo");
For more info about JSon path check here.

AFQueryStringPairsFromKeyAndValue not giving proper URL with NSArray?

I am trying to send following parameters in GET method call:
{
query = {
"$or" = (
{
name = yes;
},
{
status = Open;
}
);
};
}
But it seems it is not returning the proper URL:
baseURL/objects?query%5B%24or%5D%5B%5D%5Bname%5D=yes&query%5B%24or%5D%5B%5D%5Bstatus%5D=Open
I was expecting to "Or" my data, but it is doing "And".
I am using AFURLRequestSerialization class.
I have followed this SO, but it gives me all the object without applying any query.
AFNetworking GET parameters with JSON (NSDictionary) string contained in URL key parameter
It was working properly in POST call, but in GET it is not working as expected.
I have resolved this by converting dictionary against query key to a string and adding this string as a value of key query in the dictionary.
So my parameters will look like:
parameters: {
query = "{\"$or\":[{\"name\":\"yes\"},{\"status\":\"Open\"}]}";
}
Then I am passing this dictionary to AFNetworking.

How to get particular json key value from Response Object

I got the response from REST API into Response object after called through RestAssured API.
Response body is json, i want to get the particular key value from that?
Following is the code
Response res = given()
.relaxedHTTPSValidation()
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.get(url);
String rbody = res.body().asString();
How to get particular key value in rbody string?
Response class has method path() using that, user can give the json path to get the particular value.
Eg:-
Response res = given()
.relaxedHTTPSValidation()
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.get(url);
String value = res.path("root.childKey").toString();
root.childKey is the path of the json element
The JasonPath class that is a part of Restassured is the one that I used for my project. First you need to import the JsonPath class using:
import com.jayway.restassured.path.json.JsonPath;
Then you need to pass the JSON string and use it to create the JsonPath object. From the JsonPath object you can use the key to get the corresponding value. The following code will work for you.
Response res = given()
.relaxedHTTPSValidation()
.with()
.contentType(ConfigReader.get("application.json"))
.then()
.get(url);
String rbody = res.asString();
JsonPath jp = new JsonPath( rbody );
String value = jp.getString( "your.key" );
JSON is formated like this {someProprty:"someValue"} so instead of getting it as a String, you'll want to access that specific property. ie: b.body.someProperty
Note: I strongly encourage you to name your response something more like res or response. You aren't going to enjoy having b as your response.
How to access JSON Object name/value?
JSON can also be formatted like {somePropertyThatIsNumerical:1} or can contain arrays.
baseURI="url";
Map<String,String> reqParam=new HashMap<String,String>();
reqParam.put("loginID","abc");
reqParam.put("password","123");
JSONObject reqObjects=new JSONObject(reqParam);
Response response =
given()
.header("Content-Type", "application/json").accept(ContentType.JSON)
.when()
.body(reqObjects.toJSONString()).post("/v1/getDetails")
.then().log().body().extract().response();
String responseBody= response.asString();
JsonPath path=new JsonPath(responseBody);
String key=path.getString("path.key");

Resources