REST Assured Create JSON Body Using HashMap

Profile picture for user arilio666

In real world scenario when payload is dynamic or it contains many key-value pairs it is not the good idea to hard code them in Body or pass them in the form of a string.Today we are gonna discuss an alternate solution for it using java hash map. We will be sending a java mapped key-value pair data as a JSON payload via REST ASSURED to a rest API service.

An Example Of The Sample JSON Payload Of Gorest Site which you will pass as a HashMap:

{
    "gender": "Male",
    "name": "Harry Potter",
    "email": "hoggwarts@wiz.com",
    "status": "active"
}

For demo we will be using the rest API testing site called https://gorest.co.in/

You can view pom.xml for our project here

Example : Rest Assured HashMap

Note: Please generate your own Bearer token from gorest website this will not work for you. 

private void JsonBodyHashMap()
{
    HashMap<String,Object> dataBody = new HashMap<String,Object>();
        
    dataBody.put("name", "Harry Potter");
    dataBody.put("email", "hoggwarts22@wiz.com");
    dataBody.put("gender", "Male");
    dataBody.put("status", "active");
        
    RestAssured
        .given()
            .header("Authorization","Bearer c005c96081fd4f9205d53b5f0e8d0aab4eac0c63ad282de7aeda1f2b2fd0bdc6")
            .baseUri("https://gorest.co.in/public/v1/users/")
            .contentType(ContentType.JSON)
            .body(dataBody)
            .log()
            .body()
       .when()
           .post()
        .then()
            .assertThat().statusCode(201)
            .log().body();
}

Output:

Body:
{
    "gender": "Male",
    "name": "Harry Potter",
    "email": "hoggwarts24@wiz.com",
    "status": "active"
}
{
    "meta": null,
    "data": {
        "id": 4400,
        "name": "Harry Potter",
        "email": "hoggwarts24@wiz.com",
        "gender": "male",
        "status": "active"
    }
}
  • Here We have used the hashmap to add some data according to the JSON structure of the go rest API site.
  • As you can see after adding the respective fields of data for the POST request We have called the rest assured and set the bearer token as the site needs that to POST requests.
  • So after that, we have passed the data body-mapped object as JSON body which will ultimately be taken as JSON body and will post.

The above example is the basic one, in next article we will discuss similar example with more complex and nested JSON.