Showing posts with label RestAssured. Show all posts
Showing posts with label RestAssured. Show all posts

How to Make a POST Request with Rest Assured?

In previous post you've learned Rest API Testing using Rest Assured and in this below post you will learn How to Make a POST Request with Rest Assured library.In this below code uses requestSpecBuilder to make a post request. Parameter descriptions are listed below.

restAPIURL – URL of the Rest API
APIBody – Body of the Rest API. Example: {"key1":"value1","key2":"value2"}
setContentType() – Pass the "application/json", "application/xml" or "text/html" etc. headers to setContenType() method.
Authentication credentials – Pass the username and password to the basic() method or if there is no authentication leave them blank basic("","")

How to Make a POST Request with Rest Assured


public class RestAssured {


 @Test
 public void httpPostMethodTest() throws JSONException, InterruptedException {

  //Rest API's URL
  String restAPIUrl = "http://{RestAPIURL}";

  //API Body
  String apiBody = "{\"key1\":\"value1\",\"key2\":\"value2\",\"key3\":\"value3\"}";

  // Building request by using requestSpecBuilder
  RequestSpecBuilder builder = new RequestSpecBuilder();

  //Set API's Body
  builder.setBody(apiBody);

  //Setting content type as application/json
  builder.setContentType("application/json; charset=UTF-8");

  RequestSpecification requestSpec = builder.build();

  //Making post request with authentication or leave blank if you don't have credentials like: basic("","")
  Response response = given().authentication().preemptive().basic({
    username
   }, {
    password
   })
   .spec(requestSpec).when().post(restAPIUrl);

  JSONObject JSONResponseBody = new JSONObject(response.body().asString());

  //Get the desired value of a parameter
  String result = JSONResponseBody.getString({
   key
  });

  //Check the Result
  Assert.assertEquals(result, "{expectedValue}");

 }
}

REST API testing using Rest Assured

In this REST API testing using Rest Assured post, You will learn what is API and API testing, what is the little difference between SOAP and REST services, and how to test REST APIs using Rest Assured Library.


Rest API Testing using Rest Assured with Examples


What is API?


API full form is Application Programming Interface. It comprises of a set of functions that can be accessed and executed by another software systems. It is an interface between different systems and establishes interaction with systems and data exchange process.

What is API Testing?


In the modern development world, many web applications are designed based on three-tier architecture model. Those are:

1) Presentation Tier – Occupies the top level and displays information related to services available on a website ,User Interface (UI)
2) Application Tier – Also called Middle Tier or Logic Tier ,Business logic is written in this tier which is pulled from Presentation tier. It is also called Business Tier. (API)
3) Data Tier – Here information about database and data is stored and retrieved from a Database. (DB)

REST vs SOAP

REST (Representational State Transfer)


REST is an architectural style that uses simple HTTP calls for inter-machine communication. REST does not contain an additional messaging layer and focuses on design rules for creating stateless services. A client can access the resource using the unique URI and a representation of the resource is returned. With each new resource representation, the client is said to transfer state. While accessing RESTful resources with HTTP protocol, the URL of the resource serves as the resource identifier and GET, PUT, DELETE, POST and HEAD are the standard HTTP operations to be performed on that resource.

SOAP (Simple Object Access Protocol)


SOAP relies heavily on XML, and together with schema, defines a very strongly typed messaging framework. Every operation the service provides is explicitly defined, along with the XML structure of the request and response for that operation. Each input parameter is similarly defined and bound to a type: for example, an integer, a string, or some other complex object. All of this is codified in the WSDL – Web Service Description (or Definition, in later versions) Language. The WSDL is often explained as a contract between the provider and the consumer of the service. SOAP uses different transport protocols, such as HTTP and SMTP. The standard protocol HTTP makes it easier for SOAP model to tunnel across firewalls and proxies without any modifications to the SOAP protocol.

Trending Posts:



REST API Testing Using Rest Assured

What is Rest Assured?

In order to test REST APIs, I found REST Assured library so useful. It is developed by JayWay Company and it is a really powerful catalyzer for automated testing of REST-services. REST-assured provides a lot of nice features, such as DSL-like syntax, XPath-Validation, Specification Reuse, easy file uploads and with those features we will handle automated API testing much easier.

Rest Assured has a gherkin type syntax which is shown in below code. If you are a fan of BDD (Behavior Driven Development).

Rest Assured Example:

public class RestAssured{

@Test
public void appRestTest() {
given()
.contentType(ContentType.JSON)
.pathParam("name", "suresh")
.when()
.get("/restapipath/{name}")
.then()
.statusCode(200)
.body("firstName", equalTo("Suresh"))
.body("Lastname", equalTo("Narayana"));
}
}

Also, we can get JSON response as a string and send it to the JsonPath class and we can use its methods to write flexible structured tests.

public class RestAssured{

@Test
public void appJsonPathTest() {
Response res = get("/RestAPiservice/customer");
assertEquals(200, res.getStatusCode());
String json = res.asString();
JsonPath jp = new JsonPath(json);
assertEquals("rajesh@gmail.com, jp.get("email"));
assertEquals("suresh", jp.get("firstName"));
assertEquals("Narayana", jp.get("LastName"));
}
}