Request Headers

Introduction

When a client sends an HTTP request to a server, the URL and request body are not always enough. The server often needs additional information before it can process the request correctly. It may need to know who is making the request, whether the caller is authenticated, what kind of data is being sent, what response format the client expects, which language the client prefers, whether compressed responses are supported, or which application is making the call. This extra information is sent through request headers.

Request headers are part of the HTTP request. They are key-value pairs that describe metadata about the request rather than the main business data itself. For example, an API request may send Authorization: Bearer eyJhbGc... to prove the caller's identity, Content-Type: application/json to tell the server how to parse the request body, and Accept: application/json to tell the server which response format the client prefers.

For API testers, request headers are essential. Many API failures are caused by missing, invalid, or inconsistent headers. A request body may be perfectly valid JSON, but the server may reject it if the Content-Type header is missing. A token may be expired, tampered, or absent. A browser request may fail because an Origin header does not match CORS rules. A multi-tenant API may return the wrong data if a tenant-specific custom header is missing or incorrect.

Understanding request headers helps testers move beyond simple endpoint checks. A strong API test suite validates authentication headers, content negotiation, request body formats, cookies, custom business headers, language preferences, compression behavior, cache-related headers, and security-sensitive conditions. Request headers are small pieces of metadata, but they have a large impact on API behavior.

What Are Request Headers?

Request headers are HTTP headers sent by the client to the server as part of an HTTP request. They provide metadata about the request and help the server decide how to authenticate, parse, route, process, and respond to the call. Headers do not usually contain the main business payload. Instead, they describe the request context.

A request header follows a simple key-value format: Header-Name: Header-Value. For example, Authorization: Bearer TOKEN sends an authentication credential, while Accept-Language: en-US indicates the preferred language. Header names are generally case-insensitive in HTTP, but teams should still write them consistently for readability and documentation.

A simple definition is this: request headers are key-value pairs sent by the client to the server to provide additional information about an HTTP request. They help the server understand how the request should be handled and what the client expects.

Where Request Headers Are Sent

An HTTP request is made of several parts. It begins with the request line, which includes the method and path. After that come the request headers. Then a blank line separates the headers from the optional request body. A POST, PUT, or PATCH request often has a body. A GET request usually does not have a body, but it can still include headers.

POST /users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
Authorization: Bearer eyJhbGc...

{
  "name": "John",
  "city": "Chicago"
}

In this example, the request body contains the business data for creating a user. The headers explain the host, body format, expected response format, and authentication credential. The server uses all of this information together to process the request.

Why Request Headers Are Important

Request headers help the server determine who is making the request, whether the caller is authenticated, what content type is being sent, what response format is expected, whether compression is supported, which language is preferred, how caching should behave, whether an API version is being selected, and whether custom business context is required. Without headers, many API interactions would be ambiguous.

For example, a request body may contain JSON, XML, form data, or raw text. The server should not guess the format. The Content-Type header tells it how to parse the body. Similarly, a server may support both JSON and XML responses. The Accept header tells it which representation the client prefers. Authentication headers tell the server whether the request is allowed to access protected resources.

Headers also support non-functional behavior. Accept-Encoding helps reduce network usage through compression. Cache-Control influences caching. User-Agent helps with logging, analytics, and compatibility. Correlation IDs help trace a request across distributed systems. Tenant headers help route or scope data in multi-tenant applications.

Common Request Headers

Several request headers appear frequently in API testing. The Host header identifies the target server. Authorization sends authentication credentials. Content-Type specifies the format of the request body. Accept specifies the preferred response format. User-Agent identifies the client application. Accept-Language specifies the preferred language. Accept-Encoding specifies supported compression formats. Cache-Control controls caching behavior. Cookie sends stored cookies. Origin identifies the origin of a browser request. Custom headers carry application-specific metadata.

Header Purpose
HostIdentifies the target server
AuthorizationSends authentication credentials
Content-TypeSpecifies the request body format
AcceptSpecifies the preferred response format
User-AgentIdentifies the client application
Accept-LanguageSpecifies language preference
Accept-EncodingSpecifies supported compression formats
CookieSends cookie values to the server
OriginIdentifies the browser request origin
Custom HeadersCarry application-specific metadata

Host Header

The Host header specifies the server receiving the request. In HTTP/1.1, the Host header is important because multiple domains may be served from the same IP address. The server uses the Host value to determine which virtual host or application should handle the request.

