Rest Assured
Rest Assured is a powerful library for API testing in Java. It provides a simple and
intuitive DSL (Domain Specific Language) for making HTTP requests and validating
responses. Below are some of the built-in methods and features of Rest Assured for API
testing.
Basic Setup
First, include Rest Assured in your project dependencies. If you're using Maven, add the
following to your pom.xml:
xml
Copy code
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
Basic Usage
Here are some of the key methods and how to use them:
1. Making a GET Request
java
Copy code
import io.restassured.RestAssured;
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
Response response = given()
.when()
.get("/posts/1")
.then()
.statusCode(200)
.extract()
.response();
System.out.println(response.asString());
}
}
2. Making a POST Request
java
Copy code
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
public static void main(String[] args) {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
given()
.header("Content-type", "application/json")
.body("{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }")
.when()
.post("/posts")
.then()
.statusCode(201)
.body("title", equalTo("foo"))
.body("body", equalTo("bar"))
.body("userId", equalTo(1));
}
}
3. Making a PUT Request
java
Copy code
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
public static void main(String[] args) {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
given()
.header("Content-type", "application/json")
.body("{ \"id\": 1, \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }")
.when()
.put("/posts/1")
.then()
.statusCode(200)
.body("title", equalTo("foo"))
.body("body", equalTo("bar"))
.body("userId", equalTo(1));
}
}
4. Making a DELETE Request
java
Copy code
import io.restassured.RestAssured;
import static io.restassured.RestAssured.*;
public class ApiTest {
public static void main(String[] args) {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
given()
.when()
.delete("/posts/1")
.then()
.statusCode(200);
}
}
Validating Responses
Rest Assured provides several methods to validate the response:
1. Validating Status Code
java
Copy code
given()
.when()
.get("/posts/1")
.then()
.statusCode(200);
2. Validating Response Body
java
Copy code
given()
.when()
.get("/posts/1")
.then()
.body("userId", equalTo(1))
.body("id", equalTo(1))
.body("title", equalTo("sunt aut facere repellat provident occaecati excepturi
optio reprehenderit"));
3. Validating Headers
java
Copy code
given()
.when()
.get("/posts/1")
.then()
.header("Content-Type", "application/json; charset=utf-8");
4. Validating Cookies
java
Copy code
given()
.when()
.get("/posts/1")
.then()
.cookie("cookie_name", "cookie_value");
Query Parameters
java
Copy code
given()
.queryParam("userId", 1)
.when()
.get("/posts")
.then()
.statusCode(200);
Path Parameters
java
Copy code
given()
.pathParam("postId", 1)
.when()
.get("/posts/{postId}")
.then()
.statusCode(200);
JSON Path
You can extract values from the JSON response using JSON Path.
java
Copy code
Response response = given()
.when()
.get("/posts/1")
.then()
.statusCode(200)
.extract()
.response();
int userId = response.path("userId");
System.out.println("User ID: " + userId);
XML Support
Rest Assured also supports XML response validation.
java
Copy code
given()
.accept("application/xml")
.when()
.get("/path/to/xml/endpoint")
.then()
.statusCode(200)
.body("response.element", equalTo("value"));
Authentication
Basic Authentication
java
Copy code
given()
.auth()
.preemptive()
.basic("username", "password")
.when()
.get("/secure-endpoint")
.then()
.statusCode(200);
OAuth 2.0 Authentication
java
Copy code
given()
.auth()
.oauth2("your_access_token")
.when()
.get("/secure-endpoint")
.then()
.statusCode(200);
Advanced Features
Request Specification
You can define common settings using RequestSpecification.
java
Copy code
RequestSpecification requestSpec = new RequestSpecBuilder()
.setBaseUri("https://jsonplaceholder.typicode.com")
.setContentType(ContentType.JSON)
.build();
given()
.spec(requestSpec)
.when()
.get("/posts/1")
.then()
.statusCode(200);
Response Specification
You can also define common response validations using ResponseSpecification.
java
Copy code
ResponseSpecification responseSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.build();
given()
.when()
.get("/posts/1")
.then()
.spec(responseSpec);
Example: Complete Test Class
java
Copy code
import io.restassured.RestAssured;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import io.restassured.specification.ResponseSpecification;
import io.restassured.builder.RequestSpecBuilder;
import io.restassured.builder.ResponseSpecBuilder;
import io.restassured.http.ContentType;
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class ApiTest {
private static RequestSpecification requestSpec;
private static ResponseSpecification responseSpec;
public static void main(String[] args) {
RestAssured.baseURI = "https://jsonplaceholder.typicode.com";
// Setup Request Specification
requestSpec = new RequestSpecBuilder()
.setBaseUri(RestAssured.baseURI)
.setContentType(ContentType.JSON)
.build();
// Setup Response Specification
responseSpec = new ResponseSpecBuilder()
.expectStatusCode(200)
.expectContentType(ContentType.JSON)
.build();
// GET Request
getExample();
// POST Request
postExample();
// PUT Request
putExample();
// DELETE Request
deleteExample();
}
public static void getExample() {
given()
.spec(requestSpec)
.when()
.get("/posts/1")
.then()
.spec(responseSpec)
.body("userId", equalTo(1))
.body("id", equalTo(1))
.body("title", equalTo("sunt aut facere repellat provident occaecati excepturi
optio reprehenderit"));
}
public static void postExample() {
given()
.spec(requestSpec)
.body("{ \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }")
.when()
.post("/posts")
.then()
.statusCode(201)
.body("title", equalTo("foo"))
.body("body", equalTo("bar"))
.body("userId", equalTo(1));
}
public static void putExample() {
given()
.spec(requestSpec)
.body("{ \"id\": 1, \"title\": \"foo\", \"body\": \"bar\", \"userId\": 1 }")
.when()
.put("/posts/1")
.then()
.spec(responseSpec)
.body("title", equalTo("foo"))
.body("body", equalTo("bar"))
.body("userId", equalTo(1));
}
public static void deleteExample() {
given()
.spec(requestSpec)
.when()
.delete("/posts/1")
.then()
.statusCode(200);
}
This example covers the basic and advanced usage of Rest Assured for API testing. You
can further customize and expand upon these methods to fit your specific testing
needs.
THE END