top of page

Welcome
to NumpyNinja Blogs

NumpyNinja: Blogs. Demystifying Tech,

One Blog at a Time.
Millions of views. 

Rest Assured Specification Class for Code Reusability

Let’s begin by understanding what is an API, API stands for Application Programming Interface that primarily focuses on data request and their corresponding response. It serves as a medium that facilitates interaction between the client and server. API uses HTTP or HTTPS protocol to communicate with JSON or XML data.


ree


 We can achieve functional API Testing with POSTMAN or Rest-Assured,

  • Postman is a platform for testing API’s

  • Rest Assured is a JAVA-based library for Testing REST API’s

 

Rest-Assured:

In API automation, Rest Assured can be integrated with popular testing frameworks such as Cucumber, TestNG, Karata DSL, and JUnit. Rest Assured is an open-source Java library that supports JSON and XML-based web service data for testing REST APIs. Rest Assured facilitates various HTTP methods like GET, POST, PUT, DELETE, PATCH, OPTIONS, and HEAD. You can pass parameters (query, path, or form), headers, and cookies along with the request, and then validate the corresponding response, including aspects such as the status code, status line, response time, content type, response body, and more.


Rest Assured Specification Builder:

As a developer or an automation tester, our primary goal is to create optimized, reusable, and scalable code. Rest Assured offers several features to achieve such goals. One such feature is the Specification builder.


In real-time, we often have multiple API request methods that have the same configurations. Instead of repeating configurations, they can be generalized and reused across all API Requests with Spec Builder.


There are two types of Spec builders in Rest Assured,

  • Request Specification builder

  • Response Specification builder


 

Need of Specification Builders:

Let’s understand the need for a Spec builder with an example,

Assume you have different Request methods like Add, Search, Update, and Delete books for Library API. If you observe closely the below request as highlighted in red font, these are some common configurations such as Base URI, header, content type & logging details that keep repeating for all the request methods. This repetitive set of code not only reduces readability but also makes maintenance difficult. This is where the Rest Assured Specification builder comes into the picture.

    
  /* ------------------- Add Book - POST ----------------------*/
    public void addBook(String payload) {
        RestAssured.given()
                .baseUri(baseURL).log().all()
                .header("Content-Type", "application/json")
                .body(payload)
                .when().post("/AddBook")
                .then().assertThat().statusCode(201);
    }
   /* --------------------- Search Book - GET ------------------- */
    public void searchBook(String id) {
        RestAssured.given()
                .baseUri(baseURL).log().all()
                .header("Content-Type", "application/json")
                .queryParam("ID", id)
                .when().get("/GetBook")
                .then().assertThat().statusCode(200);
    }
    /* -------------------- Update Book - PUT --------------------*/
    public void updateBook(String payload) {
        RestAssured.given()
                .baseUri(baseURL).log().all()
                .header("Content-Type", "application/json")
                .body(payload)
                .when().put("/UpdateBook")
                .then().assertThat().statusCode(200);
    }
    /* -------------------- Delete Book - DELETE------------------*/
    public void deleteBook(String id) {
        RestAssured.given()
                .baseUri(baseURL).log().all()
                .header("Content-Type", "application/json")
                .queryParam("ID", id)
                .when().delete("/DeleteBook")
                .then().assertThat().statusCode(200);
    }

 

Request Spec Builder:

The Request Specification interface provided by Rest Assured is used to group common configurations such as Base URI, header, content type, etc. that can be accessed across multiple Rest APIs. The build() method compiles all the configurations provided to a Request specification. This reusable specification that’s already built can be accessed across all the request methods using the spec method. The spec() method takes the request specification object as a parameter.

 

Imports required for spec builders,

               import io.restassured.builder.RequestSpecBuilder;          

    
    /* -------------- Request Specification Builder ------------------*/
   
    private RequestSpecification requestSpec = new RequestSpecBuilder()
            .setBaseUri(baseURL)
            .addHeader("Content-Type", "application/json")
            .log(io.restassured.filter.log.LogDetail.ALL)
            .build();
    
 
    /*--------------------- Add Book - POST -------------------------*/
    public void addBook(String payload) {
        RestAssured.given().spec(requestSpec)
                .body(payload)
                .when().post("/AddBook")
                .then().assertThat().statusCode(201);  
    }

Response Spec Builder:

The Response Specification interface helps us to group similar sets of assertions that are required for multiple HTTP Methods. This is achieved by consolidating common assertions to a Response Spec Builder instance, that can be reused across multiple tests for validations. The build() method compiles all the assertions and to a Response Specification. This reusable specifications can be accessed across all request methods using the spec method. The spec() method takes the response specification object as a parameter.


Imports required for spec builders,

               import io.restassured.builder.ResponseSpecBuilder; 


 /* ------------- Response Specification Builder ------------------*/
    
    private ResponseSpecification responseSpec = new ResponseSpecBuilder()
            .expectStatusCode(200)
            .expectContentType("application/json")
            .log(LogDetail.ALL)
            .build();
    /*--------------------- Search Book - GET -------------------------*/
    
    public void searchBook(String id) {
        RestAssured.given().spec(requestSpec)
                .queryParam("ID", id)
                .when().get("/GetBook")
                .then().spec(responseSpec);
    } 

 

Now, look into the below code that’s more optimized by avoiding duplicates in the code by using the Rest Assured RequestSpecBuilder and ResponseSpecBuilder features.


 
    /*--------------------- Add Book - POST -------------------------*/   
    public void addBook(String payload) {
        RestAssured.given().spec(requestSpec)
                .body(payload)
                .when().post("/AddBook")
                .then().assertThat().statusCode(201);  
    }     
    /*--------------------- Search Book - GET -------------------------*/
    
    public void searchBook(String id) {
        RestAssured.given().spec(requestSpec)
                .queryParam("ID", id)
                .when().get("/GetBook")
                .then().spec(responseSpec);
    }  
    /*--------------------- Update Book - PUT -------------------------*/
    
    public void updateBook(String payload, String id) {
        RestAssured.given().spec(requestSpec)
                .body(payload).queryParam("ID", id)
                .when().put("/UpdateBook")
                .then().spec(responseSpec);
    }
    /*--------------------- Delete Book - DELETE -------------------------*/
    public void deleteBook(String id) {
        RestAssured.given().spec(requestSpec)
                .queryParam("ID", id)
                .when().delete("/DeleteBook")
                .then().spec(responseSpec);
    }
    

 

Key Benefits of using Spec Builder:

  • Proactive Authentication:

Specification builder allows to set up authentication preemptively. We can set up authentication in a centralized way such as adding a token to request Specification, enabling requests to be authorized upfront and reused across multiple API Calls.

 

  • Centralized Configuration:

Specification builder allows to centralize common configurations like Base URI, headers, authentication and logging in one place instead of repeating them across multiple API calls, which in turn reduces code repetition and increases maintainability.

 

  • Code Reusability:

By defining instances of reusable Request Specification and Response Specifications, we can simplify multiple requests with shared configurations resulting in cleaner and more efficient code.

 

 

I hope this blog helps you to understand the Rest Assured Specification builder to create more optimized, reusable, and maintainable code.


‘If learning is an act of exploration, then technology equips the explorer for the journey of a lifetime.’

Keep learning!!!📖


 

+1 (302) 200-8320

NumPy_Ninja_Logo (1).png

Numpy Ninja Inc. 8 The Grn Ste A Dover, DE 19901

© Copyright 2025 by Numpy Ninja Inc.

  • Twitter
  • LinkedIn
bottom of page