Check Every Part of an HTTP Response
Check every part of an HTTP response with REST Assured, covering status codes and lines, content types, case-insensitive headers, GPath body paths, lists, Float numbers, problem details and response time.
Your account tests check for 200 and nothing else. Then a release ships where the accounts list drops its Cache-Control: no-store header, and errors come back in a shape no client can parse, while every test stays green. In this guide, you’ll check every part of a response a client relies on: status, content type, headers, body values, lists, errors and response time.
Level: Beginner · Time: 25 minutes · Part of: Module 1: Foundations, section 4
What You’ll Build
You’ll build a test class called FirstAssertionsTest with 14 tests. Together they prove that the Accounts API returns the right status, content type, headers and data, and that its errors follow a standard format.
Most tests send this request and check parts of this response:
1
2
3
4
5
6
7
8
9
GET /api/v1/accounts HTTP/1.1
Host: localhost:<port>
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-request-id: a5265961-69e5-4b7b-821a-8818ba02c86e
Cache-control: no-store
{"count":4,"accounts":[{"id":"acc-1001", ...}, ...]}
When you’re done, Maven reports 14 passing tests:
1
2
[INFO] Tests run: 14, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Check the status code and status line.
- Check the content type and headers.
- Check single values in the body.
- Check values inside a list.
- Check error responses.
- Check the response time.
What You Need
- About 25 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you can check a status code and a body field, as taught in Send Your First REST Assured Request, fill a path parameter, as taught in Take Apart a REST Assured Test, and set a base path, as taught in Control Where REST Assured Requests Go.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
FirstAssertionsTestin a newsection_04package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
FirstAssertionsTest.java) and read along. You can run it at any time with the command in Run the Tests.
Get the code: if you haven’t cloned the examples repository yet, follow the steps in Send Your First REST Assured Request.
Out of scope: this guide doesn’t cover advanced GPath, root paths or reading money as BigDecimal; they’re taught in Module 3. Request headers and query parameters appear in two tests but are taught in Module 2.
Understand Response Assertions
The problem. A client relies on much more than the status code. It needs JSON when it asks for JSON, cache headers that keep account data out of shared caches, the right values in the right places, and errors it can parse. A test that checks only 200 misses every one of those regressions.
The concept. Every check after then() takes either a plain value or a Hamcrest Matcher, and targets one part of the response:
| Part | Method | Example |
|---|---|---|
| Status | statusCode(..), statusLine(..) | statusCode(200) |
| Content type | contentType(..) | contentType(ContentType.JSON) |
| Headers | header(name, ..) | header("Cache-Control", "no-store") |
| Body | body(path, ..) | body("accounts[0].id", equalTo(..)) |
| Time | time(..) | time(lessThan(2L), TimeUnit.SECONDS) |
When to check what. Check the parts a client depends on, not every byte. An exact match on the whole body breaks on harmless changes, such as a new field.
Check what the client relies on, not only the status code.
Meet the API Under Test
This guide uses the account endpoints of the Accounts API, all under the base path /api/v1:
| Method | Path | Purpose |
|---|---|---|
GET | /accounts | List all accounts, optionally filtered |
GET | /accounts/{id} | Fetch one account |
DELETE | /accounts/{id} | Not supported; answers 405 Method Not Allowed |
The data never changes, so tests can assert exact values. GET /api/v1/accounts returns a response similar to the following, shortened to the first and last account:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-request-id: a5265961-69e5-4b7b-821a-8818ba02c86e
Cache-control: no-store
{
"count": 4,
"accounts": [
{
"id": "acc-1001",
"iban": "NL91ABNA0417164300",
"owner": "Anna de Vries",
"type": "CURRENT",
"currency": "EUR",
"balance": 1250.50,
"status": "ACTIVE",
"openedOn": "2019-04-01"
},
...
{
"id": "acc-1004",
"owner": "Emily Clarke",
"currency": "GBP",
...
}
]
}
The two accounts in between are acc-1002 (Anna de Vries, savings) and acc-1003 (Jan Jansen, blocked, with a balance of -42.10).
An unknown account gives an RFC 9457 problem details response:
1
2
3
4
5
6
7
8
9
10
HTTP/1.1 404 Not Found
Content-type: application/problem+json; charset=utf-8
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "Account acc-9999 does not exist",
"instance": "/api/v1/accounts/acc-9999"
}
Your tests check these fields:
countand theidof the first and last element ofaccounts, for lists.id,iban,status,openedOnandbalanceofacc-1001, for single values.title,statusanddetailof the problem details, for errors.
Check the Status Code and Status Line
Set Up the Test Class
Goal: create the test class, start the API and add a helper for the request that every test shares.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.javanibble.module_01.section_04;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.everyItem;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.hasSize;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.lessThan;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.notNullValue;
import com.javanibble.accounts.AccountsApi;
import io.restassured.http.ContentType;
import io.restassured.specification.RequestSpecification;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class FirstAssertionsTest {
private static AccountsApi api;
@BeforeAll
static void startApi() {
api = AccountsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification accountsApi() {
return given()
.baseUri(api.baseUri())
.port(api.port())
.basePath(AccountsApi.BASE_PATH);
}
}
What’s happening:
accountsApi()returns aRequestSpecificationwith the base URI, port and base path set, so no test repeats those three lines.- Your IDE may mark some Hamcrest imports as unused until you add the tests that need them.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Check the Status Code and Line
Goal: check the status as a number, with a matcher, and as the full status line.
1
2
3
4
5
6
7
8
9
10
11
@Test
void statusCodeAndStatusLine() {
accountsApi()
.when()
.get("/accounts")
.then()
.statusCode(200)
.statusCode(lessThan(300))
.statusLine("HTTP/1.1 200 OK")
.statusLine(containsString("OK"));
}
What’s happening:
statusCode(200)checks the exact number, andstatusCode(lessThan(300))accepts any success code.statusLine("HTTP/1.1 200 OK")checks the whole first line, including the protocol and reason phrase.statusLine(containsString("OK"))shows that every check accepts a matcher as well as a value.
Checkpoint: run FirstAssertionsTest from your IDE. One test runs and passes.
Check a Not Found Status
Goal: check that an unknown account gives 404.
1
2
3
4
5
6
7
8
@Test
void anUnknownAccountGives404() {
accountsApi()
.when()
.get("/accounts/{id}", "acc-9999")
.then()
.statusCode(404);
}
What’s happening:
- REST Assured doesn’t treat a
404as an error, so a test can expect it like any other status.
Checkpoint: run the class again. Two tests pass.
Check the Content Type and Headers
Check the Content Type
Goal: check that the response is JSON, in two ways.
1
2
3
4
5
6
7
8
9
@Test
void contentType() {
accountsApi()
.when()
.get("/accounts")
.then()
.contentType(ContentType.JSON)
.contentType("application/json");
}
What’s happening:
ContentType.JSONmatchesapplication/jsonwith any parameters, such as; charset=utf-8. It also matches any+jsontype, such asapplication/problem+json.- A string must be how the actual value starts, so
"application/json"matchesapplication/json; charset=utf-8.
Checkpoint: run the class again. Three tests pass.
A string doesn’t match a
+jsontype.contentType("application/json")fails on a problem details response withExpected content-type "application/json" doesn't match actual content-type "application/problem+json; charset=utf-8". UseContentType.JSONwhen any JSON will do.
Check Headers
Goal: check one header’s exact value and another header’s format.
1
2
3
4
5
6
7
8
9
10
@Test
void headers() {
accountsApi()
.when()
.get("/accounts")
.then()
.header("Cache-Control", "no-store")
.header("X-Request-Id", notNullValue())
.header("X-Request-Id", matchesPattern("[0-9a-f-]{36}"));
}
What’s happening:
header("Cache-Control", "no-store")checks that account data stays out of shared caches.X-Request-Idchanges on every request, sonotNullValue()checks that it’s there andmatchesPattern(..)that it looks like a UUID.
Checkpoint: run the class again. Four tests pass.
Ignore the Case of Header Names
Goal: show that header names match in any case.
The JDK server sends Cache-control and X-request-id, yet the previous test used Cache-Control and X-Request-Id:
1
2
3
4
5
6
7
8
9
@Test
void headerNamesAreCaseInsensitive() {
accountsApi()
.when()
.get("/accounts")
.then()
.header("cache-control", "no-store")
.header("CACHE-CONTROL", "no-store");
}
What’s happening:
- HTTP header names are case-insensitive, and so is REST Assured.
- Header values are still compared exactly, so
"No-Store"wouldn’t match.
Checkpoint: run the class again. Five tests pass.
Check an Echoed Header
Goal: send a header and check that the API returns it.
The API echoes the X-Correlation-Id header:
1
2
3
4
5
6
7
8
9
@Test
void aRequestHeaderIsEchoedBack() {
accountsApi()
.header("X-Correlation-Id", "test-42")
.when()
.get("/accounts")
.then()
.header("X-Correlation-Id", "test-42");
}
What’s happening:
header(..)beforewhen()adds a header to the request, andheader(..)afterthen()checks it on the response.
Checkpoint: run the class again. Six tests pass.
Check Single Values in the Body
REST Assured reads the body with GPath, the path language of Groovy. For a single object, the path is the field name.
Check Several Fields
Goal: check four fields of one account.
1
2
3
4
5
6
7
8
9
10
11
@Test
void singleValuesInTheBody() {
accountsApi()
.when()
.get("/accounts/{id}", "acc-1001")
.then()
.body("id", equalTo("acc-1001"))
.body("iban", equalTo("NL91ABNA0417164300"))
.body("status", is("ACTIVE"))
.body("openedOn", equalTo("2019-04-01"));
}
What’s happening:
- Each
body(..)call reads one field and checks it with a matcher. is("ACTIVE")means the same asequalTo("ACTIVE"); it only reads better.- JSON has no date type, so
openedOnarrives as the ISO 8601 string"2019-04-01".
Checkpoint: run the class again. Seven tests pass.
Check Several Paths in One Call
Goal: check three fields with a single body(..) call.
body(..) takes any number of path and matcher pairs:
1
2
3
4
5
6
7
8
9
10
@Test
void severalPathsInOneBodyCall() {
accountsApi()
.when()
.get("/accounts/{id}", "acc-1003")
.then()
.body("owner", equalTo("Jan Jansen"),
"status", equalTo("BLOCKED"),
"currency", equalTo("EUR"));
}
What’s happening:
- Each further path and matcher pair adds one more check.
- All pairs in one call are checked together, so a failure reports every mismatch at once. Read REST Assured Failure Messages shows this in action.
Checkpoint: run the class again. Eight tests pass.
Compare Decimal Numbers
Goal: check a decimal balance.
JSON has one number type. REST Assured reads a decimal such as 1250.50 as a Float, so the expected value needs the f suffix:
1
2
3
4
5
6
7
8
@Test
void numbersAreFloatsByDefault() {
accountsApi()
.when()
.get("/accounts/{id}", "acc-1001")
.then()
.body("balance", equalTo(1250.50f));
}
What’s happening:
1250.50fis aFloat, the type REST Assured produces, soequalTo(..)matches.- Comparing with the
double1250.50fails, as you’ll see in Make a Test Fail.
Checkpoint: run the class again. Nine tests pass.
A
Floatis fine for a first test, but it isn’t exact enough for money. Module 3 shows how to read decimals asBigDecimal.
Check Values Inside a List
For a list, GPath adds three forms to the field name:
- An index:
"accounts[0].id"reads from the first element, and"accounts[-1].id"from the last. - A collected field:
"accounts.id"collects theidof every element into a list. - A method call:
"accounts.size()"callssize()on the list.
Check the List and Its Elements
Goal: check the size of the accounts list and values inside it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Test
void valuesInsideAList() {
accountsApi()
.when()
.get("/accounts")
.then()
.body("count", equalTo(4))
.body("accounts", hasSize(4))
.body("accounts.size()", equalTo(4))
.body("accounts[0].id", equalTo("acc-1001"))
.body("accounts[-1].id", equalTo("acc-1004"))
.body("accounts.id", hasItems("acc-1002", "acc-1003"))
.body("accounts.currency", everyItem(is(notNullValue())));
}
What’s happening:
"count"reads the number the API reports;hasSize(4)and"accounts.size()"count the elements themselves."accounts[0].id"and"accounts[-1].id"read the first and last element."accounts.id"collects every id, andhasItems(..)checks that both are there, in any order.everyItem(is(notNullValue()))checks that every account has a currency.
Checkpoint: run the class again. Ten tests pass.
Filter the List
Goal: filter the list with a query parameter and check the one account left.
1
2
3
4
5
6
7
8
9
10
@Test
void queryParametersFilterTheList() {
accountsApi()
.queryParam("currency", "GBP")
.when()
.get("/accounts")
.then()
.body("count", equalTo(1))
.body("accounts[0].owner", equalTo("Emily Clarke"));
}
What’s happening:
queryParam("currency", "GBP")sends the request as/api/v1/accounts?currency=GBP.- Only
acc-1004is in GBP, so one account is left.
Checkpoint: run the class again. Eleven tests pass.
Check Error Responses
Check Problem Details
Goal: check that a 404 comes with a body the client can parse.
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void errorsAreProblemDetails() {
accountsApi()
.when()
.get("/accounts/{id}", "acc-9999")
.then()
.statusCode(404)
.contentType("application/problem+json")
.contentType(ContentType.JSON)
.body("title", equalTo("Not Found"))
.body("status", equalTo(404))
.body("detail", containsString("acc-9999"));
}
What’s happening:
contentType("application/problem+json")checks the RFC 9457 media type.contentType(ContentType.JSON)also passes, because any+jsontype counts as JSON, so body paths work on errors too.body("status", ..)reads a body field, whilestatusCode(404)checks the status line. Problem details carry both, so check both.containsString("acc-9999")checksdetailwithout depending on its exact wording.
Checkpoint: run the class again. Twelve tests pass.
Check an Unsupported Method
Goal: check that a DELETE is rejected and the response says which methods are allowed.
1
2
3
4
5
6
7
8
9
@Test
void unsupportedMethodsGive405WithAnAllowHeader() {
accountsApi()
.when()
.delete("/accounts/{id}", "acc-1001")
.then()
.statusCode(405)
.header("Allow", "GET");
}
What’s happening:
delete(..)sends aDELETErequest, which the read-only API doesn’t support.header("Allow", "GET")checks the header HTTP requires on a405, which lists the allowed methods.
Checkpoint: run the class again. Thirteen tests pass.
Check the Response Time
Set an Upper Bound
Goal: fail the test if the API takes far too long to answer.
1
2
3
4
5
6
7
8
@Test
void responseTime() {
accountsApi()
.when()
.get("/accounts")
.then()
.time(lessThan(2L), TimeUnit.SECONDS);
}
What’s happening:
time(..)checks the response time with a matcher, in the unit you choose.- The time is measured on the client, so it includes the network and the JVM.
Checkpoint: run the class again. All 14 tests pass.
Keep time limits generous. A limit of 50 ms passes on your laptop and fails on a busy CI agent. Use
time(..)to catch something badly wrong, not for performance testing.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-01 -Dtest=FirstAssertionsTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_01.section_04.FirstAssertionsTest
[INFO] Tests run: 14, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.486 s -- in com.javanibble.module_01.section_04.FirstAssertionsTest
[INFO]
[INFO] Tests run: 14, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
Change equalTo(1250.50f) to equalTo(1250.50) in numbersAreFloatsByDefault and run the command again. You should see a result similar to the following:
1
2
3
4
5
[ERROR] Failures:
[ERROR] FirstAssertionsTest.numbersAreFloatsByDefault:171 1 expectation failed.
JSON path balance doesn't match.
Expected: <1250.5>
Actual: <1250.5F>
The values look the same, but the F shows the actual value is a Float and the expected one a double. When equal-looking numbers don’t match, look at the types.
Change equalTo(1250.50) back to equalTo(1250.50f) and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Expected content-type "application/json" doesn't match actual content-type "application/problem+json; charset=utf-8" | A string content type doesn’t match a +json type | Use ContentType.JSON, or the exact type "application/problem+json" |
responseTime fails on CI but passes locally | The time limit is too tight for a busy build agent | Raise the limit; keep it at seconds, not milliseconds |
Try It Yourself
Exercise 1: Check a GBP Account
Account acc-1004 has the currency "GBP" and a balance of 980.00. Add a test called aGbpAccountHasTheRightBalance that requests it and checks the status code, the currency and the balance, using one body(..) call for both fields.
Hint
Combine the path and matcher pairs from severalPathsInOneBodyCall with the f suffix from numbersAreFloatsByDefault.
Solution
1
2
3
4
5
6
7
8
9
10
@Test
void aGbpAccountHasTheRightBalance() {
accountsApi()
.when()
.get("/accounts/{id}", "acc-1004")
.then()
.statusCode(200)
.body("currency", equalTo("GBP"),
"balance", equalTo(980.00f));
}
Exercise 2: Find the Blocked Account
The accounts list also accepts a status filter. Add a test called theBlockedFilterFindsOneAccount that requests /accounts with the query parameter status=BLOCKED. Check that the response is JSON, that count is 1, and that the only account belongs to "Jan Jansen" and has a balance of -42.10.
Hint
Start from queryParametersFilterTheList. Index into the list with accounts[0], and remember that a negative decimal is still a Float.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
void theBlockedFilterFindsOneAccount() {
accountsApi()
.queryParam("status", "BLOCKED")
.when()
.get("/accounts")
.then()
.statusCode(200)
.contentType(ContentType.JSON)
.body("count", equalTo(1))
.body("accounts[0].owner", equalTo("Jan Jansen"))
.body("accounts[0].balance", equalTo(-42.10f));
}
Summary
You built FirstAssertionsTest, which checks the status, content type, headers, body values, lists, errors and response time of the Accounts API. A release that drops a cache header or breaks the error format now turns a test red.
- Every check after
then()takes a plain value or a Hamcrest matcher, such aslessThan(300)orcontainsString("OK"). ContentType.JSONaccepts any JSON type, including+jsontypes, while a string must be how the actual value starts.- Header names are case-insensitive, so check the value, not the spelling of the name.
- GPath reads fields, indexes into lists with
[0]and[-1], collects a field across a list and calls methods such assize(). - REST Assured reads decimals as
Float, so compare them with a value such as1250.50f.
Here are the commands you used in this guide:
1
mvn test -pl module-01 -Dtest=FirstAssertionsTest
What’s Next
Next: continue with Log REST Assured Requests and Responses, which shows how to log requests and responses, all the time or only when a check fails.
The code:
- The finished test class:
FirstAssertionsTest.java - The code and run commands for this module: Module 1 README
Go deeper:
- REST Assured Usage wiki, for every way to verify a response.
- Hamcrest Matchers javadoc, for the full list of matchers.
- RFC 9457: Problem Details for HTTP APIs, for the error format the Accounts API uses.
Related guides:
- Read REST Assured Failure Messages, for how one
body(..)call reports every mismatch. - Module 3: Validating Responses in Depth, for root paths, more matchers and money as
BigDecimal.
