Ads

Rest Assured Api Automation

 

1. What is Rest Assured, and why is it used?

Answer: Rest Assured is a Java library used for testing RESTful APIs. It simplifies the process of sending HTTP requests, verifying responses, and automating API testing. Rest Assured provides a domain-specific language (DSL) for writing expressive tests, making it easier to test APIs without requiring extensive knowledge of HTTP.

GEt method:

RestAssured.BaseURI="https://jsonplaceholder.typicode.com/"; RequestSpecification reqSpec=RestAssured.given().accept(Contenttype.json).auth(). basicAuth("username","password").pathParam("sangar","kumar").header("Content-Type","application/json"); Response response=reqSpec.get("/sangar"); sysout(response.asString()); sysout(response.asPrettyString()); Assert.assertEquals(response.statusCode(),200,"Sangar bro"); Assert.assertTrue(response.statusMessage().contains("ok"));

Post Method:

Response response=RestAssured.given().baseURI("https://ai-translate.p.rapidapi.com").basePath("translate") .auth().basic(username,password) or digestAuth(username,password) or preemptive().basic(username,password) or oauth2("token") .header("content-type","application/json").header("Authorization","Bearer token"). .pathParam("sangar","sangar").pathParam("sangar","sangar") .queryParam("sangar","kumar").queryParam("sangar").headers("Co") .body(jsonBofy).when().request(Method.POST); response.statusCode() response.getHeaders() response.getCookies()

Put method:

RestAssured.given().baseURI().auth().basic().headers(new Headers(Arrays.asList(heade))) .pathParam().queryParam().body(json).put();

 

Delete method:

RestAssured.given().baseURI().header("Autherization","Bearer toke").delete("/post-1");

 

Validation of response:

Assert.assertNotNull(response.jsonPath().get("data.id"));

Method Chaining:

In pojo put return statement in setter,then we can perform method chaining.

public class Pojo{ private String sangar; private String kumar; public Pojo setSangar(String sangar){ this.sanga=sangar; return this; } public Pojo setKumar(String kumar){ this.kumar=kumar; return this; } } class mainClass{ main(){ Pojo poj=new Pojo(); poj.setSangar("SAngar").setKumar("Kumar"); } }

 

Serialisation:

is the process of converting java object into json object.

we can say,it is the process of converting a data object into a byte stream and saving the state of the object to be stored on disk or transmitted across a network.

jackson databind or gson

ObjectMapper mapper=new Objct Mapper(); String value=mapper.writerwithDefaultPrettyPrinter().writeValueAsString(pojoObject);

JSON Schema Validation:

1.Using Json schema validator 5.5.0(same from Rest Assured Library)

RestAssured.given().baseURI("Sangar").basePath("/sangar") .header("Content-Type","application/json") or header("Authorization","Bearer token") .auth().basic(username,password) or digest(username,password),oauth(consumer key,consumersecreat,access token,secret token) .oauth2(key).body(file).request(Method.POST,"/sangar").then().body(JSOnSchemaValidator.matchesJSonSchema or matchesJSonSchemainClassPath(file));

2.using networkNT

Response respone=RestAssured.given().get(); File file=new File("Sceham.json"); ObjectMapper mapper=new ObjectMapper(); JSONNode node=mapper.readTree(response.asstring()); JsonSchemaFactory factory=JSONSCHEMAFActory.getInstance(VersionFlag.v4); JSONSchema schema=factory.getSchema(new FileInputStream(file)); Set<ValidationMessage> mes=schema.validate(node); if(mes.isEmpty()){ sysout("no errors"); }else{ for(ValidationMEssage me:mes){ sysout(me.getMessage()) } }

using HamcrestMatchers:

 

Response response=RestAssured.given().post(); File file=new File("schema.json"); String response=response.asString(); String fileString=FileUtils.readFileToString(file,"UTF-8"); MatcherAssert.assertThat(response,JSONSChemaValidator.matchesJSONSchema(fileString));

Sample jsonSchema:

