Beginner
Chapter 6 · 9 min read
Headers & Content Types
Set and validate request/response headers, work with different content types (JSON, XML, form data), and understand common HTTP headers.
HTTP Headers in API Testing
HTTP headers carry metadata about the request and response. They control content negotiation, authentication, caching, and more. Understanding headers is essential for proper API testing.
Common Request Headers
- Content-Type — Format of the request body (application/json, multipart/form-data, application/x-www-form-urlencoded)
- Accept — What response formats the client can handle
- Authorization — Authentication credentials (Bearer token, Basic auth)
- User-Agent — Client identification
- X-Custom-Header — Application-specific custom headers
Common Response Headers
- Content-Type — Format of the response body
- Content-Length — Size of the response in bytes
- Cache-Control — Caching directives
- X-RateLimit-* — Rate limiting information
- Set-Cookie — Session cookies
headers.test.js
// Setting request headers
const response = await fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Custom-Header': 'test-value',
'User-Agent': 'API-Test-Suite/1.0'
},
body: JSON.stringify({ title: 'Test', body: 'Content', userId: 1 })
});
// Validate response headers
console.assert(
response.headers.get('content-type').includes('application/json'),
'Response should be JSON'
);
console.log('Content-Type:', response.headers.get('content-type'));
// Iterate through all response headers
for (const [key, value] of response.headers.entries()) {
console.log(` ${key}: ${value}`);
}
// Form URL-encoded data
const formData = new URLSearchParams();
formData.append('username', 'testuser');
formData.append('password', 'testpass');
const formResponse = await fetch('https://httpbin.org/post', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: formData.toString()
});
const formResult = await formResponse.json();
console.log('Form data received:', formResult.form);
HeadersTest.java
import static io.restassured.RestAssured.*;
import static org.hamcrest.Matchers.*;
import io.restassured.http.ContentType;
import io.restassured.response.Response;
import org.testng.annotations.Test;
public class HeadersTest {
@Test
public void testRequestHeaders() {
given()
.baseUri("https://jsonplaceholder.typicode.com")
.contentType(ContentType.JSON)
.accept(ContentType.JSON)
.header("X-Custom-Header", "test-value")
.header("User-Agent", "API-Test-Suite/1.0")
.body("{ \"title\": \"Test\", \"body\": \"Content\", \"userId\": 1 }")
.when()
.post("/posts")
.then()
.statusCode(201)
.contentType(ContentType.JSON);
}
@Test
public void testResponseHeaders() {
Response response =
given()
.baseUri("https://jsonplaceholder.typicode.com")
.when()
.get("/posts/1")
.then()
.header("Content-Type", containsString("application/json"))
.extract().response();
// Access individual headers
String contentType = response.getHeader("Content-Type");
System.out.println("Content-Type: " + contentType);
// Get all headers
response.getHeaders().forEach(h ->
System.out.println(" " + h.getName() + ": " + h.getValue())
);
}
@Test
public void testFormUrlEncoded() {
given()
.baseUri("https://httpbin.org")
.contentType("application/x-www-form-urlencoded")
.formParam("username", "testuser")
.formParam("password", "testpass")
.when()
.post("/post")
.then()
.statusCode(200)
.body("form.username", equalTo("testuser"));
}
}
test_headers.py
import requests
def test_request_headers():
"""Setting custom request headers"""
headers = {
'Content-Type': 'application/json',
'Accept': 'application/json',
'X-Custom-Header': 'test-value',
'User-Agent': 'API-Test-Suite/1.0'
}
response = requests.post(
'https://jsonplaceholder.typicode.com/posts',
headers=headers,
json={'title': 'Test', 'body': 'Content', 'userId': 1}
)
assert response.status_code == 201
assert 'application/json' in response.headers['Content-Type']
def test_response_headers():
"""Validate response headers"""
response = requests.get('https://jsonplaceholder.typicode.com/posts/1')
# Access individual headers (case-insensitive)
print(f"Content-Type: {response.headers['Content-Type']}")
# Iterate all response headers
for key, value in response.headers.items():
print(f" {key}: {value}")
assert 'application/json' in response.headers['Content-Type']
def test_form_urlencoded():
"""Submit form-urlencoded data"""
response = requests.post(
'https://httpbin.org/post',
data={'username': 'testuser', 'password': 'testpass'}
)
assert response.status_code == 200
assert response.json()['form']['username'] == 'testuser'
API Testing
Beginner
Headers & Content Types
Written by PV
© 2026 All Rights Reserved