Q8 of 40 · REST Assured
How do you set headers and content type in a REST Assured request?
Short answer
Short answer: Use .header("Name", "value") for individual headers or .headers(map) for multiple. .contentType(ContentType.JSON) is a typed shorthand that sets Content-Type and configures Jackson body serialisation. .accept(ContentType.JSON) sets the Accept header. Prefer the typed enums over raw header strings.
Detail
REST Assured provides both low-level and high-level header APIs:
Low-level: .header("Authorization", "Bearer " + token) — sets any header by name and value. Multiple calls are additive.
High-level shortcuts:
.contentType(ContentType.JSON)→ setsContent-Type: application/json; charset=UTF-8and configures Jackson/Gson body serialisation.accept(ContentType.JSON)→ sets theAcceptheader.cookie(name, value)→ sets a cookie header
With maps — useful for data-driven scenarios where headers vary:
given().headers(Map.of(
"Authorization", "Bearer " + token,
"X-Correlation-Id", correlationId,
"X-Tenant-Id", "tenant-1"
))
Always prefer .contentType(ContentType.JSON) over .header("Content-Type", "application/json") — the enum version also sets up the ObjectMapper for POJO body serialisation.
// EXAMPLE
@Test
void createProduct_withCustomHeaders() {
given()
.baseUri("https://api.example.com")
.contentType(ContentType.JSON) // Content-Type + serialisation
.accept(ContentType.JSON) // Accept header
.header("Authorization", "Bearer " + token)
.header("X-Idempotency-Key", UUID.randomUUID().toString())
.header("X-Correlation-Id", "test-run-001")
.body(Map.of("name", "Widget", "price", 9.99))
.when()
.post("/products")
.then()
.statusCode(201)
.body("name", equalTo("Widget"));
}