API returning text/html rather than JSON when triggered using RestArrured - rest-assured

I'm triggering the Zomato api for the collections request, however, I keep getting the headers as if they were text/html. Postman returns them as JSON, which is what I need. All other Zomato apis I've tested so far are returning JSON but collections and not sure why. That's what I have on my attempts to force the JSON as the type for the response.
#Test
public void testGetCousinesApiReturnsItemsInAscendingAlphabeticalOrder() {
Map<String, Object> map = new HashMap<>();
map.put("city_id", 61);
Response r = given()
.baseUri(baseUrl)
.basePath("/cousines")
.queryParams(map)
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.contentType("application/json\r\n")
.header("Accept", "application/json").and()
.header("Content-Type", "application/json")
.header("user-key", zomatoKey)
.log().body(false)
.get();
System.out.println(r.getContentType());
}

I convert response to JsonPath :
public static JsonPath getJsonPath (Response res) {
String json = res.asString();
System.out.println("returned json: " + json);
return new JsonPath(json);
}
and then use this JsonPath to get each value of Response:
JsonPath jp = getJsonPath(res);
String type = jp.get("type");

Related

Fetching Value From Json Object Stored as String for a Key in Response payload

How do I read a value from below response payload. From the second property in this JSON object, how do I fetch the value for the 'status' i.e "Active" or any other value for response key.
{
"signature": "1hdj12493039282849922",
"response": "{'UsersList':[{'userName':'Madan Jones','mobileNumber':'767780987','status':'Active','statusCode':null}],'status':0,'messageCode':null,'message':null,'errorMap':null}"
}
Any help is greatly appreciated!! Thanks in advance!!
Your response contains just a text that only looks like another json. So in order to do a check you have to fetch that value, parse it and hope that it would be a valid json too.
public static void main(String[] args) throws JsonProcessingException {
String str = RestAssured
.get("http://demo1954881.mockable.io/textjson")
.jsonPath().get("response");
JsonPath jsonPath = new JsonPath(str.replace("'", "\""));
String status = jsonPath.get("UsersList.find{u -> u.userName = 'Madan Jones'}.status");
MatcherAssert.assertThat(status, Matchers.equalTo("Active2"));
}
In your particular example JsonPath does not like that your field names are wrapped with ' so I change them to be proper double-quotes.

Passing body in restassured using Generics doesn't work for File and FileInputStream

In Restassured we can pass the request payload in the body method by different ways like
String
POJO Object
Map Object
JsonObject (from GSON library)
File and
FileInputStream
So, I created following one method using generics to accommodate all these types: -
public <T> Response postAMember(T body) {
return given().spec(this.spec).body(body).when().post(EndPoints.GET_ALL_POST_A_MEMBER).andReturn();
}
Now, this is how I'm consuming it for respective Type (Not all in one go...one at a time): -
#Test
public void postMember() throws IOException {
// Using Hashmap
Map<String, String> body = new HashMap<>();
body.put("name", "Rocky");
body.put("gender", "Male");
// Using Model and GSON
Member imember = new Member("Rocky", "Male");
Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
String body = gson.toJson(imember);
// Using JsonObject (GSON)
JsonObject body = new JsonObject();
body.addProperty("name", "Rocky");
body.addProperty("gender", "Male");
// Using Payload JSON File
File body = new File("src/test/resources/Payloads/postmemberpayload.json");
// Using Raw String
String body = "{\r\n" +
" \"name\": \"Rocky\",\r\n" +
" \"gender\": \"Male\"\r\n" +
"}";
// Using FileInputStream
FileInputStream fis = new FileInputStream(body); // in this case I would pass fis to body method
Response resp = MemberService.getMemberServiceInstance().postAMember(body);
Assert.assertEquals(resp.getStatusCode(), StatusCode.CREATED_201);
Member omember = resp.getBody().as(Member.class);
System.out.println(omember.toString());
}
postAMember method works fine only with : -
String
POJO Object
Map Object
JsonObject (from GSON library)
But fails with remaining two: -
File - Output is bad request 400
FileInputStream - Output is java.lang.IllegalArgumentException: jdk.internal.ref.PhantomCleanable<?> declares multiple JSON fields named next
And for now I've to make following two more overloaded version of postAMember: -
public Response postAMember(File body) {
return given().spec(this.spec).body(body).when().post(EndPoints.GET_ALL_POST_A_MEMBER).andReturn();
}
public Response postAMember(FileInputStream body) {
return given().spec(this.spec).body(body).when().post(EndPoints.GET_ALL_POST_A_MEMBER).andReturn();
}
Now above two methods generate the response. Any clue what's wrong here? Why the method with generics is not able to take File and FileInputStream?
I've fetched the latest Restassured libraries from maven central repo.
As far as I understand, your generics method will map to body(Object object) of RequestSpecification, then this object will be serialized.
class RequestSpecificationImpl
...
RequestSpecification body(Object object) {
...
this.requestBody = ObjectMapping.serialize(object, requestContentType,
findEncoderCharsetOrReturnDefault(requestContentType), null,
objectMappingConfig(), restAssuredConfig().getEncoderConfig());
...
}
All below kinds of object has no problem with serialization.
String
POJO Object
Map Object
JsonObject (from GSON library)
But
File ---serialize---> full path of FILE
FileInputStream ---serialize---> exception (from Gson/Jackson)
When you add 2 methods, then Rest-Assured correctly map to body(File body) and body(InputStream body) --> no serialization for them --> no issue.