{ "$Schema":"json-schema-2019/schema", "type":"object", "required":[ "ground", "sangar", "sangaran" ], "properties":{ "ground":{ "type":"string", "title":"sangar", "default":"" }} }

JSON Path:

  • using jayway json path

  • using rest assured json path

JSON Path terminologies:

whole data--->Qeury--->subset of data

  • notations:

    • Bracket,dot

  • Expression:

    • Query

  • Predicate:

    • Conditions like yes or no

  • Filters:

    • logical operations

  • {}--->Dictionary

  • []---->List

 

Notations:

  • $------------>to indicate the root Element

  • . or []---->indicate the child element

  • @ ---->indicate the current element

  • * ------------->wild card..All eliminates

  • .. ----->deep scan

  • [start:end]----->slicing the array

  • [?(<Expression>)]-------->Filter Expression.The result of this should be a boolean one(for json path)

Sample JSON for Play json path:

{ "firstName": "John", "lastName": "doe", "age": 26, "address": { "streetAddress": "naist street", "city": "Nara", "postalCode": "630-0192" }, "phoneNumbers": [ { "type": "iPhone", "number": "0123-4567-8888" }, { "type": "home", "number": "0123-4567-8910" } ], "heros": [ { "type": "iPhone", "name":"SAngar", "age":40, "sangar":[{ "age":25 }], "number": "0123-4567-8888" }, { "type": "home", "name":"SAngar", "age":25, "number": "0123-4567-8910" }, { "type": "iPhone", "name":"Ayyappan", "age":30, "number": "0123-4567-8888" }, { "type": "home", "name":"Mugilan", "age":49, "number": "0123-4567-8910" }, { "type": "iPhone", "name":"kumaresan", "age":48, "number": "0123-4567-8888" }, { "type": "home", "name":"saminathan", "age":67, "number": "0123-4567-8910" } ] }
  • $.firstName--------->[“John"]

  • $.lastName------>[ "doe"]

  • $.address.city----------->[ "Nara"] or $[“address”][“city”]

  • $.*------------>returns all values only

  • $.heros.[?(@.age>30)] ------->returns object which has age > 30

  • $.heros[0:].sangar[?(@.age>22 && @.name =~ /.*ayya.*/)] ------------>add operations

  • [0:3]------->here 0 is inclusing,3 is exclusive

  • [:3]------>from beginning to 2

  • [0:]------>till last element

  • [1]--->only first

  • [-1]---->last value only

  • [-2]--->second last value

  • [1:1]--->empty

  • [0:-1]--->empty,right to left not possible

  • [-1:1]--->last and first value

JSONPath:

1.using normal

using jayway json path Configuration config=Configuration.defaultConfiguration(); List<Object> obj=JSONPath.using(config).parse(jsonFile). read("$.phoneNumbers[?(@.type =~ /.*hom.*/)].number");

2.using Predicates:

1.inline,filter,customized predicates

Inline:

$.phoneNumbers[?(@.type=='home' && @.name=='sangar')]
$.phoneNumbers[?(!(@type=='home'))]

Filter Predicate:

Configuration config=Configuration.defaultConfiguration(); Filter filter=Filter.filter(Criteria.where('teamName').contains('ndia')); List<Object> obj=JSONPath.using(config).parse(response.asSString).read("$.list.[?]",filter); for(Object ob;obj){ sysout(ob); }

Custom Predicate:

Predicate prd=(ctx)->ctx.item(Map.class).containsKey('teamName'); List<Map<String,Object>> mp=JsonPath.using(config).parse(response.asString).read("$.list.[?]"); for(Map<String,Object> ob:mp){ String string=(String)mp.get('teamName'); if(string.contains('ndi')){ sysout(mp) } }

 

Configurations:

We can modify the exceptions like path not found exception.,.whenever the path is incorrect we can modify the configurations

Configuration confi=Configuration.defaultConfiguration(); confi.addOptions(Option.Always_Return_List); confi.addOptions(Option.Default_Path_Leaf_to_Null); confi.addOptions(option.suppressExceptions); confi.addOptions(Option.requireProperties); List<Object> list=JSONPath.using(config).parse(resonse.asString()).read("$.list[?]",filter);

Eliminate Boilder plate Code:

USing Lambok, install it on machine and add dependency
in every pojo class @Getters @Setters in class level it automatically do the ssetters getters work if we mention variable level getter setter only work for those variables

Getters,Setters:

Getters internally calls setters,Similarly setters internally calls Getters.

 

Request Specification:

RequestSpecBuilder builder=RequestSpecBuilder(); builder.setBaseURI("https://"); builder.setBasePath("sangar"); builder.addHeader("Content-Type","application/json"); RequestSpecification spec=builder.build(); Response response=RestAssured.given().spec(spec).request(Method.POST,"international"); sysout(response.asString());

DeSerialisation:

  1. using ObjectMapper

  2. ObjectMapper mapper=new ObjectMapper(); Employee employee=mapper.readValue(response.asString(),Employee.class); sysout(employee.getFirstName()); sysout(employee.getLastName())

2.Using jayway json

JAckSonMappingProvider provider=new JAckSonMappingProvider(); Configuration config=Configuration.builder().mappingProvider(provider).build(); Pojo pojo=JsonPath.using(config).parse(response.asString()).read("$",Pojo.class); sysout(pojo.getFirstName());

3.Using Rest Assured json path:

Pojo pojo=response.jsonPath().getObject("$",Pojo.class); sysout(pojo.getFirstname());

4.using as Function

Map<String,Object> mp=response.body().as(new TypeRef<Map<String,Object>> (){}); sysout(mp.get("name"));

Authentication:

Basic auth:

RestAssured.given().auth().preembtive().basic(username,password);

Digest auth:

RestAssured.given().auth().digest(username,password)

API Key:

RestAssured.given().basePath("https://ww.affafa/kmafm{API_KEY}")or .queryParam("appId","value");

Bearer Token:

RestAssured.given().Header("Authorization","Bearer token");

OAuth:

RestAssured.given().auth().oauth(consumerkey,consumer secret,accesstokn,secret token);

OAuth2.0:

RestAssured.given().auth().oauth2(key,OAuthSignature)

 

 

Jackson DataBind Annotations:

  • JSONAnyGetter--->used to serialise map

    • Use case: whenever we try to serial lise map,map object also put as a key.to avoid that we are usiong jsonanygetter annotation on top over of getter method

    • before annotation { "mp" : { "SAngar" : "Gunasekaran", "kumaresan" : "Gunasekaran" } }

After Annotation:

public class pojo{ private Map<STring,String> mp; @JSONAnyGetter public Map<String,String> getMp(){ } Setter(){} }
After JSONAnyGetter Annotation: { "SAngar" : "Gunasekaran", "kumaresan" : "Gunasekaran" }
  • JSONANySetter:

  • Used to deserialise map

  • class pojo{ private Map<STring,Object> mp=new HashMap<String,Object>(); public Map<String,Object> getMp(){ return mp} @JsonAnySetter() public void setMap(String key,Object Value){ mp.put(key,value); } }
String mp={"firstname":"sangar"}; ObjectMapper mapper=new ObjectMapper(); Pojo pojo=mapper.readValue(mp,Pojo.class); sysout(pojo.getMp());
  • JSONGetter:

  • used to adding some Prefix text during getting value or replacing with new value

  • class pojo{ private String name; @JSonGetter(value="FullName") public String getName(){ } class main(){ SimplePojo sim=new SimplePojo(); sim.setFull("Sangar"); sim.setSangar("Gunas"); ObjectMapper mapper=new ObjectMapper(); String writeValueAsString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(sim); System.out.println(writeValueAsString); } } Output: { "sangar" : "Gunas", "NotFullName" : "Sangar" }
  • JSOnSetter:

  • same like json getter,but used to set new value for during deserialisation

  • private String sangar; private String full; public String getSangar() { return sangar; } public void setSangar(String sangar) { this.sangar = sangar; } public String getFull() { return full; } @JsonSetter(value = "NotFullName") public void setFull(String full) { this.full = full; } class Actual{ String s="{\r\n" + " \"sangar\" : \"Gunas\",\r\n" + " \"NotFullName\" : \"Sangar\"\r\n" + "}"; ObjectMapper mapper=new ObjectMapper(); SimplePojo writeValueAsString = mapper.readValue(s, SimplePojo.class); System.out.println(writeValueAsString.getFull()); }
  • JSONPropertyOrder: & with Alphabetic=true

    • used to maintain the order of sequence in json.

    • if it has jsongetter or jsonsetter annotation new value will be considered

    • @JsonPropertyOrder(alphabetic = true) or @JsonPropertyOrder({"name","Sangar","sangar2"}) public class pojo{}

JSONCReator with JSONProperty:

incase if we didnt have setter to use jsonsetter annotation we can create like this

public class SimplePojo { private String sangar; private String full; private String guna; private String velu; @JsonCreator public SimplePojo( @JsonProperty(value="FullSangarBro") String sangar, @JsonProperty(value="FullName") String full, @JsonProperty(value="FullGuna") String guna, @JsonProperty(value="FullVelu") String velu) { super(); this.sangar = sangar; this.full = full; this.guna = guna; this.velu = velu; }

JSONRAwValue:

used to return the raw value

{ "FullSangarBro":["Gunasekanar","kuamsad"], } @JsonRawValue private String[] sangar;

JSONValue:

if any value annotated with json value,that value only present in json.

@JsonValue public String getSangar() { return sangar; }

JSONRootName:

used to insert the root element in the json

@JsonRootName(value="SangarWhole") public class SimplePojo {
ObjectMapper mapper=new ObjectMapper(); mapper.enable(SerializationFeature.WRAP_ROOT_VALUE); String writeValueAsString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(po); System.out.println(writeValueAsString);

Jackson inject:

if json has only two values but pojo has three values

public class Pojo{ @JacksonInject private String newValue; getters,setters }
String s="{"firstvalue":"sangar","lastname":"finally"}; InjectableValues values=new InjectableValues.std().addValue(String.class,"sangar"); ObjectMapper map=new ObjectMapper(); Pojo pojo=map.reader(values).readValue(s,Pojo.class); sysout(pojo.getNewValue());

@JsonAlias

Used to mention more number alternate words to specific variable.

@JsonAlias({"newSangar","anotherSangar","pudhuSangar"}) private String sangar;

JSOnIgnore &jsonignoreProperties

JSONIgnore:

used to ignore the particular Values

JSONIgnoreProperties:

used to ignore more properties.in class level

JSONInclude:

used to include non null values,non

empty values

JsonInclude(Include.NON_NULL)

JSONInclude(INCLUDE.NON_EMPTY)

JSONIcnlude(INCLUDE>NON_default)

 

Requestspec value Retrieve:

QueriableRequestSpecification query=SpecificationQuerier.query(spec);

query.getBasePath();

query.getBaseURI();

query.getHeaders();

 

RestAssured.log().all():

used to show all logs.in above case it shows all request method,headers,uri everything

 

compare Two jsons:

JSONNode node=mapper.readTree(stringJson);

node.equals(node2);

 

Comparision:

JSONAssert.assertEquals(expectedJson, actualJson, JSONCompareMode.STRICT);

 

 

Custom Serialiser:

@JSONSerialiser class Pojo{ }
class customeSerialiser extends stdSerialise<pojo.class>{ public customeSerialiser (class<Pojo> p){ super(t); } public customeSerialiser (){ this(null); } @override public void serialise(Pojo pojo,JSONGenerator gen){ gen.writeStartObject(); gen.writeStringField("sangar","assnka"); gen.writeStringField("saknk","safnjn") gen.writerEndObject()} } class main(){ SimpleModule mod=new SimepleModule(); mod.addSerialiser(Pojo.class,new CustomSerialiser()); ObjectMapper mapper=new ObjectMapper(); mapper.registerModule(mod); String str=mapper.writerwithDefaultPrettyPRinter().writeValueAsString(); }

Comments

Popular posts from this blog

Appium Notes

Jenkins Notes