Sunday 24 November 2019

Rest Assured: Post Request Example


Using ‘post()’ method, we can send post request.

For example, Let's create an employee by hitting below request.

API: http://localhost:8080/api/v1/employees/
Method: POST
Request Payload:
{
         "firstName" : "Raju",
         "lastName" : "Narayana"
}

Rest Assured snippet to create employee
String payload = "{\n" + 
  " \"firstName\" : \"Raju\",\n" + 
  " \"lastName\" : \"Narayana\"\n" + 
  "}";

given().header("Accept", "application/json").header("Content-Type", "application/json")
    .body(payload).when()
    .post("api/v1/employees/")
    .then().assertThat()
    .statusCode(201).and()
    .contentType(ContentType.JSON).and()
    .body("firstName", equalTo("Raju")).and()
    .body("lastName", equalTo("Narayana"));

Above snippet create an employee and validate the response code, response payload.

TestApp.java
package com.sample.app;

import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;

import org.junit.Test;

import io.restassured.RestAssured;
import io.restassured.http.ContentType;

public class TestApp {

 @Test
 public void testApp() {
  RestAssured.baseURI = "http://localhost:8080";

  String payload = "{\n" + 
    " \"firstName\" : \"Raju\",\n" + 
    " \"lastName\" : \"Narayana\"\n" + 
    "}";

  given().header("Accept", "application/json").header("Content-Type", "application/json").body(payload).when()
    .post("api/v1/employees/").then().assertThat().statusCode(201).and().contentType(ContentType.JSON)
    .and().body("firstName", equalTo("Raju")).and().body("lastName", equalTo("Narayana"));

 }

}





Previous                                                    Next                                                    Home

No comments:

Post a Comment