Skip to Content

What is REST assured given ()?

REST assured is a Java library that provides a domain-specific language to test RESTful web services. It is used for automation testing of REST APIs. The given() method in REST assured is used to specify the request parameters for a REST API call.

Testing REST APIs is an important part of the development process. Some key aspects of REST API testing include:

  • Functional testing – Verify the core functionality and business logic of the APIs
  • Load testing – Test the performance of APIs under different user loads
  • Security testing – Check APIs for vulnerabilities like SQL injection, XSS, etc.
  • Reliability testing – Ensure APIs behave reliably under various conditions

Manual testing of these aspects can be time-consuming and error-prone. This is where REST API automation testing frameworks like REST assured come into the picture. They help write maintainable, reusable, and robust test suites for REST APIs.

REST Assured Overview

REST assured provides a DSL (domain-specific language) in Java to simplify testing of REST services. Some key features of REST assured include:

  • Intuitive DSL for constructing requests and validating responses
  • Support for different HTTP methods like GET, POST, PUT, DELETE, etc.
  • Ability to extract and validate data from responses
  • Seamless integration with TestNG and JUnit
  • Supports asserting response status codes, headers, body content
  • Built-in support for authentication

The DSL provided by REST assured build on top of other Java libraries like Apache HTTP Client, Hamcrest, and JsonPath. But it hides away the complexity and makes writing REST API tests very easy.

REST Assured Request Specification

The starting point for any REST assured test is to create a request specification. This involves specifying the basic details like:

  • HTTP method (GET, POST, etc)
  • URL to send the request
  • Headers
  • Request parameters
  • Cookies

For example:

RequestSpecification request = RestAssured.given()
  .baseUri("https://api.example.com/")
  .header("Content-Type", "application/json")
  .cookie("sessionToken", "12345"); 

This creates a request specification that sets the base URL, header, and cookie for all requests. The cookie and header will be sent with every request using this specification.

given() method

The given() method in REST assured is used to configure the request specification and specify parameters for the request.

For example, to specify request parameters for a GET request:

given()
  .param("id", "1234")
  .param("format", "json")

This will add the query parameters “id” and “format” to the request.

For a POST request, you can specify form parameters using given():

  
given()
  .formParam("name", "John")
  .formParam("age", "20") 

To specify URL path parameters, you can do:

given()
  .pathParam("userId", "1234")

This adds a path parameter named “userId” with value 1234 to the request URL.

In summary, the given() method is used to configure:

  • Query parameters
  • Form parameters
  • Path parameters
  • Request headers
  • Cookies

for a REST API request using REST assured.

Example Request Specification

Here is an example of a complete request specification:

RequestSpecification request = RestAssured.given()
                               .baseUri("https://api.example.com")
                               .header("Content-Type", "application/json")
                               .cookie("sessionToken", "123")
                               .pathParam("userId", "1234")
                               .param("format", "json")
                               .body(jsonBody);

This creates a request specification that:

  • Sets base URL
  • Adds Content-Type header
  • Adds sessionToken cookie
  • Sets userId as path parameter
  • Adds format query parameter
  • And jsonBody as request body

Sending Request and Validating Response

Once the request specification is created using given(), you can send the request and validate the response using methods like when() and then():

when()
   .get("/users/{userId}");

then()
   .statusCode(200)
   .body("firstName", equalTo("John)); 

The when() method sends the actual GET request to “/users/{userId}”.

The then() method validates the response. Here we assert that status code returned is 200 and the “firstName” in response body equals “John”.

You can also extract values from the response using:

String userId = when()
                 .get("/users")
               .then()
                 .extract().path("id");

This makes REST API testing very easy and concise with REST assured.

Authentication

REST assured provides many options for adding authentication to requests:

given()
  .auth().basic("username","password") 

given()
  .auth().oauth2("accessToken")  

given()
  .auth().certificate("cert.pem", "key.pem")

You can use basic auth, OAuth2, SSL client certificates to authenticate requests. The credentials are added to the request specification and applied to all requests.

Common Validation Options

Some common validations you can do on the response using REST assured:

// Validate status code 
then().statusCode(200);

// Validate response header
then().header("Content-Type", "application/json");

// Validate response body
then().body("name", equalTo("John"));

// Extract value from response 
String id = then().extract().path("id");

You can easily assert on status codes, headers, body content using familiar Hamcrest matchers like equalTo(), containsString() etc. JSONPath syntax helps extract data from the response body.

Chaining Requests

REST assured also allows you to chain multiple requests together in a test scenario:

String userId = 
  given()
    .get("/users")
  .then()
    .extract().path("id");

given()
  .pathParam("userId", userId) 
.when()
  .get("/users/{userId}");  

Here we make one request to get userId, extract it, use it to make another request – all using a concise chained syntax.

Writing Reusable Test Steps

For maximizing reusability, common test steps can be extracted out into reusable methods. For example:

public void login() {

  given()
    .formParam("username", "john")
    .formParam("password", "1234")
  .when()
    .post("/login");  
}

@Test 
public void testUserProfile() {
  
  login();
  
  given()
    .pathParam("userId", "1234")
  .when()
    .get("/users/{userId}");

  // Assertions here 
}

The login steps are extracted out to a reusable method. This avoids duplicating the code in every test.

Conclusion

To summarize, REST assured provide an intuitive domain-specific language for writing automated tests for REST APIs in Java. The given(), when() and then() methods allow you to easily configure requests, send them and validate responses.

Features like extraction, chaining, authentication and reusable test steps make REST API testing very productive and maintainable using REST assured. Its concise and fluent syntax reduces code bloat in tests. REST assured is one of the most popular Java libraries for REST API test automation.