A typical Host header looks like Host: api.example.com. In most API tools, this header is generated automatically from the URL, so testers rarely need to set it manually. However, understanding it helps when debugging gateway routing, reverse proxy issues, virtual host configuration, or local test environments.

If the Host header is wrong, the request may route to the wrong service, fail at the gateway, or return a response from an unexpected application. In production-like testing, this can be important when APIs sit behind load balancers, API gateways, or ingress controllers.

Authorization Header

The Authorization header is used to send credentials that prove the caller's identity or access rights. A common example is Authorization: Bearer JWT_TOKEN. APIs may also use Basic authentication, API tokens, OAuth 2.0 access tokens, or other schemes depending on the security model.

Authorization header testing should include valid token, missing token, invalid token, expired token, tampered token, wrong scheme, insufficient permissions, and token belonging to another user or tenant. A valid token should allow the request when the user has permission. A missing or invalid token should usually return 401 Unauthorized. A valid token without sufficient permission should usually return 403 Forbidden.

Security testing should also verify that tokens are transmitted only over HTTPS. Tokens should not be exposed in logs, URLs, error messages, or client-side storage without proper controls. The Authorization header is one of the most security-sensitive request headers in API testing.

Content-Type Header

The Content-Type header specifies the format of the request body. When a client sends JSON, it should usually send Content-Type: application/json. XML requests may use application/xml or a more specific XML media type. File uploads may use multipart/form-data. Form submissions may use application/x-www-form-urlencoded.

The server uses Content-Type to decide how to parse the body. If a request sends JSON but claims text/plain, the server may reject it or parse it incorrectly. If Content-Type is missing, the server may not know how to handle the body. A clean API should return a clear error such as 415 Unsupported Media Type when the media type is not supported.

Testers should validate correct Content-Type, missing Content-Type, unsupported Content-Type, mismatched body and header, and case or charset variations such as application/json; charset=utf-8. Content-Type tests are especially important for POST, PUT, PATCH, and file upload endpoints.

Accept Header

The Accept header specifies the response format preferred by the client. A common value is Accept: application/json. If the server supports multiple representations, it can use the Accept header to choose whether to return JSON, XML, plain text, or another format.

If a client sends Accept: application/xml but the API supports only JSON, the server may return 406 Not Acceptable if it strictly enforces content negotiation. Some APIs ignore unsupported Accept values and return the default format anyway. The correct behavior depends on the API contract, but it should be consistent.

Testing the Accept header is important when APIs support multiple media types or when clients rely on JSON responses. Tests should verify supported formats, unsupported formats, missing Accept headers, wildcard values, and response Content-Type consistency.

User-Agent Header

The User-Agent header identifies the client making the request. A browser may send a long User-Agent string. Postman sends values such as PostmanRuntime. Automated test frameworks, mobile apps, SDKs, and backend services may send their own identifiers.

Servers use User-Agent for logging, analytics, compatibility handling, rate limiting, or troubleshooting. In many APIs, User-Agent does not change core business behavior. However, some public APIs require a meaningful User-Agent so they can contact consumers or identify abusive clients.

Testers should know whether User-Agent is required or optional. If it is required, missing or vague values should be tested. If the API changes behavior based on client type, those variations should be validated carefully.

Accept-Language Header

The Accept-Language header indicates the client's preferred response language. For example, Accept-Language: en-US asks for American English, while Accept-Language: fr-FR asks for French as used in France. APIs that return localized messages, labels, product descriptions, or validation errors may use this header.

Localization testing should verify supported languages, unsupported languages, fallback behavior, default language, and translated error messages. If the API returns user-facing text, language behavior should be predictable. If the API returns only machine-readable codes, Accept-Language may have little effect.

Testers should also check whether language preference can come from multiple sources such as user profile, query parameter, cookie, or Accept-Language header. The priority order should be documented.

Accept-Encoding Header

The Accept-Encoding header tells the server which compression formats the client can handle. Common values include gzip, deflate, and br. Compression reduces network usage by making large responses smaller.

API tools and browsers often set this header automatically. The server may return compressed content and include a response header such as Content-Encoding: gzip. For large API responses, compression can have a significant performance benefit.