How to Put request with json payload with rest assured

I want to load the JSON file in a body with rest assured but getting error 415.
Can you please help me?
code is:
public class Entitlement_Creation extends BaseClass {
#Test
public void JsonPayload() throws IOException
{
Path json_data = Paths.get("test.json");
byte[] wikiArray = Files.readAllBytes(json_data);
String wikiString = new String(wikiArray);
System.out.println(wikiString);
given()
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.body(wikiString)
.when()
.put()
.then()
.statusCode(200)
.extract()
.response();
}
from this snippet, I can't see any information about URL of your service.
You should put your URL as an argument to put() method.

setting api key to restassured tests

I am trying to pass api key in restassured. From postman, i got the repsonse data using 'X-Api-Key' with value. But with rest assured, i am seeing null pointer exception
Response res = given()
.header("key","55af7bc105c9c2ee98e2abb32979fee")
.when()
.get ("https://mbaseurl/api/v1/search-listings/").then().
// contentType(ContentType.JSON). // check that the content type return from the API is JSON
extract().response();
I tried passing key value with .header("X-Api-Key", "value") but was not successful
Map<String, String> pMap = new HashMap<String, String>();
pMap.put("apiKey","yourAPIKEY");
pMap.put("format","json");
pMap.put("show","storeId,`storeType`,name,city,region");

ASP.Net MVC: how to create a JsonResult based on raw Json Data

Having a string containing the following raw Json data (simplified for the sake of the question):
var MyString = "{ 'val': 'apple' }";
How can I create a JsonResult object representing MyString?
I tried to use the Json(object) method. but it handles the raw json data as an string -logically :P-. So the returned HTTP response looks like:
"{ 'val': 'apple' }"
instead of the given raw Json Data:
{ 'val': 'apple' }
this is what I want to achieve:
The Json() method on Controller is actually a helper method that creates a new JsonResult. If we look at the source code for this class*, we can see that it's not really doing that much -- just setting the content type to application/json, serializing your data object using a JavaScriptSerializer, and writing it the resulting string.. You can duplicate this behavior (minus the serialization, since you've already done that) by returning a ContentResult from your controller instead.
public ActionResult JsonData(int id) {
var jsonStringFromSomewhere = "{ 'val': 'apple' }";
// Content() creates a ContentResult just as Json() creates a JsonResult
return Content(jsonStringFromSomewhere, "application/json");
}
* Starting in MVC2, JsonResult also throws an exception if the user is making an HTTP GET request (as opposed to say a POST). Allowing users to retrieve JSON using an HTTP GET has security implications which you should be aware of before you permit this in your own app.
The way I have generated json data from a string is by using JavaScriptResult in the controller:
public JavaScriptResult jsonList( string jsonString)
{
jsonString = "var jsonobject = new Array(" + jsonString + ");";
return JavaScript(jsonString)
}
Then when you request pass the json string to that action in your controller, the result will be a file with javascript headers.
I think you can use the JavaScriptSerializer class for this
var js = new System.Web.Script.Serialization.JavaScriptSerializer();
var jsonObject = js.Deserialize("{ 'val': 'apple' }", typeof(object));

Resources