REST Assured is a Java-based library that simplifies testing RESTful APIs by providing a domain-specific language (DSL) for writing readable and maintainable tests. It is widely used for automating API testing, allowing developers and testers to validate the correctness, performance, and behavior of APIs effortlessly.
Supports RESTful API Testing:
Simple and Readable Syntax:
Built-In HTTP Methods:
GET, POST, PUT, DELETE, PATCH, etc.JSON and XML Support:
Built-In Assertions:
Authentication Support:
Integration with Testing Frameworks:
Support for Parameterization:
Custom Filters:
Simplifies Testing:
Minimal Boilerplate Code:
Comprehensive API Validation:
Wide Format Compatibility:
Flexibility:
Here is a basic example of using REST Assured to test a RESTful API:
Add the REST Assured dependency to your Maven project:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.x.x</version> <!-- Use the latest version -->
<scope>test</scope>
</dependency>
Simple and Readable Syntax:
given(), when(), and then() syntax improves code readability and organization.Comprehensive API Testing:
GET, POST, PUT, DELETE, PATCH, etc., enabling end-to-end testing of RESTful APIs.Supports JSON and XML:
Authentication Mechanisms:
Seamless Integration:
Efficient Assertions:
assertThat().statusCode(200).body("key", equalTo("value")).Custom Filters:
Reusable Code:
Free and Open-Source:
Active Community Support:
Java-Specific:
Dependency Management:
Limited to RESTful APIs:
Steep Learning Curve for Non-Programmers:
No Built-In Reporting:
Performance Testing Limitations:
Log Management:
Thread Safety Concerns:
Complex Setup for Advanced Use Cases:
Limited Support for API Mocking:
import io.restassured.RestAssured;
import io.restassured.response.Response;
public class StatusCodeValidation {
public static void main(String[] args) {
Response response = RestAssured.get("https://api.example.com/resource");
int statusCode = response.getStatusCode();
// Validate the status code
if (statusCode == 200) {
System.out.println("Status code is 200: OK");
} else {
System.out.println("Unexpected status code: " + statusCode);
}
}
}? import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class RestAssuredExample {
public static void main(String[] args) {
// Base URI
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
// Perform a GET request and validate the response
given()
.log().all() // Log request details
.when()
.get("/posts/1") // Send GET request to /posts/1
.then()
.log().all() // Log response details
.assertThat()
.statusCode(200) // Verify the status code is 200
.body("id", equalTo(1)) // Verify the JSON field 'id' is 1
.body("title", notNullValue()); // Verify the title is not null
}
}? import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class PostRequestExample {
public static void main(String[] args) {
given()
.header("Content-Type", "application/json") // Set Content-Type
.body("{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }") // Set request body
.when()
.post("https://jsonplaceholder.typicode.com/posts") // Send POST request
.then()
.statusCode(201) // Verify the status code is 201 (Created)
.body("id", notNullValue()); // Verify the response contains an 'id'
}
}? import io.restassured.RestAssured;
import io.restassured.response.Response;
public class QueryParamExample {
public static void main(String[] args) {
Response response = RestAssured.given()
.queryParam("param1", "value1")
.queryParam("param2", "value2")
.when()
.get("https://api.example.com/resource");
System.out.println(response.getBody().asString());
}
}
?
queryParam method is used to add two query parameters to the request. JsonPath class, which allows you to parse and query JSON data.import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.path.json.JsonPath;
public class ExtractValues {
public static void main(String[] args) {
Response response = RestAssured.get("https://api.example.com/data");
JsonPath jsonPath = response.jsonPath();
String value = jsonPath.getString("key");
System.out.println("Extracted Value: " + value);
}
}?
jsonPath method is used to create a JsonPath object, which allows you to extract values using JSON path expressions. pathParam method.import io.restassured.RestAssured;
import io.restassured.response.Response;
public class PathParameterExample {
public static void main(String[] args) {
Response response = RestAssured.given()
.pathParam("userId", 1)
.when()
.get("https://jsonplaceholder.typicode.com/users/{userId}");
System.out.println(response.getBody().asString());
}
}?
pathParam method is used to set the userId path parameter. header or headers methods.import io.restassured.RestAssured;
import io.restassured.response.Response;
public class RestAssuredExample {
public static void main(String[] args) {
Response response = RestAssured.given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer your_token_here")
.get("https://api.example.com/data");
System.out.println(response.getStatusCode());
}
}?
header method is used to set the “Content-Type” and “Authorization” headers. import io.restassured.RestAssured;
import io.restassured.response.Response;
public class APILoggingExample {
public static void main(String[] args) {
Response response = RestAssured.given()
.log().all() // Log all request details
.when()
.get("https://jsonplaceholder.typicode.com/posts/1")
.then()
.log().all() // Log all response details
.extract().response();
}
}?
log().all() method is used to log all details of the request and response. given()
.auth().basic("username", "password")
.when()
.get("/secure-endpoint");
?
given()
.auth().oauth2("token")
.when()
.get("/secure-endpoint");? Response response = given().get("/endpoint");
String value = response.jsonPath().getString("field");? response.body() : Returns the response body object. response.getBody().asString() : Converts the response body to a string format.
@Test(dataProvider = "data")
public void testApi(String param1, String param2) {
given()
.queryParam("key", param1)
.when()
.get("/endpoint")
.then()
.statusCode(200);
}
given()
.config(RestAssured.config()
.httpClient(HttpClientConfig.httpClientConfig()
.setParam("http.connection.timeout", 5000)))
.when()
.get("/endpoint");
REST Assured can be seamlessly integrated into various CI/CD pipelines to automate API testing as part of your continuous integration and delivery processes. Here's a general approach and key considerations:
1. Choose a CI/CD Tool
2. Project Setup
3. CI/CD Pipeline Configuration
4. Example with Jenkins (using a Jenkinsfile)
Groovy :
pipeline {
agent any
stages {
stage('Build') {
steps {
sh 'mvn clean install'
}
}
stage('Test') {
steps {
sh 'mvn test'
}
}
stage('Report') {
steps {
// Publish test reports (e.g., using JUnit or Allure)
}
}
}
}
5. Key Considerations
Benefits of Integration
given()
.relaxedHTTPSValidation()
.when()
.get("/secure-endpoint");
/users/{id}).given()
.pathParam("id", 123)
.when()
.get("/users/{id}");
? RestAssured.filters(new RequestLoggingFilter(), new ResponseLoggingFilter());
?
import io.restassured.filter.Filter;
import io.restassured.filter.FilterContext;
import io.restassured.response.Response;
import io.restassured.specification.FilterableRequestSpecification;
import io.restassured.specification.FilterableResponseSpecification;
public class CustomFilter implements Filter {
@Override
public Response filter(FilterableRequestSpecification requestSpec, FilterableResponseSpecification responseSpec, FilterContext ctx) {
// Add a custom header
requestSpec.header("Custom-Header", "value");
// Log the request
System.out.println("Request: " + requestSpec.getMethod() + " " + requestSpec.getURI());
// Proceed with the request
Response response = ctx.next(requestSpec, responseSpec);
// Log the response
System.out.println("Response: " + response.getStatusCode());
return response;
}
}?
import static io.restassured.RestAssured.given;
public class APITest {
public void testAPI() {
given()
.filter(new CustomFilter())
.when()
.get("https://api.example.com/data")
.then()
.statusCode(200);
}
}? import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeMatcher;
public class CustomMatchers {
public static TypeSafeMatcher<String> containsSubstring(final String substring) {
return new TypeSafeMatcher<String>() {
@Override
public void describeTo(Description description) {
description.appendText("a string containing ").appendValue(substring);
}
@Override
protected boolean matchesSafely(String item) {
return item.contains(substring);
}
};
}
public static void main(String[] args) {
String response = "This is a sample response";
assertThat(response, containsSubstring("sample"));
}
}?
containsSubstring is created to check if a string contains a specific substring. import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
public static void main(String[] args) {
try {
Response response = given()
.baseUri("https://api.example.com")
.when()
.get("/endpoint")
.then()
.statusCode(200)
.body("key", equalTo("value"))
.extract()
.response();
// Additional validation
if (response.jsonPath().getString("anotherKey") == null) {
throw new AssertionError("anotherKey is missing in the response");
}
} catch (Exception e) {
System.err.println("Error occurred: " + e.getMessage());
}
}
}? <dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
<scope>test</scope>
</dependency>?
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>4.3.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.1</version>
<scope>test</scope>
</dependency>?
Next, write your test cases using REST Assured with TestNG or JUnit. Here is an example of a simple test case using TestNG :import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.testng.Assert;
import org.testng.annotations.Test;
public class ApiTest {
@Test
public void testGetRequest() {
Response response = RestAssured.get("https://jsonplaceholder.typicode.com/posts/1");
Assert.assertEquals(response.getStatusCode(), 200);
Assert.assertEquals(response.jsonPath().getString("id"), "1");
}
}?
import io.restassured.RestAssured;
import io.restassured.response.Response;
import org.junit.Assert;
import org.junit.Test;
public class ApiTest {
@Test
public void testGetRequest() {
Response response = RestAssured.get("https://jsonplaceholder.typicode.com/posts/1");
Assert.assertEquals(200, response.getStatusCode());
Assert.assertEquals("1", response.jsonPath().getString("id"));
}
}?