REST Assured Use Root Path

Profile picture for user devraj

To avoid duplicated paths in body expectations you can specify a root path. In below body section you can observe we are using [0].user path for every key name,screen_name and followers_count. To avoid such repetition of code we can use root path:

.body("[0].user.name", equalTo("Tarun"), "[0].user.screen_name", equalTo("tgoswami013"),"[0].user.followers_count", equalTo(10));			

Above line can be replaced with:

.rootPath("[0].user.test")
.body("name", equalTo("Tarun"), "screen_name", equalTo("tgoswami013"),"followers_count", equalTo(10));

You can also set default root path using below command, if your root is common for particular class you can use before class annotation of TestNG:

RestAssured.rootPath = "[0].user";

REST Assured - Append Root Path

In more advanced use cases it may also be useful to append additional root arguments to existing root arguments. To do this you can use the appendRoot method, for example:

For single value use:

.appendRootPath("%s",withArgs("user"))

For multiple value use dot(.) with %s and , to separate values:

.appendRootPath("%s.%s",withArgs("user","profile"))

you need to do static import for withArgs:

import static io.restassured.RestAssured.withArgs;

Rest Assured - Detach Root Path

It's also possible to detach a root. For example: To detach test from root path use below command

.rootPath("[0].user.test")
.detachRootPath("test")