Testing compression usually matters in performance, gateway, or production-readiness checks. Testers can verify that the server returns compressed responses when requested and that clients can decode them correctly. They should also verify that compression does not break response body validation in automation.

Cache-Control and Conditional Headers

Request headers can influence caching. Cache-Control: no-cache asks caches to revalidate before using stored content. Conditional headers such as If-None-Match and If-Modified-Since allow clients to ask whether cached data is still valid. These headers are common in APIs that serve cacheable data.

For example, a client may first receive an ETag from a response. Later, it can send If-None-Match with that ETag. If the resource has not changed, the server may return 304 Not Modified. This saves bandwidth because the full response body does not need to be sent again.

Testers should validate caching headers when API performance and freshness matter. They should verify correct behavior for fresh content, stale content, changed resources, unchanged resources, and endpoints that must never be cached.

Cookie Header

The Cookie header sends previously stored cookies from the client to the server. A cookie may carry a session ID, user preference, tracking value, CSRF token, or authentication-related data depending on the application. Browser-based applications often use cookies heavily, while pure token-based APIs may not.

A Cookie header may look like Cookie: sessionId=ABC123. The server reads the cookie and uses it to identify the session or apply stored preferences. If the cookie is missing, expired, or invalid, the API may reject the request or treat the caller as anonymous.

Cookie testing should include valid cookies, missing cookies, expired cookies, tampered cookies, cookies from another user, secure flag behavior, SameSite behavior, and interaction with Authorization headers. Session-based APIs require careful cookie validation.

Origin and Referer Headers

The Origin header identifies the origin that initiated a browser request. It is important for CORS validation. If a web application hosted at https://app.example.com calls an API, the browser may send Origin: https://app.example.com. The server decides whether that origin is allowed.

The Referer header indicates the page that initiated the request. It can be useful for logging or analytics, but it should not be treated as a strong security control because clients may omit or manipulate it depending on context.

API testers should validate CORS behavior for allowed origins, disallowed origins, missing origins, preflight requests, allowed methods, allowed headers, and credentialed requests. Browser-facing APIs can fail in production even when direct Postman calls work because CORS rules are enforced by browsers.

Custom Headers

Applications can define custom headers for business or technical needs. Examples include Tenant-Id: 1001, Client-Version: 2.5.0, Correlation-Id: 123456789, X-API-Key: abc123, and Device-Id: Android-XYZ123. These headers can be useful, but they should be documented clearly.

Custom headers are common in multi-tenant systems, mobile APIs, partner integrations, distributed tracing, feature rollout, and client version control. A tenant header may scope data to one organization. A correlation ID may help trace a request through multiple services. A client version header may allow the server to handle backward compatibility.

Testing custom headers requires understanding whether they are required, optional, validated, case-sensitive in value, restricted to allowed values, or security-sensitive. Missing required custom headers should return clear errors. Invalid values should not cause server crashes or data leakage.

Request Headers vs Response Headers

Request headers are sent by the client to the server. Response headers are sent by the server back to the client. Request headers describe the request and client expectations. Response headers describe the response and server decisions. Both are important in API testing, but they are validated from different directions.

Request Headers Response Headers
Sent by the clientSent by the server
Describe the requestDescribe the response
Example: AuthorizationExample: Content-Length
Example: Content-TypeExample: Cache-Control
Example: AcceptExample: ETag

Request Headers in API Testing

API testers should validate request headers according to the API specification. The first area is authorization. Tests should cover valid token, missing token, invalid token, expired token, tampered token, and insufficient permission. The expected results may include 200 OK, 401 Unauthorized, or 403 Forbidden depending on the scenario.

The second area is Content-Type. If the request sends JSON, the Content-Type should match JSON. Unsupported content types should produce a controlled error such as 415 Unsupported Media Type where the API enforces media types. Mismatched body and Content-Type should also be tested.

The third area is Accept. If the client requests JSON, the response should be JSON when supported. If the client requests XML and the API does not support XML, the response should follow the documented behavior, often 406 Not Acceptable or a default JSON response. Response Content-Type should match what is returned.

Custom headers should be tested for presence, valid values, invalid values, missing values, and authorization impact. Cookie headers should be tested when the API uses sessions. Browser-facing headers such as Origin should be tested when CORS behavior matters.

Header Governance in Real Projects

