Send Headers and Cookies in REST Assured
Send headers one by one, from a map and as objects, learn which headers are merged and which are overwritten, see the charset REST Assured adds to text content types, and send cookies.
A shared helper sets the X-Tag header on every payment request, and one test sets it again to replace it. The server receives both values. Another test posts a text/plain body, and a strict server rejects it, because the content type arrived as text/plain; charset=ISO-8859-1. In this guide, you’ll send headers, content types and cookies, and learn which values REST Assured merges, which it overwrites and which it adds for you.
Level: Beginner · Time: 20 minutes · Part of: Module 2: Building Requests, section 3
What You’ll Build
You’ll build a test class called HeadersAndCookiesTest with 12 tests. They send headers, content types and cookies to the echo endpoint, and prove what the server received.
One of the tests sends this request and checks this response:
1
2
3
4
5
6
7
8
9
GET /api/v1/echo HTTP/1.1
Host: localhost:<port>
X-Request-ID: req-1
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-request-id: req-1
{"headers":{"x-request-id":["req-1"], ...}, ...}
When you’re done, Maven reports 12 passing tests:
1
2
[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
In this guide, you will:
- Send headers.
- Control which headers are merged and which are overwritten.
- Control the charset of a content type.
- Send cookies.
What You Need
- About 20 minutes
- JDK 26 or later
- Maven 3.9 or later
- An IDE (IntelliJ IDEA, VS Code or Eclipse)
- Knowledge: you know the echo endpoint and the
paymentsApi()helper from Fill Path Parameters in REST Assured, and how the echo reports lists of values, from Send Query and Form Parameters in REST Assured.
How to Complete This Guide
You can work through this guide in one of two ways:
- Build it step by step: create
HeadersAndCookiesTestin a newsection_03package next to the classes from the previous sections, and follow every heading below. - Skip ahead: open the finished class (
HeadersAndCookiesTest.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 Fill Path Parameters in REST Assured.
Out of scope: this guide doesn’t cover checking cookies the server sends back, or shared configuration with RestAssuredConfig; they’re taught in Module 3 and Module 5.
Understand Headers, Content Types and Cookies
The problem. Headers carry what a request is about rather than its data: a request id for tracing, the media types the client accepts, the type of the body, a session cookie. Setting one is a single call, but REST Assured applies rules you can’t see in that call. Some headers collect every value you set; others keep only the last. Text content types gain a charset. And cookies share one header.
The concept. The request specification has a method for each part:
| Method | Sets |
|---|---|
header(name, ..) | One header with one or more values; also headers(map) and header(new Header(..)) |
accept(..) | The Accept header: the media types the client wants back |
contentType(..) | The Content-Type header: the media type of the body |
cookie(name, ..) | One cookie; also cookies(map) and cookie(new Cookie.Builder(..).build()) |
Setting the same header twice sends both values, except for Accept and Content-Type, where the last value wins. A text content type without a charset gets ; charset=ISO-8859-1 added. All cookies travel together in one Cookie header.
When to use each. Use accept(..) and contentType(..) rather than header(..) for those two headers, because they say what they mean. Use cookie(..) for every cookie, never a hand-written Cookie header. Turn the rules off with configuration only when an API needs it.
Know which headers REST Assured merges, overwrites or adds, and check them on the wire.
Meet the API Under Test
This guide uses the Payments API’s echo endpoint, /api/v1/echo, which accepts any method. A request with a request id, a two-value X-Tag header and two cookies returns a response similar to the following, shortened:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
HTTP/1.1 200 OK
Content-type: application/json; charset=utf-8
X-request-id: req-1
{
"method": "GET",
"path": "/api/v1/echo",
"headers": {
"accept": ["*/*"],
"cookie": ["theme=dark; lang=nl"],
"x-request-id": ["req-1"],
"x-tag": ["salary", "monthly"],
...
},
"cookies": {
"theme": "dark",
"lang": "nl"
},
"contentType": "",
...
}
Your tests check these fields:
headers, a map from each header name, in lower case, to the list of its values. HTTP header names are case-insensitive, so the echo normalises them.cookies, a map from each cookie name to its value.contentType, theContent-Typeheader exactly as the server received it.
The Payments API also copies the X-Request-ID header into every response, so a request can be traced from end to end.
Send Headers
Set Up the Test Class
Goal: create the test class, start the Payments API and add the shared request helper.
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
package com.javanibble.module_02.section_03;
import static io.restassured.RestAssured.given;
import static io.restassured.config.EncoderConfig.encoderConfig;
import static io.restassured.config.HeaderConfig.headerConfig;
import static io.restassured.config.RestAssuredConfig.config;
import static org.hamcrest.Matchers.contains;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasEntry;
import com.javanibble.payments.PaymentsApi;
import io.restassured.http.ContentType;
import io.restassured.http.Cookie;
import io.restassured.http.Header;
import io.restassured.specification.RequestSpecification;
import java.util.Map;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
class HeadersAndCookiesTest {
private static PaymentsApi api;
@BeforeAll
static void startApi() {
api = PaymentsApi.start();
}
@AfterAll
static void stopApi() {
api.close();
}
private static RequestSpecification paymentsApi() {
return given().baseUri(api.baseUri()).port(api.port()).basePath(PaymentsApi.BASE_PATH);
}
}
What’s happening:
- The lifecycle methods and the
paymentsApi()helper are the same as in the previous sections. encoderConfig,headerConfigandconfigare for the steps that change REST Assured’s default rules.HeaderandCookieare REST Assured’s objects for a header and a cookie.
Checkpoint: the class compiles. There are no tests yet, so there’s nothing to run until the next step.
Send One Header
Goal: send a request id and check it on the request and on the response.
1
2
3
4
5
6
7
8
9
10
@Test
void oneHeader() {
paymentsApi()
.header("X-Request-ID", "req-1")
.when()
.get("/echo")
.then()
.body("headers.'x-request-id'", contains("req-1"))
.header("X-Request-ID", "req-1");
}
What’s happening:
header("X-Request-ID", "req-1")adds the header to the request.- The
body(..)check reads the header the server received, in lower case. - The
header(..)check afterthen()reads a response header: the API copied the request id back.
Checkpoint: run HeadersAndCookiesTest from your IDE. One test runs and passes.
The class quotes header names that contain dashes, as in
headers.'x-request-id', so it’s clear the dashes are part of the name. In REST Assured 6.3 the unquotedheaders.x-request-idresolves to the same value.
Send Several Headers From a Map or as Objects
Goal: add headers from a map and from a Header object.
1
2
3
4
5
6
7
8
9
10
11
@Test
void severalHeadersFromAMapOrAsObjects() {
paymentsApi()
.headers(Map.of("X-Request-ID", "req-2", "X-Channel", "mobile"))
.header(new Header("X-Device", "android"))
.when()
.get("/echo")
.then()
.body("headers.'x-channel'", contains("mobile"))
.body("headers.'x-device'", contains("android"));
}
What’s happening:
headers(..)sends every map entry as a header.header(new Header(..))adds a header object. Objects are useful when headers are built in one place, such as a helper method, and used in another.
Checkpoint: run the class again. Two tests pass.
Send a Header With Several Values
Goal: send two values under one header name.
1
2
3
4
5
6
7
8
9
@Test
void aHeaderWithSeveralValues() {
paymentsApi()
.header("X-Tag", "salary", "monthly")
.when()
.get("/echo")
.then()
.body("headers.'x-tag'", contains("salary", "monthly"));
}
What’s happening:
- Extra arguments to
header(..)are extra values. REST Assured sends oneX-Tagheader per value. - The server collects both into one list, in order.
Checkpoint: run the class again. Three tests pass.
Control Which Headers Are Merged and Which Are Overwritten
See the Same Header Merged
Goal: show that setting a header twice sends both values.
1
2
3
4
5
6
7
8
9
10
@Test
void theSameHeaderTwiceIsMerged() {
paymentsApi()
.header("X-Tag", "salary")
.header("X-Tag", "monthly")
.when()
.get("/echo")
.then()
.body("headers.'x-tag'", contains("salary", "monthly"));
}
What’s happening:
- The second
header(..)call doesn’t replace the first. Both values are sent, the same as in the previous test. - This is the opening scenario: a test can’t replace a header that a helper set by setting it again.
Checkpoint: run the class again. Four tests pass.
See Accept Overwritten
Goal: show that Accept keeps only the last value.
A request has one body type, and a client usually wants one answer type, so Accept and Content-Type are the exceptions:
1
2
3
4
5
6
7
8
9
10
@Test
void acceptAndContentTypeAreOverwrittenNotMerged() {
paymentsApi()
.header("Accept", "text/plain")
.header("Accept", "application/json")
.when()
.get("/echo")
.then()
.body("headers.accept", contains("application/json"));
}
What’s happening:
- The second
Acceptvalue replaces the first, so onlyapplication/jsonis sent. Content-Typebehaves the same way: setting it twice sends only the last value.
Checkpoint: run the class again. Five tests pass.
Choose Which Headers Are Overwritten
Goal: make X-Tag keep only its last value, like Accept.
1
2
3
4
5
6
7
8
9
10
11
@Test
void headerConfigDecidesWhichHeadersAreOverwritten() {
paymentsApi()
.config(config().headerConfig(headerConfig().overwriteHeadersWithName("X-Tag")))
.header("X-Tag", "salary")
.header("X-Tag", "monthly")
.when()
.get("/echo")
.then()
.body("headers.'x-tag'", contains("monthly"));
}
What’s happening:
HeaderConfigsets which header names are overwritten instead of merged.overwriteHeadersWithName("X-Tag")addsX-Tagto that list.config(..)applies the configuration to this request only.- With it, the second
X-Tagvalue replaces the first, which fixes the opening scenario.
Checkpoint: run the class again. Six tests pass.
Use accept(..)
Goal: set Accept with its own method, and see what ContentType.JSON sends.
1
2
3
4
5
6
7
8
9
@Test
void acceptHasItsOwnMethod() {
paymentsApi()
.accept(ContentType.JSON)
.when()
.get("/echo")
.then()
.body("headers.accept[0]", equalTo("application/json, application/javascript, text/javascript, text/json"));
}
What’s happening:
accept(..)sets theAcceptheader.ContentType.JSONstands for every JSON media type REST Assured knows, so it sends all four in one value.headers.accept[0]reads the first, and only, value of the list.
Checkpoint: run the class again. Seven tests pass.
If an API is strict about
Accept, pass the one string it expects, such asaccept("application/json"), instead ofContentType.JSON.
Control the Charset of a Content Type
Send JSON Without a Charset
Goal: show that a JSON content type is sent as it is.
1
2
3
4
5
6
7
8
9
10
@Test
void jsonGetsNoCharsetAdded() {
paymentsApi()
.contentType(ContentType.JSON)
.body("{}")
.when()
.post("/echo")
.then()
.body("contentType", equalTo("application/json"));
}
What’s happening:
- JSON is always UTF-8, as RFC 8259 requires, so REST Assured adds no charset.
body("{}")sends an empty JSON object. Request bodies are the topic of the next section.
Checkpoint: run the class again. Eight tests pass.
See a Charset Added to Text
Goal: show the charset REST Assured adds to a text content type.
1
2
3
4
5
6
7
8
9
10
@Test
void textGetsTheDefaultCharsetAdded() {
paymentsApi()
.contentType("text/plain")
.body("hello")
.when()
.post("/echo")
.then()
.body("contentType", equalTo("text/plain; charset=ISO-8859-1"));
}
What’s happening:
- For text types, REST Assured adds
ISO-8859-1, the default charset of the original HTTP/1.1 specification. - Form bodies get the same charset, which is why Send Query and Form Parameters in REST Assured checks them with
startsWith(..).
Checkpoint: run the class again. Nine tests pass.
The added charset is harmless for plain ASCII, but a server that checks the content type exactly, or a body with characters outside ISO-8859-1, can trip over it. That’s the rejected
text/plainbody from the opening.
Turn the Charset Off
Goal: send a text content type exactly as you wrote it.
1
2
3
4
5
6
7
8
9
10
11
@Test
void addingTheCharsetCanBeTurnedOff() {
paymentsApi()
.config(config().encoderConfig(encoderConfig().appendDefaultContentCharsetToContentTypeIfUndefined(false)))
.contentType("text/plain")
.body("hello")
.when()
.post("/echo")
.then()
.body("contentType", equalTo("text/plain"));
}
What’s happening:
EncoderConfigcontrols how REST Assured encodes a request.appendDefaultContentCharsetToContentTypeIfUndefined(false)stops it adding the default charset.- REST Assured only adds a charset when the content type has none, so naming one yourself, as in
"text/plain; charset=UTF-8", works too.
Checkpoint: run the class again. Ten tests pass.
Send Cookies
Send One Cookie
Goal: send a cookie and check that the server received it.
1
2
3
4
5
6
7
8
9
@Test
void oneCookie() {
paymentsApi()
.cookie("theme", "dark")
.when()
.get("/echo")
.then()
.body("cookies", hasEntry("theme", "dark"));
}
What’s happening:
cookie("theme", "dark")adds a cookie to the request.cookiesis a map, sohasEntry(..)checks that it holds this name and value.
Checkpoint: run the class again. Eleven tests pass.
Send Several Cookies in One Header
Goal: send two cookies, and prove they share one Cookie header.
1
2
3
4
5
6
7
8
9
10
11
12
@Test
void severalCookiesShareOneCookieHeader() {
paymentsApi()
.cookies(Map.of("theme", "dark"))
.cookie(new Cookie.Builder("lang", "nl").build())
.when()
.get("/echo")
.then()
.body("cookies.theme", equalTo("dark"))
.body("cookies.lang", equalTo("nl"))
.body("headers.cookie.size()", equalTo(1));
}
What’s happening:
cookies(..)adds cookies from a map, andCookie.Builderbuilds a cookie object.- Both cookies travel in a single header,
Cookie: theme=dark; lang=nl.headers.cookie.size()proves it: the header has exactly one value. Cookie.Buildercan also set attributes such as the domain and path, which matter for cookies the server sends back.
Checkpoint: run the class again. All 12 tests pass.
Don’t set a cookie with
header("Cookie", ..). As soon as the request also has acookie(..), REST Assured writes its ownCookieheader and the one you set by hand is lost:header("Cookie", "session=abc")withcookie("theme", "dark")sends onlytheme=dark. Usecookie(..)for every cookie.
Run the Tests
Run the following command from the repository root:
1
mvn test -pl module-02 -Dtest=HeadersAndCookiesTest
You should see a result similar to the following:
1
2
3
4
5
6
[INFO] Running com.javanibble.module_02.section_03.HeadersAndCookiesTest
[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.451 s -- in com.javanibble.module_02.section_03.HeadersAndCookiesTest
[INFO]
[INFO] Tests run: 12, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] BUILD SUCCESS
Make a Test Fail
In headerConfigDecidesWhichHeadersAreOverwritten, delete the .config(config().headerConfig(..)) line and run the command again. You should see a result similar to the following:
1
2
3
4
5
[ERROR] Failures:
[ERROR] HeadersAndCookiesTest.headerConfigDecidesWhichHeadersAreOverwritten:113 1 expectation failed.
JSON path headers.'x-tag' doesn't match.
Expected: iterable containing ["monthly"]
Actual: <[salary, monthly]>
Without the configuration, X-Tag is merged again, so the server received both values. The Actual list shows exactly what was sent, which tells you the header wasn’t replaced.
Put the .config(..) line back and run the tests once more to confirm they pass.
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
Expected: iterable containing ["monthly"] but Actual: <[salary, monthly]> | A header set twice is merged, not replaced | Add the name with headerConfig().overwriteHeadersWithName(..) |
Expected: text/plain but Actual: text/plain; charset=ISO-8859-1 | REST Assured adds a default charset to text types | Name a charset, turn the default off with EncoderConfig, or check with startsWith(..) |
A cookie set with header("Cookie", ..) never reaches the server | A cookie(..) call replaced the hand-written header | Use cookie(..) for every cookie |
Try It Yourself
Exercise 1: Send Text in UTF-8
Add a test called aCharsetYouNameIsKept that posts the body "héllo" to /echo with the content type text/plain; charset=UTF-8. Check that the content type arrives unchanged and that the body arrives intact.
Hint
Start from textGetsTheDefaultCharsetAdded. A content type that already names a charset gets nothing added, so no configuration is needed.
Solution
1
2
3
4
5
6
7
8
9
10
11
@Test
void aCharsetYouNameIsKept() {
paymentsApi()
.contentType("text/plain; charset=UTF-8")
.body("héllo")
.when()
.post("/echo")
.then()
.body("contentType", equalTo("text/plain; charset=UTF-8"))
.body("body", equalTo("héllo"));
}
Exercise 2: Send a Traced Session Request
Add a test called aTracedSessionRequest that sends the request id req-7, accepts only application/json, and sends two cookies: session=abc123 and theme=dark. Check that the response echoes the request id, that the server received exactly one Accept value, and that both cookies arrived.
Hint
Combine oneHeader, the string form of accept(..) from the tip, and two cookie(..) calls. Use hasEntry(..) for one cookie and a cookies. path for the other.
Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Test
void aTracedSessionRequest() {
paymentsApi()
.header("X-Request-ID", "req-7")
.accept("application/json")
.cookie("session", "abc123")
.cookie("theme", "dark")
.when()
.get("/echo")
.then()
.header("X-Request-ID", "req-7")
.body("headers.accept", contains("application/json"))
.body("cookies", hasEntry("session", "abc123"))
.body("cookies.theme", equalTo("dark"));
}
Summary
You built HeadersAndCookiesTest, which sends headers, content types and cookies, and proves which values REST Assured merges, overwrites and adds. A helper’s header that won’t go away, or a charset that a strict server rejects, no longer surprises you.
- Headers can be set one by one, from a map or as
Headerobjects, and one header can have several values. - Setting a header twice merges the values, except for
AcceptandContent-Type, where the last value wins;HeaderConfigchanges that per header. accept(ContentType.JSON)sends four JSON media types; pass a string when an API wants exactly one.- REST Assured adds
charset=ISO-8859-1to text content types unless you name a charset or turn the default off withEncoderConfig. - All cookies travel in one
Cookieheader, so add every cookie withcookie(..).
Here are the commands you used in this guide:
1
mvn test -pl module-02 -Dtest=HeadersAndCookiesTest
What’s Next
Next: continue with Send Request Bodies in REST Assured, which shows which bodies are sent as they are, which are serialized, and how to test rejected bodies.
The code:
- The finished test class:
HeadersAndCookiesTest.java - The code and run commands for this module: Module 2 README
Go deeper:
- REST Assured Usage wiki, for headers, cookies,
HeaderConfigandEncoderConfig. - RFC 6265, section 5.4: The Cookie Header, for why all cookies share one header.
Related guides:
- Send Query and Form Parameters in REST Assured, where the form’s charset first appeared.
- Check Every Part of an HTTP Response, for checking response headers such as the echoed
X-Request-ID.
