Q8 of 40 · REST Assured

How do you set headers and content type in a REST Assured request?

REST AssuredJuniorrest-assuredheaderscontent-typefundamentals

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) → sets Content-Type: application/json; charset=UTF-8 and configures Jackson/Gson body serialisation
  • .accept(ContentType.JSON) → sets the Accept header
  • .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"));
}

// WHAT INTERVIEWERS LOOK FOR

Awareness of both .header() and the .contentType()/.accept() shortcuts, and knowing that ContentType.JSON does more than set a header string — it configures serialisation. Bonus: using headers(Map) for data-driven scenarios.

// COMMON PITFALL

Setting Content-Type as a raw string header without configuring serialisation, then wondering why REST Assured sends the POJO as a String literal rather than JSON.