Large projects need header governance because headers can easily become inconsistent across services. One team may use Tenant-Id, another may use X-Tenant-ID, and another may pass tenant information inside the request body. One service may require Correlation-Id, while another generates it silently. These differences make APIs harder to use and harder to test.

A good API platform defines shared header standards. It should document required security headers, tracing headers, tenant headers, client identification headers, content negotiation headers, and versioning headers where used. The same header should have the same meaning across services. If a header is deprecated, the migration plan should be documented clearly.

Testers can help enforce this governance. Contract tests can verify that required headers are accepted consistently. Negative tests can verify missing or invalid headers. API review checklists can catch unclear custom headers before implementation. This is especially useful in microservice environments where many teams publish APIs independently.

Debugging Header-Related Failures

Header-related failures are sometimes misdiagnosed as endpoint or payload defects. A 401 may be caused by an expired token rather than a broken endpoint. A 415 may be caused by the wrong Content-Type rather than invalid JSON. A 406 may be caused by an unsupported Accept header. A browser failure may be caused by CORS headers even though the same request works in Postman.

When debugging, inspect the actual request sent over the network. Do not rely only on what the test code appears to set. Tools and frameworks may add, remove, normalize, or override headers. Proxies, gateways, and browser policies may also affect what reaches the server. Logging the final request headers in test reports can save significant investigation time.

Compare a failing automated request with a known working request from Postman, curl, browser developer tools, or API documentation. Look for differences in Authorization, Content-Type, Accept, cookies, tenant headers, Origin, API keys, and correlation headers. Small differences in headers often explain large differences in behavior.

Reusable Header Strategy in Automation

A practical automation framework should centralize common headers but still allow tests to override them. Happy-path tests usually need default Authorization, Accept, Content-Type, tenant, and correlation headers. Repeating those headers in every test creates duplication. A reusable request specification, API client, or helper method keeps common setup consistent.

However, negative tests must be able to remove or change headers deliberately. If the framework always adds Authorization automatically and provides no way to remove it, testing missing-token behavior becomes awkward. If Content-Type is always forced to JSON, testing unsupported media types becomes harder. Good framework design supports defaults and controlled exceptions.

Header generation should also be deliberate. Correlation IDs can be generated per request or per test flow. Tokens can be created through authentication helpers. Tenant IDs can come from test data setup. Client version headers can be driven by configuration. The goal is to make headers traceable and meaningful, not hidden or random.

Common Request Header Test Cases

A practical header test suite includes valid authorization, missing authorization, invalid authorization, expired authorization, correct Content-Type, missing Content-Type, invalid Content-Type, supported Accept, unsupported Accept, missing required custom header, invalid custom header, valid cookie, invalid cookie, allowed Origin, and disallowed Origin.

Test Case Expected Result
Valid AuthorizationRequest succeeds when permissions allow
Missing Authorization401 Unauthorized for protected resources
Invalid Authorization401 Unauthorized
Correct Content-TypeRequest body is parsed successfully
Invalid Content-Type415 Unsupported Media Type where enforced
Supported AcceptExpected response format returned
Unsupported Accept406 Not Acceptable or documented fallback
Missing Custom HeaderClear validation error if required
Invalid CookieAuthentication or session failure if required

REST Assured Example

In REST Assured, headers can be added using the header or headers methods. A typical request may look like this:

given()
  .header("Authorization", "Bearer " + token)
  .header("Content-Type", "application/json")
  .header("Accept", "application/json")
  .body(requestBody)
  .when()
  .post("/users")
  .then()
  .statusCode(201);

In larger frameworks, common headers are usually added through a reusable request specification. This avoids repeating Authorization, Accept, Content-Type, tenant, and correlation headers in every test. Individual tests can override or remove headers when testing negative scenarios.

Postman Example

In Postman, request headers can be added in the Headers tab. Headers can use static values or variables such as {{authToken}}, {{tenantId}}, and {{correlationId}}. This makes the same collection reusable across environments and users.

Postman also automatically adds some headers depending on request type. For example, it may set Content-Type when a JSON body is selected. Testers should still inspect the generated request because hidden or auto-generated headers can affect API behavior. When debugging, always confirm the actual headers sent.

Karate Example

Karate supports request headers using the header keyword. A simple request may look like this:

Given path 'users'
And header Authorization = 'Bearer ' + token
And header Content-Type = 'application/json'
And header Accept = 'application/json'
And request { name: 'John' }
When method POST
Then status 201

