Rest Assured API testing - Pass a Json Object as parameter to a get request - rest

REST Assured Testing -
How to use delete request to delete the Workspace from this url
http://in-kumaran2-1:8080/devops-workbench-web/rest/api/workspace/delete/{projectId}
given the request
given().when().delete(url,JSON body);
Where Sample Request JSON body is given below
{"name":"newworkspace","workspaceFlow":"Open
Sorce","versionControl":"SVN","featureManagement":"JIRA","defectManagement":"","buildAutomation":"Selenium","deploymentAutomation":"","buildRepository":"Nexus","codeQualityTools":"SonarQube","automatedTestingTools":"Selenium","environmentProvision":"Puppet","environmentConfiguration":"Puppet","projectId":{"id":"56cebe578850d51c6fe07684","name":"wbproject","description":"wbproject","processTemplate":"Agile","projectManager":"Anil","projectStartDate":1454284800000,"projectEndDate":1475193600000,"remarks":null,"accountId":{"id":"56cebe218850d51c6fe07683","accountName":"workbench","accountDescription":"workbench
account"}}}
projectID has another Object {"id": "56cebe578850d51c6fe07684" ....} How to pass this projectId in the delete Request

actually, i have passed json object like below:
Response res =given().
content(jo). //jo is the json object to pass with the url.
with().
contentType("application/json").
header("Content-Type", "application/json").
when().
post(settings.getApiUrl()); //this is the url, i use post method
and jo is something like this:
JsonObject jo = new JsonObject();
jo.addProperty("username", "abc");//key and value
jo.addProperty("password", "abc");//key and value
u may try something like this.i used here as header u may send it as param.

URL is: http://example.com/building
My Query Strings are :
globalDates:{"startMs":1473672973818,"endMs":1481448973817,"period":90}
limitTo:6
loadTvData:true
startFrom:0
userId:5834fb36981baacb6a876427
Way to pass Query String Parameters in GET url using Rest Assured like this :-
when() .parameter("globalDates","startMs","1474260058054","endMs","1482036058051","period","90")
.parameters("limitTo","6")
.parameters("loadTvData","true")
.parameters("startFrom","0")
.parameters("userId","5834fb36981baacb6a876427");

Related

Verify API Response

Am getting the response of a request like this:
var response = command.PostCommand(testCommand);
I will like to validate that the response is in a json format so am doing it like this:
Assert.AreEqual("application/json", response.ContentType);
Is this way correctly or do i need to specifically validate it from the content-type header response?
You can use the IRestRequest.OnBeforeDeserialization callback to check the response content type before it gets deserialised:
var request = new RestRequest(url)
.AddQueryParameter(x, y); // whatever you need to configure
request.OnBeforeDeserialization =
response => CheckContentType(response.ContentType);
await client.PostAsync<MyResponse>(request);

How to pass response body field to other request's body (Gatling)

I have two end point.
-/authenticate
-/authenticate/verification
/authenticate return guid field on response body.
and /authenticate/verification requires that field on request body.
I have tried to get guid like this :
jsonPath("$..guid").saveAs("verificationGuid")
and pass it to other body :
.body(StringBody(s"{\"guid\":${verificationGuid}, \"code\":\"123456\"}"))
this is the code block:
def login = {
exec(http("Authenticate")
.post("/authenticate")
.body(StringBody(userString))
.headers(headerLogin)
.check(status is 200)
.check(jsonPath("$..guid").saveAs("verificationGuid"))
)
.exec(http( "Authenticate verify")
.post("/authenticate/verify")
.headers(headerLogin)
.body(StringBody(s"{\"guid\":${verificationGuid}, \"code\":\"123456\"}"))
.check(status is 200)
)
}
But it doesnt work, how can I do this?
Remove s from s"{\"guid\":${verificationGuid}, \"code\":\"123456\"}"). If s is in front of string every ${something} placeholder will be treated as Scala built in string interpolation and compiler will try to replace it with Scala variable, which in your case does not exist. Without s it will be treated as literal string and than caught by Gatling EL Parser and replaced with previously saved Gatling session attribute.

RestAssured response validation using body and array as parameter

I am trying to validate a REST response. Is it possible to use an array as parameter to containsonly?
Ex:
String values[] = line.split(",");
given().
when().
then().
statusCode(200).
body("value", containsOnly(values));
Also, can we use variables as parameters to other methods like HasItems, equalTo etc?
Ex: body(HasItems(values))
Yes, You could use any appropriate matcher to check whole body or just part of it. Just take attention on a object type returned by pecified path - first argument of body().
Try this :
Response resp = RestAssured.given()
.header("Content-Type", "application/vnd.dpd.public.v1+json")
.body(FixtureHelpers.fixture("request/request.json"))
.post("/");
resp
.then()
.statusCode(200)
.body("random.object", CoreMatchers.equalTo("value"));
This would work for request.json object like :
{"random":{"object": "value"}}

How to set url encoded form entity and add params to form entity in rest assured?

