API REFERENCE
Karate Keywords Reference
Complete reference of all Karate DSL keywords and actions used in API testing.
Core Keywords
def
Define variables with various data types:
* def name = 'John'
* def age = 30
* def user = { name: 'John', age: 30 }
* def response = call read('get-user.feature')
match
Assert and validate data:
* match response == { id: '#number', name: '#string' }
* match response.status == 200
* match response contains { success: true }
* match each response.items == '#object'
call
Call features or JavaScript functions:
* def result = call read('auth.feature')
* def token = call read('auth.feature@login')
* callonce read('setup.feature')
read
Read files or classpath resources:
* def data = read('data.json')
* def users = read('classpath:data/users.csv')
* def template = read('template.xml')
* def config = read('this:config.json') # relative to current feature
get
Extract values from JSON or XML using path expressions:
* def name = get response.user.name
* def first = get[0] response.users
* def ids = get response..id
* def value = get users[?(@.age > 25)]
callonce
Call a feature file only once per test run:
* def auth = callonce read('auth.feature')
* callonce read('setup.feature')
listen
Wait for async events with timeout:
* listen 5000
* def message = listen { type: 'notification' }
doc
Add documentation/comments to test reports:
* doc 'This scenario tests user creation flow'
HTTP Keywords
url
Set the base URL:
* url 'https://api.example.com'
* url baseUrl # from config
path
Append to the URL:
* path 'users', userId
* path 'api/v1/users'
method
Execute HTTP request:
* method get
* method post
* method put
* method delete
* method patch
request
Set request body:
* request { name: 'John', email: 'john@example.com' }
* request read('request.json')
headers
Set request headers:
* headers { 'Content-Type': 'application/json', 'Authorization': token }
* header Accept = 'application/json'
params
Set query parameters:
* params { page: 1, size: 10 }
* param sort = 'name'
cookies
Set cookies:
* cookies { session: 'abc123', userId: '456' }
* cookie sessionId = 'xyz789'
form field
Set form data:
* form field username = 'john'
* form field password = 'secret'
multipart field
Set multipart field:
* multipart field file = { read: 'test.pdf', filename: 'test.pdf' }
* multipart field name = 'John'
multipart file
Upload a file:
* multipart file file = { read: 'test.pdf', filename: 'test.pdf', contentType: 'application/pdf' }
multipart entity
Set multipart entity with custom content type:
* multipart entity { name: 'John', age: 30 }
multipart fields
Set multiple multipart fields at once:
* multipart fields { name: 'John', email: 'john@example.com' }
multipart files
Set multiple files at once:
* multipart files { file1: 'test1.pdf', file2: 'test2.pdf' }
form fields
Set multiple form fields at once:
* form fields { username: 'john', password: 'secret', remember: true }
soap action
Set SOAP action header:
* soap action 'http://example.com/GetUser'
status
Validate response status:
* status 200
* status 201
* assert responseStatus == 404
Control Flow
if
Conditional execution:
* if (responseStatus == 200) karate.call('success.feature')
* if (env == 'dev') karate.set('url', devUrl)
retry until
Retry with condition:
* retry until response.status == 'complete'
* configure retry = { count: 10, interval: 1000 }
foreach
Iterate over collections:
* foreach response.items karate.call('process-item.feature')
Configuration Keywords
configure
Set configuration options:
* configure ssl = true
* configure connectTimeout = 60000
* configure readTimeout = 60000
* configure headers = { 'X-API-Key': apiKey }
* configure cookies = null
* configure logPrettyRequest = true
* configure logPrettyResponse = true
Assertion Keywords
assert
Assert boolean expressions:
* assert response.total > 0
* assert response.items.length == 10
print
Debug output:
* print response
* print 'Status:', responseStatus
* print karate.pretty(response)
eval
Execute JavaScript:
* eval response.items.forEach(x => x.processed = true)
* def sum = eval(response.items.reduce((a,b) => a + b.price, 0))
Special Variables
karate
Access Karate runtime:
* karate.log('Debug message')
* karate.set('myVar', value)
* karate.get('myVar')
* karate.call('feature.feature')
* karate.callSingle('setup.feature')
* karate.env
* karate.properties
response
HTTP response data (automatically set after method call):
* method get
* match response.name == 'John'
* match response == { id: '#number', name: '#string' }
responseStatus
HTTP response status code:
* method get
* match responseStatus == 200
* assert responseStatus >= 200 && responseStatus < 300
responseHeaders
HTTP response headers as map:
* method get
* match responseHeaders['Content-Type'] contains 'application/json'
* def contentType = responseHeaders['Content-Type'][0]
responseCookies
HTTP response cookies as map:
* method get
* def sessionId = responseCookies.JSESSIONID.value
* match responseCookies contains { session: '#present' }
responseTime
Response time in milliseconds:
* method get
* assert responseTime < 1000
* print 'Response time:', responseTime, 'ms'
responseBytes
Raw response as byte array:
* method get
* def bytes = responseBytes
* match bytes == read('expected.pdf')
responseType
Response content type:
* method get
* match responseType == 'application/json'
* assert responseType.contains('json')
requestTimeStamp
Timestamp of request in milliseconds:
* method get
* def reqTime = requestTimeStamp
* print 'Request sent at:', reqTime
requestHeaders
Request headers that were sent:
* header Authorization = 'Bearer token123'
* method get
* match requestHeaders.Authorization == ['Bearer token123']
prevRequest
Inspect actual HTTP request details:
* method post
* print prevRequest.uri
* print prevRequest.method
* print prevRequest.headers
Scenario Keywords
Background
Setup for all scenarios:
Background:
* url 'https://api.example.com'
* def auth = call read('auth.feature')
Scenario
Define test scenario:
Scenario: Get user by ID
* path 'users', userId
* method get
* status 200
Scenario Outline
Data-driven scenarios:
Scenario Outline: Create users
* request { name: '<name>', age: <age> }
* method post
* status 201
Examples:
| name | age |
| John | 30 |
| Jane | 25 |
Advanced Keywords
table
Define data tables:
* table users
| name | age |
| John | 30 |
| Jane | 25 |
text
Multi-line text:
* text query =
"""
query GetUser($id: ID!) {
user(id: $id) {
name
email
}
}
"""
yaml
Convert YAML string to JSON:
* yaml data =
"""
name: John
age: 30
"""
* match data == { name: 'John', age: 30 }
csv
Read CSV file as JSON array:
* def users = read('users.csv')
copy
Deep copy objects:
* copy user = response.user
remove
Remove JSON paths:
* remove response.user.password
* remove response..internal
set
Set nested values:
* set response.user.verified = true
* set response.items[*].processed = true
replace
String replacement:
* replace response.template.'{name}' = 'John'
Type Conversion
string
Convert to string:
* string jsonAsString = { name: 'John' }
* match jsonAsString == '{"name":"John"}'
json
Convert to JSON:
* json data = '{"name":"John"}'
* match data.name == 'John'
xml
Convert to XML:
* xml data = <user><name>John</name></user>
xmlstring
Convert XML to string:
* xmlstring xmlAsString = data
bytes
Convert to byte array:
* bytes fileData = read('file.pdf')
Mock Server Keywords
pathMatches
Match request paths:
* pathMatches('/api/users/{id}')
paramExists
Check query parameter:
* paramExists('page')
paramValue
Match parameter value:
* paramValue('size') == '10'
methodIs
Match HTTP method:
* methodIs('post')
typeContains
Match content type:
* typeContains('json')
acceptContains
Match accept header:
* acceptContains('xml')
headerContains
Match header value:
* headerContains('Authorization', 'Bearer')
requestMatches
Match request body:
* requestMatches { name: '#string' }
Utility Functions
karate.jsonPath
Extract using JsonPath:
* def names = karate.jsonPath(response, '$.items[*].name')
karate.xmlPath
Extract using XPath:
* def title = karate.xmlPath(response, '//book[1]/title')
karate.map
Transform collections:
* def ids = karate.map(response.items, function(x){ return x.id })
karate.filter
Filter collections:
* def active = karate.filter(response.users, function(x){ return x.active })
karate.forEach
Iterate with side effects:
* karate.forEach(response.items, function(x){ karate.log(x.name) })
karate.repeat
Repeat operations:
* def items = karate.repeat(5, function(i){ return { id: i } })
karate.range
Generate range:
* def numbers = karate.range(1, 10)
karate.uuid
Generate UUID:
* def id = karate.uuid()
karate.random
Random number:
* def num = karate.random(100)
karate.now
Current timestamp:
* def timestamp = karate.now()
karate.pretty
Pretty print JSON:
* print karate.pretty(response)
karate.prettyXml
Pretty print XML:
* print karate.prettyXml(xmlData)
karate.read
Read file (same as read keyword):
* def data = karate.read('data.json')
karate.readAsString
Read file as string without auto-conversion:
* def csv = karate.readAsString('data.csv')
karate.readAsBytes
Read file as byte array:
* def bytes = karate.readAsBytes('file.pdf')
karate.readAsStream
Read file as InputStream:
* def stream = karate.readAsStream('large-file.dat')
karate.write
Write object to file:
* karate.write(data, 'target/output.json')
karate.toBean
Convert JSON to Java object:
* def user = karate.toBean(userJson, 'com.example.User')
karate.toJava
Convert JS function to Java:
* def javaFn = karate.toJava(jsFn)
karate.toJavaFile
Get java.io.File instance:
* def file = karate.toJavaFile('path/to/file')
karate.toMap
Convert to Java Map:
* def map = karate.toMap(jsonObject)
karate.toCsv
Convert JSON array to CSV:
* def csv = karate.toCsv(users)
karate.merge
Merge JSON objects:
* def combined = karate.merge(user, updates)
karate.append
Combine arrays or objects:
* def all = karate.append(array1, array2)
karate.appendTo
Append to existing array variable:
* karate.appendTo('users', newUser)
karate.remove
Conditional removal from JSON/XML:
* karate.remove('response', '$.items[?(@.inactive)]')
karate.set
Set value (same as set keyword):
* karate.set('response.user.active', true)
karate.get
Get value (same as get keyword):
* def name = karate.get('response.user.name')
karate.keysOf
Get keys of object:
* def keys = karate.keysOf(response)
karate.valuesOf
Get values of object:
* def values = karate.valuesOf(response)
karate.sizeOf
Get size of collection:
* def count = karate.sizeOf(response.items)
karate.typeOf
Get type of value:
* def type = karate.typeOf(response.value)
karate.match
Fuzzy matching in JavaScript:
* eval karate.match(response, expected)
karate.filterKeys
Extract subset of JSON keys:
* def filtered = karate.filterKeys(user, ['name', 'email'])
karate.mapWithKey
Transform array of primitives to objects:
* def objects = karate.mapWithKey(['a', 'b'], 'key')
karate.sort
Sort array with custom function:
* def sorted = karate.sort(items, function(a,b){ return a.price - b.price })
karate.distinct
Remove duplicates from array:
* def unique = karate.distinct(items)
karate.extract
Extract text using regex:
* def value = karate.extract(text, 'id=(\\d+)', 1)
karate.extractAll
Extract all regex matches:
* def matches = karate.extractAll(text, '\\d+')
karate.lowerCase
Convert JSON/XML to lowercase:
* def lower = karate.lowerCase(response)
karate.call
Call feature (same as call keyword):
* def result = karate.call('feature.feature')
karate.callSingle
Call feature once and cache result:
* def config = karate.callSingle('setup.feature')
karate.log
Log message to output:
* karate.log('Debug:', value)
karate.logger
Access logger instance:
* karate.logger.debug('Message')
karate.embed
Embed content in HTML report:
* karate.embed(screenshot, 'image/png')
karate.abort
Exit scenario early:
* if (condition) karate.abort()
karate.fail
Fail test with message:
* if (!valid) karate.fail('Validation failed')
karate.stop
Pause for debugging:
* karate.stop(port)
karate.pause
Sleep for milliseconds:
* karate.pause(1000)
karate.signal
Trigger async event:
* karate.signal({ type: 'ready' })
karate.waitForHttp
Wait for HTTP endpoint to be ready:
* karate.waitForHttp('http://localhost:8080')
karate.waitForPort
Wait for port to be ready:
* karate.waitForPort('localhost', 8080)
karate.exec
Execute OS command (blocking):
* def output = karate.exec('ls -la')
karate.fork
Execute OS command (non-blocking):
* def proc = karate.fork('npm start')
karate.setup
Call @setup scenario:
* karate.setup()
karate.setupOnce
Call @setup scenario once:
* karate.setupOnce()
karate.env
Current environment:
* print karate.env
karate.properties
System properties:
* def prop = karate.properties['user.home']
karate.os
Operating system information:
* def isWindows = karate.os.type == 'windows'
karate.feature
Current feature metadata:
* def name = karate.feature.fileName
karate.scenario
Current scenario metadata:
* def scenarioName = karate.scenario.name
karate.scenarioOutline
Current scenario outline metadata:
* def iteration = karate.scenarioOutline.iteration
karate.tagValues
Get tag values:
* def env = karate.tagValues.env[0]
karate.tags
Get scenario tags:
* def tags = karate.tags
karate.prevRequest
Inspect actual HTTP request:
* print karate.prevRequest
Configuration Options
configure ssl
Enable/disable SSL:
* configure ssl = true
* configure ssl = { keyStore: 'file.jks', keyStorePassword: 'pass' }
configure connectTimeout
Connection timeout in milliseconds:
* configure connectTimeout = 30000
configure readTimeout
Read timeout in milliseconds:
* configure readTimeout = 60000
configure proxy
Set HTTP proxy:
* configure proxy = 'http://proxy.example.com:8080'
* configure proxy = { uri: 'http://proxy', username: 'user', password: 'pass' }
configure headers
Set default headers for all requests:
* configure headers = { 'X-API-Key': apiKey, 'User-Agent': 'Karate' }
configure cookies
Clear or set default cookies:
* configure cookies = null
* configure cookies = { session: 'abc123' }
configure followRedirects
Follow HTTP redirects:
* configure followRedirects = true
configure lowerCaseResponseHeaders
Normalize response headers to lowercase:
* configure lowerCaseResponseHeaders = true
configure charset
Set request charset:
* configure charset = 'UTF-8'
configure logPrettyRequest
Pretty print request in logs:
* configure logPrettyRequest = true
configure logPrettyResponse
Pretty print response in logs:
* configure logPrettyResponse = true
configure printEnabled
Enable/disable print output:
* configure printEnabled = false
configure report
Control report verbosity:
* configure report = { showLog: true, showAllSteps: false }
configure retry
Configure retry behavior:
* configure retry = { count: 3, interval: 5000 }
configure httpRetryEnabled
Enable automatic retry for failed requests:
* configure httpRetryEnabled = true
configure afterScenario
Hook to run after each scenario:
* configure afterScenario = function(){ karate.log('Scenario done') }
configure afterFeature
Hook to run after feature:
* configure afterFeature = function(){ karate.log('Feature done') }
configure logModifier
Mask sensitive data in logs:
* configure logModifier = function(text){ return text.replace(/password/, '***') }
configure responseHeaders
Set mock server response headers:
* configure responseHeaders = { 'X-Custom': 'value' }
configure cors
Enable CORS for mock server:
* configure cors = true
configure abortedStepsShouldPass
Control behavior of aborted steps:
* configure abortedStepsShouldPass = true
configure abortSuiteOnFailure
Stop test suite on first failure:
* configure abortSuiteOnFailure = true
configure xmlNamespaceAware
Enable XML namespace handling:
* configure xmlNamespaceAware = false
configure matchEachEmptyAllowed
Allow empty arrays in match each:
* configure matchEachEmptyAllowed = true
configure localAddress
Set local address for requests:
* configure localAddress = '192.168.1.100'
configure pauseIfNotPerf
Pause behavior for performance testing:
* configure pauseIfNotPerf = true
configure callSingleCache
Configure cache for callSingle:
* configure callSingleCache = { minutes: 5 }
configure driver
UI automation driver configuration:
* configure driver = { type: 'chrome', headless: true }
configure driverTarget
Driver target configuration:
* configure driverTarget = { docker: 'chrome' }
configure imageComparison
Image comparison options:
* configure imageComparison = { failureThreshold: 2, engine: 'ssim' }
Special Tags
@ignore
Skip scenario at runtime:
@ignore
Scenario: This test is temporarily disabled
@setup
Mark scenario for setup data:
@setup
Scenario: Initialize test data
@parallel=false
Disable parallel execution for scenario:
@parallel=false
Scenario: Sequential test
@report=false
Hide scenario from HTML reports:
@report=false
Scenario: Internal helper scenario
See Also
- Core Syntax - Feature file structure
- Actions - Core actions and keywords
- Match Keyword - Assertion patterns
- Variables - Variable usage
- HTTP Requests - HTTP testing
- Configuration - Configuration options