Common headers can be configured in the Background section or through reusable functions. As with other frameworks, testers should keep positive requests clean while still creating explicit negative tests for missing and invalid headers.

Best Practices

Always send the correct Content-Type when a request has a body. Specify an appropriate Accept header when response format matters. Use HTTPS when transmitting authentication credentials, cookies, API keys, or sensitive custom headers. Keep header names consistent across APIs and documentation.

Validate required custom headers and avoid sending unnecessary headers. Extra headers can confuse debugging, expose information, or trigger gateway rules unexpectedly. Follow the API specification for required and optional headers. If a header is required for one endpoint but not another, document that clearly.

Use reusable request specifications in automation, but do not let them hide important negative tests. A global specification that always adds Authorization is useful for happy paths, but tests for missing Authorization must be able to remove that header deliberately. Good frameworks make both reuse and controlled override easy.

Common Mistakes

A common mistake is sending a JSON request body without Content-Type: application/json. Some servers may still parse it, but others will reject it. Tests should not rely on forgiving behavior unless the API explicitly supports it.

Another mistake is sending the wrong Accept header. If the client requests XML from an API that supports only JSON, the response may be 406 Not Acceptable or a documented fallback. Testers should verify the expected behavior rather than assuming all Accept values are ignored.

Exposing sensitive information in custom headers is another risk. Passwords, raw secrets, long-lived tokens, or private business data should not be placed in headers unless the API explicitly requires it and the connection is protected. Even then, logging and masking must be considered.

Ignoring required headers is also common. Many APIs require Authorization, Content-Type, API-Key, Tenant-Id, Client-Version, or Correlation-Id. Missing these headers should produce clear errors. Silent fallback behavior can hide defects and create security issues.

Real-World Examples

A login API may use POST /login with Content-Type: application/json and Accept: application/json. A protected order API may use GET /orders with Authorization: Bearer JWT_TOKEN. A multi-tenant customer API may use Tenant-Id: 5001 to scope data to the correct organization.

A mobile API may send Client-Version: 5.1.2 and Device-Id: Android-XYZ123. A distributed microservice system may send Correlation-Id so logs from multiple services can be connected. A browser application may send Origin and cookies, which makes CORS and session behavior part of the test scope.

Interview Questions

A common interview question is: what are request headers? A strong answer is that request headers are HTTP headers sent by the client to the server to provide metadata about the request, such as authentication, body format, expected response format, language preference, compression support, cookies, and custom business context.

Another question is why request headers are important. They help the server process the request correctly. Without the right headers, the server may reject authentication, fail to parse the body, return an unsupported format, ignore localization, or miss required tenant context.

Interviewers may ask for examples of common request headers. Good examples include Authorization, Content-Type, Accept, Host, User-Agent, Accept-Language, Accept-Encoding, Cache-Control, Cookie, Origin, Referer, and custom headers such as API-Key, Tenant-Id, Client-Version, and Correlation-Id.

Interview-Ready Explanation

Request headers are HTTP headers sent by the client to the server as part of an HTTP request. They contain metadata that helps the server understand how to process the request. Common request headers include Authorization for authentication, Content-Type for the request body format, Accept for the preferred response format, Accept-Language for language preference, Accept-Encoding for compression support, Cookie for session information, and custom headers for application-specific metadata.

In API testing, request headers are validated to ensure correct authentication, content negotiation, body parsing, security, localization, caching, custom business context, and compliance with the API specification. Testers should cover valid headers, missing headers, invalid values, expired tokens, unsupported content types, unsupported Accept values, custom header validation, cookie behavior, and CORS-related headers where applicable.

Request headers are small compared with request bodies, but they are critical to API behavior. A correct endpoint and body can still fail if the headers are wrong. Strong API testing treats headers as part of the contract, not as optional decoration.

Key Takeaway

Request headers are key-value metadata sent by the client to the server. They explain who is calling, what format is being sent, what format is expected, what language is preferred, whether compression is supported, which cookies are available, and what custom context the application requires.

The practical rule is to validate headers with the same seriousness as URL parameters and request bodies. Check required headers, invalid values, missing values, authentication behavior, content negotiation, custom headers, cookies, security, and documentation accuracy. Well-tested request headers make API behavior more predictable, secure, and reliable.