The below sample code is in http client , But I want to write the same in Rest Assured. I know we can use the http lib in rest assured as well, But I want to have in Rest assured
HttpPost pst = new HttpPost(baseUrl, "j_spring_security_check"))
pst.setHeader("Content-Type", "application/x-www-form-urlencoded")
ArrayList<NameValuePair> postParam = new ArrayList<NameValuePair>()
postParam .add(new BasicNameValuePair("j_username",username))
postParam .add(new BasicNameValuePair("j_password",password))
UrlEncodedFormEntity formEntity23 = new UrlEncodedFormEntity(postParam)
pst.setEntity(formEntity23 )
HttpResponse response = httpclient.execute(pst);
For Rest Assured you can use below code snippet.
Response response = RestAssured
.given()
.header("Content-Type", "application/x-www-form-urlencoded")
.formParam("j_username", "uName")
.formParam("j_password", "pwd")
.request()
.post(url);
As, your application is using form url-encoded content type you can set the Header type to this as mentioned above.
Hope, this helps you.
#Test
public void postRequestWithPayload_asFormData() {
given().contentType(ContentType.URLENC.withCharset("UTF-8")).formParam("foo1", "bar1").formParam("foo2", "bar2").log().all()
.post("https://postman-echo.com/post").then().log().all().statusCode(200)
.body("form.foo1", equalTo("bar1"));
}
Add content type of URLENC with charaset as UTF-8. It works will latest rest assured.

How to construct a REST API that takes an array of id's for the resources

I am building a REST API for my project. The API for getting a given user's INFO is:
api.com/users/[USER-ID]
I would like to also allow the client to pass in a list of user IDs. How can I construct the API so that it is RESTful and takes in a list of user ID's?
If you are passing all your parameters on the URL, then probably comma separated values would be the best choice. Then you would have an URL template like the following:
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?id=id1,id2,id3,id4,id5
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
IMO, above calls does not looks RESTful, however these are quick and efficient workaround (y). But length of the URL is limited by webserver, eg tomcat.
RESTful attempt:
POST http://example.com/api/batchtask
[
{
method : "GET",
headers : [..],
url : "/users/id1"
},
{
method : "GET",
headers : [..],
url : "/users/id2"
}
]
Server will reply URI of newly created batchtask resource.
201 Created
Location: "http://example.com/api/batchtask/1254"
Now client can fetch batch response or task progress by polling
GET http://example.com/api/batchtask/1254
This is how others attempted to solve this issue:
Google Drive
Facebook
Microsoft
Subbu Allamaraju
I find another way of doing the same thing by using #PathParam. Here is the code sample.
#GET
#Path("data/xml/{Ids}")
#Produces("application/xml")
public Object getData(#PathParam("zrssIds") String Ids)
{
System.out.println("zrssIds = " + Ids);
//Here you need to use String tokenizer to make the array from the string.
}
Call the service by using following url.
http://localhost:8080/MyServices/resources/cm/data/xml/12,13,56,76
where
http://localhost:8080/[War File Name]/[Servlet Mapping]/[Class Path]/data/xml/12,13,56,76
As much as I prefer this approach:-
api.com/users?id=id1,id2,id3,id4,id5
The correct way is
api.com/users?ids[]=id1&ids[]=id2&ids[]=id3&ids[]=id4&ids[]=id5
or
api.com/users?ids=id1&ids=id2&ids=id3&ids=id4&ids=id5
This is how rack does it. This is how php does it. This is how node does it as well...
There seems to be a few ways to achieve this. I'd like to offer how I solve it:
GET /users/<id>[,id,...]
It does have limitation on the amount of ids that can be specified because of URI-length limits - which I find a good thing as to avoid abuse of the endpoint.
I prefer to use path parameters for IDs and keep querystring params dedicated to filters. It maintains RESTful-ness by ensuring the document responding at the URI can still be considered a resource and could still be cached (although there are some hoops to jump to cache it effectively).
I'm interested in comments in my hunt for the ideal solution to this form :)
You can build a Rest API or a restful project using ASP.NET MVC and return data as a JSON.
An example controller function would be:
public JsonpResult GetUsers(string userIds)
{
var values = JsonConvert.DeserializeObject<List<int>>(userIds);
var users = _userRepository.GetAllUsersByIds(userIds);
var collection = users.Select(user => new { id = user.Id, fullname = user.FirstName +" "+ user.LastName });
var result = new { users = collection };
return this.Jsonp(result);
}
public IQueryable<User> GetAllUsersByIds(List<int> ids)
{
return _db.Users.Where(c=> ids.Contains(c.Id));
}
Then you just call the GetUsers function via a regular AJAX function supplying the array of Ids(in this case I am using jQuery stringify to send the array as string and dematerialize it back in the controller but you can just send the array of ints and receive it as an array of int's in the controller). I've build an entire Restful API using ASP.NET MVC that returns the data as cross domain json and that can be used from any app. That of course if you can use ASP.NET MVC.
function GetUsers()
{
var link = '<%= ResolveUrl("~")%>users?callback=?';
var userIds = [];
$('#multiselect :selected').each(function (i, selected) {
userIds[i] = $(selected).val();
});
$.ajax({
url: link,
traditional: true,
data: { 'userIds': JSON.stringify(userIds) },
dataType: "jsonp",
jsonpCallback: "refreshUsers"
});
}