When working with RESTful web services, verifying response headers is an essential part of testing API endpoints. Headers often provide critical metadata about the response, including content type, encoding, caching directives, or server-specific information. In this blog post, we’ll learn how to verify JSON response headers using Rest Assured, a popular Java library for API testing.
Why Verify Response Headers?
Validating response headers ensures:
- Compliance: APIs follow proper standards and return expected headers (e.g.,
Content-Type
should match the format of the body). - Security: Headers like
CORS
,Authorization
, andContent-Security-Policy
should be correctly set. - Performance: Headers like
Cache-Control
orETag
influence caching and reduce redundant API calls.
Setting Up Rest Assured
To start, ensure you’ve added the Rest Assured dependency in your pom.xml
:
<dependency>
<groupId>io.rest-assured</groupId>
<artifactId>rest-assured</artifactId>
<version>5.3.0</version>
<scope>test</scope>
</dependency>
Sample API Response
Let’s consider a sample JSON API endpoint:GET https://jsonplaceholder.typicode.com/posts/1
Sample JSON Response:
Verifying JSON Response Headers
Here’s how you can validate specific response headers using Rest Assured:
Basic Header Validation
Extracting and Validating Headers
If you need to perform more advanced validations or reuse header values, you can extract headers using the Response
object:
import io.restassured.response.Response;
import static io.restassured.RestAssured.*;
public class ExtractHeaderTest {
public static void main(String[] args) {
baseURI = "https://jsonplaceholder.typicode.com";
Response response = given()
.when()
.get("/posts/1");
// Extract and print headers
String contentType = response.getHeader("Content-Type");
String cacheControl = response.getHeader("Cache-Control");
System.out.println("Content-Type: " + contentType);
System.out.println("Cache-Control: " + cacheControl);
// Perform validations
assert contentType.equals("application/json; charset=utf-8");
assert cacheControl.contains("public");
}
}
Advanced Header Assertions
Validate All Headers
You can validate multiple headers at once using the headers()
method:
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
public class MultipleHeadersValidationTest {
public static void main(String[] args) {
baseURI = "https://jsonplaceholder.typicode.com";
given()
.when()
.get("/posts/1")
.then()
.assertThat()
.headers("Content-Type", "application/json; charset=utf-8",
"Cache-Control", containsString("public"),
"ETag", notNullValue());
}
}
Use Hamcrest Matchers
Rest Assured supports Hamcrest matchers for more complex validations. For example: