Sameera De Silva
2 min readMar 2, 2022

Send Post request with Bearer token and Nested input value using Rest-Assured.

I have this API post request which creates a record.

It’s payload is as per below.

"sysId": "666666",
"plannedStart" : "02-24-2022 17:00:00",
"plannedEnd" : "02-27-2022 17:10:00",
"changeDetails" : {
"requirement" : "https:"
}
}

The the response is like below.

{
"result": {
"change": {
"sys_id": "66",
"number": "777"
},
"status": "OK",
"message": "Change Request Created Successfully"
}
}

How to achieve this in Rest Assured with Java?

Code solution is as per below.

import io.restassured.RestAssured;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.json.JSONObject;
import org.testng.annotations.Test;

public class PostRequest {
@Test
public void sendPostRequestWithBearerTokenAndNestedInput(){

RequestSpecification request = RestAssured.given();
request.header("Content-Type", "application/json");
// Mention the keys and values which wish to pass as haeders.
request.header("key", "value");
// Give the username and password.
request.auth().basic("username", "password");
// Give the bearer token.
request.header("Authorization", "Basic 66666==");

// Create Json Object to store attributes
JSONObject jsonPayloadBody = new JSONObject();

// Now let's see how to add a nested parameter. Define a object as changeDetails
JSONObject changeDetailsObject = new JSONObject();
// For inside of that , add requirement, key and value.
changeDetailsObject.put("requirement", "https");
// Attach those attributes to Body after convert them in to JsonString
request.body(jsonPayloadBody.toString());
// Post the request with URL
Response response = request.post("https://URI");
int actual_Status_Code = response.getStatusCode();
System.out.println("actualStatuscode"+actual_Status_Code);
// Assert.assertEquals(actual_Status_Code, 200, "ID does not matches in API response.");
JsonPath jsonPathEvaluator = response.jsonPath();
//Extract the ticket number.
System.out.println("Response is "+response.asString());
// Here Number is inside of result.change. So using result.change.number we can extract the value/
String ticketNumber = jsonPathEvaluator.get("result.change.number");
}
}

No responses yet