Skip to main content

HTTP REQUESTS

Headers and Cookies

Set HTTP headers and cookies using individual or bulk assignment methods with automatic cookie management and authentication pattern support.

Benefits of Header Management

  • Flexible assignment: Use header/cookie for individual values or headers/cookies for bulk operations
  • Automatic cookie handling: Response cookies are automatically sent in subsequent requests
  • Global configuration: Set headers once using configure headers for all requests
  • Authentication patterns: Built-in support for Bearer tokens, API keys, and dynamic auth

Simple Headers

Set individual headers for API requests:

Scenario: Basic authentication header
Given url baseUrl
And path 'users'
And header Authorization = 'Bearer abc123token'
And header Accept = 'application/json'
When method get
Then status 200
Key Points
  • Use header keyword followed by name and value
  • Headers apply only to the next HTTP request
  • Header names are case-insensitive per HTTP standards

Simple Cookies

Set individual cookies for requests:

Scenario: Basic cookie usage
Given url baseUrl
And path 'api/preferences'
And cookie sessionId = 'abc123'
And cookie theme = 'dark'
When method get
Then status 200

Individual Headers

Authentication Headers

Scenario: Bearer token authentication
Given url baseUrl
And path 'api/users'
And header Authorization = 'Bearer ' + authToken
When method get
Then status 200

Content Negotiation

Scenario: Accept and Content-Type headers
Given url baseUrl
And path 'api/data'
And header Accept = 'application/json'
And header Content-Type = 'application/json'
And request { name: 'John Doe', email: 'john@example.com' }
When method post
Then status 201

Custom Headers

Scenario: Custom application headers
* def requestId = karate.uuid()

Given url baseUrl
And path 'api/tracking'
And header X-Client-Version = '2.1.0'
And header X-Request-ID = requestId
And header X-Forwarded-For = '192.168.1.100'
When method get
Then status 200

Multi-Value Headers

Scenario: Headers with multiple values
Given url baseUrl
And path 'api/content'
And header Accept = ['application/json', 'application/xml']
And header Cache-Control = ['no-cache', 'no-store']
When method get
Then status 200

Individual Cookies

Scenario: Multiple cookies
Given url baseUrl
And path 'api/preferences'
And cookie sessionId = 'abc123'
And cookie theme = 'dark'
And cookie language = 'en-US'
When method get
Then status 200
Scenario: Cookies with variables
* def userId = 123
* def timestamp = new Date().getTime()

Given url baseUrl
And path 'api/tracking'
And cookie userId = userId
And cookie lastVisit = timestamp
When method get
Then status 200

Multiple Headers

Set multiple headers using JSON for cleaner syntax:

Scenario: Bulk header assignment
* def authToken = 'abc123token'
* def clientId = 'client-456'

Given url baseUrl
And path 'api/secure'
And headers { Authorization: 'Bearer ' + authToken, Accept: 'application/json', 'X-Client-ID': clientId }
When method get
Then status 200
Important
  • Local headers override global configure headers settings
  • Use headers (plural) for bulk assignment
  • JSON keys with hyphens must be quoted

Headers from Files

Scenario: Load and merge headers
* def commonHeaders = read('common-headers.json')
* def authHeaders = { Authorization: 'Bearer ' + token }
* def allHeaders = karate.merge(commonHeaders, authHeaders)

Given url baseUrl
And path 'api/protected'
And headers allHeaders
When method get
Then status 200

Conditional Headers

Scenario: Environment-specific headers
* def requestHeaders = { Accept: 'application/json', 'User-Agent': 'Karate-Test' }
* def env = karate.env || 'dev'
* if (env == 'dev') requestHeaders['X-Debug'] = 'true'
* if (env != 'prod') requestHeaders['X-Test-Mode'] = 'enabled'

Given url baseUrl
And path 'api/data'
And headers requestHeaders
When method get
Then status 200

Multiple Cookies

Set multiple cookies using JSON:

Scenario: Bulk cookie assignment
Given url baseUrl
And path 'api/user-prefs'
And cookies { sessionId: 'sess_abc123', theme: 'dark', language: 'en-US' }
When method get
Then status 200

Cookies from Authentication

Scenario: Extract and reuse session cookies
Given url baseUrl
And path 'auth/login'
And request { username: 'test', password: 'secret' }
When method post
Then status 200

* def sessionCookies = { sessionId: response.sessionId, csrfToken: response.csrfToken }

Given path 'api/profile'
And cookies sessionCookies
When method get
Then status 200

Global Headers with Configure

Set headers for all requests in a feature:

Feature: Global header configuration

Background:
* configure headers = { 'User-Agent': 'Karate Test', Accept: 'application/json' }

Scenario: Headers applied automatically
Given url baseUrl
And path 'users'
When method get
Then status 200

Override Global Headers

Background:
* configure headers = { Accept: 'application/json' }

Scenario: Override specific header
Given url baseUrl
And path 'special-endpoint'
And header Accept = 'application/xml'
When method get
Then status 200

Add to Global Headers

Background:
* configure headers = { Accept: 'application/json' }

Scenario: Combine global and local headers
* def additionalHeaders = { 'X-Request-ID': karate.uuid() }

Given url baseUrl
And path 'tracking'
And headers additionalHeaders
When method get
Then status 200

Dynamic Header Functions

Generate headers dynamically for each request:

Background:
* def getAuthHeaders =
"""
function() {
var token = karate.get('authToken');
if (!token) {
var auth = karate.call('classpath:auth/get-token.feature');
token = auth.token;
karate.set('authToken', token);
}
return { Authorization: 'Bearer ' + token };
}
"""
* configure headers = getAuthHeaders

Scenario: Auto-generated auth headers
Given url baseUrl
And path 'protected/data'
When method get
Then status 200
Development Workflow
  • Use header functions for authentication that expires or changes
  • Functions are called before each HTTP request automatically
  • Access current variables using karate.get()

Authentication Patterns

Bearer Token Authentication

Background:
* def authResult = call read('classpath:auth/login.feature')
* def token = authResult.response.access_token

Scenario: Use bearer token
Given url baseUrl
And path 'protected/users'
And header Authorization = 'Bearer ' + token
When method get
Then status 200

Token Refresh Handling

Background:
* def refreshToken =
"""
function() {
var tokenExp = karate.get('tokenExpiry');
var now = new Date().getTime();
if (!tokenExp || now > tokenExp) {
var refresh = karate.call('classpath:auth/refresh.feature');
karate.set('authToken', refresh.token);
karate.set('tokenExpiry', now + 3600000);
}
return { Authorization: 'Bearer ' + karate.get('authToken') };
}
"""
* configure headers = refreshToken

Scenario: Auto-refresh on expiry
Given url baseUrl
And path 'api/sensitive-data'
When method get
Then status 200

API Key Authentication

Scenario: API key in header
Given url baseUrl
And path 'api/data'
And header X-API-Key = apiKey
And header X-Client-ID = clientId
When method get
Then status 200
Scenario: API key as query parameter
Given url baseUrl
And path 'api/public-data'
And param api_key = apiKey
And param format = 'json'
When method get
Then status 200

Next Steps