Q25 of 40 · REST Assured
How does REST Assured handle cookies across requests?
REST AssuredMidrest-assuredcookiessessionapi-testing
Short answer
Short answer: Use .cookie(name, value) to send cookies and .then().cookie(name, matcher) to assert response cookies. To persist cookies across requests (session simulation), extract with .extract().detailedCookies() and feed back into the next request's .cookies(cookies) — REST Assured does not maintain a cookie jar automatically.
Detail
Setting cookies on a request:
given()
.cookie("sessionId", "abc123")
.cookie("preferences", "theme=dark")
Asserting cookies in a response:
.then()
.cookie("sessionId", notNullValue())
.cookie("XSRF-TOKEN", not(emptyString()))
Extracting detailed cookie attributes (value, path, domain, expiry, secure, httpOnly):
Cookies cookies = ...then().extract().detailedCookies();
Cookie session = cookies.get("sessionId");
assertThat(session.isHttpOnly()).isTrue();
assertThat(session.isSecured()).isTrue();
Simulating a stateful session (login → use session → logout):
Cookies session = given().body(creds).when().post("/login")
.then().statusCode(200).extract().detailedCookies();
given().cookies(session)
.when().get("/profile")
.then().statusCode(200);
given().cookies(session)
.when().post("/logout")
.then().statusCode(204);
REST Assured does not auto-manage cookies like a browser — you extract and re-inject manually.
// EXAMPLE
@Test
void sessionFlow_loginGetProfileLogout() {
// Step 1: Login and capture the session cookie
Cookies sessionCookies = given(reqSpec)
.body(Map.of("username", "alice", "password", "secret"))
.when()
.post("/auth/login")
.then()
.statusCode(200)
.cookie("SESSION", notNullValue())
.extract().detailedCookies();
Cookie session = sessionCookies.get("SESSION");
assertThat(session.isHttpOnly()).isTrue();
// Step 2: Use the session cookie on a protected endpoint
given(reqSpec)
.cookies(sessionCookies)
.when()
.get("/profile")
.then()
.statusCode(200)
.body("username", equalTo("alice"));
// Step 3: Logout
given(reqSpec)
.cookies(sessionCookies)
.when()
.post("/auth/logout")
.then()
.statusCode(204);
}// WHAT INTERVIEWERS LOOK FOR
Knowing REST Assured has no automatic cookie jar, the pattern of extracting detailedCookies() and re-injecting them, and asserting on cookie security attributes (httpOnly, secure). Testing full session flows is a strong signal.
// COMMON PITFALL
Expecting REST Assured to track cookies automatically like a browser. It doesn't — you must extract and re-attach cookies manually between requests.