ADVANCED
Karate Object API
The karate object is a runtime utility available in JavaScript functions, Karate expressions, and karate-config.js. It provides methods for test control, data manipulation, HTTP access, and system integration.
On this page:
- Variables and State -- copy, eval, get, remove, set
- Data Transforms -- append, appendTo, distinct, extract, extractAll, filter, filterKeys, forEach, fromJson, fromString, jsonPath, keysOf, lowerCase, map, mapWithKey, merge, range, repeat, sizeOf, sort, valuesOf, xmlPath
- Calling Features -- call, callonce, callSingle
- HTTP -- http, prevRequest, response, proceed, waitForHttp, waitForPort
- Assertions -- expect, match
- File I/O -- read, readAsBytes, readAsStream, readAsString, toAbsolutePath, write
- Config and Environment -- config, configure, env, feature, info, os, properties, scenario, scenarioOutline, suite, tagValues, tags
- Flow Control -- abort, fail, pause, setup, setupOnce, stop
- Process Execution -- exec, fork
- Async and Events -- channel, signal, start
- Test Data and Utilities -- doc, embed, faker.*, log, pretty, prettyXml, render, toBean, toBytes, toCsv, toJava, toJson, toString, typeOf, urlDecode, urlEncode, uuid
Variables and State
Read and write variables dynamically, especially useful in JavaScript functions and conditional logic.
karate.copy(name)
Deep-copy a variable to prevent mutation of the original. This is exposed as the copy keyword in Gherkin, not as a karate.* function call.
* def original = { name: 'John', scores: [85, 90] }
* copy clone = original
* set clone.name = 'Jane'
* match original.name == 'John'
karate.eval(expression)
Evaluate a string as a JavaScript expression at runtime. Useful when the expression itself is dynamic.
* def field = 'name'
* def result = karate.eval("response." + field)
karate.get(name, [default])
Get a variable by name or JsonPath expression. Returns null (or the optional default) if not found. Supports $variable.path syntax for JsonPath lookups.
* def timeout = karate.get('config.timeout', 3000)
* def first = karate.get('$response.users[0]')
karate.remove(name, path)
Remove a key from a JSON object or a node from XML at the given path.
* def payload = { a: 1, b: 2, secret: 'x' }
* karate.remove('payload', 'secret')
* match payload == { a: 1, b: 2 }
karate.set(name, value) | karate.set(name, path, value) | karate.set(map)
Set a variable by name, or set a value at a JsonPath/XPath within an existing variable. The two-argument form sets the variable directly; the three-argument form navigates into the variable. The single-argument form takes a map and sets each top-level key as a variable — handy for bulk-loading a settings file.
* karate.set('token', 'abc-123')
* def payload = { userId: 1 }
* karate.set('payload', '$.title', 'Hello')
* match payload == { userId: 1, title: 'Hello' }
# bulk form — each top-level key becomes a variable
* karate.set(read('classpath:settings.json'))
Data Transforms
Transform, filter, and reshape arrays and objects using functional operations.
karate.append(...items)
Create an array by concatenating items. Each argument that is itself an array is flattened into the result.
* def result = karate.append([1, 2], [3, 4], 5)
* match result == [1, 2, 3, 4, 5]
karate.appendTo(name, ...items)
Append items to an existing array variable in place. The first argument is the variable name as a string.
* def list = [1, 2]
* karate.appendTo('list', 3, 4)
* match list == [1, 2, 3, 4]
karate.distinct(list)
Return unique items from an array of strings or numbers.
* def unique = karate.distinct([1, 2, 2, 3, 1])
* match unique == [1, 2, 3]
karate.extract(text, regex, group)
Extract a single match from text using a regex. The group index follows Java regex capture-group rules.
* def html = '<div class="price">$49.99</div>'
* def price = karate.extract(html, '\\$([0-9.]+)', 1)
* match price == '49.99'
karate.extractAll(text, regex, group)
Extract all matches from text as an array.
* def text = 'a1 b2 c3'
* def nums = karate.extractAll(text, '[a-z]([0-9])', 1)
* match nums == ['1', '2', '3']
karate.filter(list, predicate)
Filter an array. The predicate receives (item, index) and returns a boolean.
* def nums = [1, 2, 3, 4, 5]
* def even = karate.filter(nums, x => x % 2 == 0)
* match even == [2, 4]
karate.filterKeys(map, keys)
Extract a key-value subset from a map. Keys can be an array of strings or another map (only its keys are used).
* def full = { a: 1, b: 2, c: 3 }
* def subset = karate.filterKeys(full, ['a', 'c'])
* match subset == { a: 1, c: 3 }
karate.forEach(list, function)
Iterate an array or object. For arrays the function receives (item, index); for objects it receives (key, value, index). Returns nothing -- use for side effects.
* def names = []
* def users = [{ name: 'Al' }, { name: 'Bo' }]
* karate.forEach(users, x => names.push(x.name))
* match names == ['Al', 'Bo']
karate.fromJson(string)
Parse a JSON string into a Karate object (map or list).
* def raw = '{"a":1}'
* def obj = karate.fromJson(raw)
* match obj == { a: 1 }
karate.fromString(string)
Convert a string to JSON or XML based on its content. Useful when you receive data as a raw string and need it parsed.
* def data = karate.fromString('{"id":1}')
* match karate.typeOf(data) == 'map'
karate.jsonPath(json, expression)
Evaluate a JsonPath expression against a JSON object. Useful for building dynamic filter expressions in JavaScript.
* def users = [{ name: 'Al', age: 30 }, { name: 'Bo', age: 20 }]
* def young = karate.jsonPath(users, "$[?(@.age < 25)]")
* match young[0].name == 'Bo'
karate.keysOf(object)
Return the keys of a map-like object as an array.
* def keys = karate.keysOf({ a: 1, b: 2 })
* match keys == ['a', 'b']
karate.lowerCase(object)
Recursively convert all string keys and values to lowercase.
* def result = karate.lowerCase({ Name: 'JOHN' })
* match result == { name: 'john' }
karate.map(list, function)
Transform each element in an array. The function receives (item, index) and returns the new value.
* def names = karate.map([{ n: 'Al' }, { n: 'Bo' }], x => x.n)
* match names == ['Al', 'Bo']
karate.mapWithKey(list, key)
Convert an array of primitives into an array of objects, each with the given key.
* def result = karate.mapWithKey(['a', 'b'], 'letter')
* match result == [{ letter: 'a' }, { letter: 'b' }]
karate.merge(...maps)
Merge multiple JSON objects into one. Later objects override earlier keys.
* def defaults = { timeout: 5000, retries: 3 }
* def overrides = { timeout: 10000 }
* def config = karate.merge(defaults, overrides)
* match config == { timeout: 10000, retries: 3 }
karate.range(start, end, [interval])
Return an array of integers from start to end (inclusive). Default interval is 1.
* def nums = karate.range(1, 5)
* match nums == [1, 2, 3, 4, 5]
* def odds = karate.range(1, 9, 2)
* match odds == [1, 3, 5, 7, 9]
karate.repeat(count, function)
Build an array by executing a function count times. The function receives the current index.
* def ids = karate.repeat(3, i => ({ id: i + 1 }))
* match ids == [{ id: 1 }, { id: 2 }, { id: 3 }]
karate.sizeOf(object)
Return the size of an array (length) or object (number of keys).
* match karate.sizeOf([1, 2, 3]) == 3
* match karate.sizeOf({ a: 1, b: 2 }) == 2
karate.sort(list, [function])
Sort an array. The optional function receives (item, index) and returns the sort value. Without a function, the items themselves are compared (natural ordering).
* def items = [{ p: 3 }, { p: 1 }, { p: 2 }]
* def sorted = karate.sort(items, x => x.p)
* match sorted[0].p == 1
* match karate.sort([3, 1, 2]) == [1, 2, 3]
* match karate.sort(['b', 'c', 'a']) == ['a', 'b', 'c']
karate.valuesOf(object)
Return only the values of a map-like object as an array.
* def vals = karate.valuesOf({ a: 1, b: 2 })
* match vals == [1, 2]
karate.xmlPath(xml, expression)
Evaluate an XPath expression against an XML document. Useful for dynamic XPath expressions built at runtime.
* def xml = <root><item id="1"/><item id="2"/></root>
* def id = karate.xmlPath(xml, '/root/item[1]/@id')
* match id == '1'
Use karate.filter(), karate.map(), and karate.forEach() instead of JavaScript for loops. Use karate.repeat() when you need to execute something a fixed number of times.
Calling Features
Invoke feature files or JS functions for reusable test logic. Called features can do anything -- HTTP calls, data setup, assertions, or any other Karate operations. For shared setup logic such as authentication or base URLs, see Configuration (karate-config.js). See also Calling Other Features for the call and callonce keywords in Gherkin.
karate.call(path, [arg])
Invoke a feature file or JS function with an optional argument. Supports shared scope via a boolean first argument: karate.call(true, 'helper.feature').
* def result = karate.call('create-user.feature', { name: 'Al' })
* def token = result.authToken
karate.callonce(path, [arg])
Like karate.call() but the result is cached per feature. Subsequent calls with the same path return the cached result.
* def setup = karate.callonce('once-setup.feature')
* def token = setup.token
karate.callSingle(path, [arg])
Like karate.call() but runs only once across the entire test suite. Typically used in karate-config.js for expensive one-time setup such as authentication.
* def auth = karate.callSingle('classpath:auth/login.feature')
* def token = auth.token
Use karate.callSingle() in karate-config.js for expensive one-time setup like authentication tokens. The result is cached across all features in the suite.
HTTP
Make programmatic HTTP requests and access request/response details.
karate.http(url)
Return the HTTP request builder for programmatic use. Lets you construct and invoke HTTP requests entirely from JavaScript, which is often clearer than the DSL keywords inside a re-usable function or a loop.
* def res = karate.http('https://api.example.com').path('users').get()
* match res.status == 200
* match res.body[0].name == '#string'
Chain path(...segments), header(name, value), headers(map), param(name, value), params(map) and body(value) to build the request. The plural forms take a scalar or a list per key, exactly like the params and headers keywords. The rest of the request builder is reachable too - url(), contentType(), cookie(), formField() and so on - so karate.http(base).url(otherUrl) is fine.
Any of get(), post(), put(), delete(), patch(), head(), options(), trace() and connect() sends the request and returns the response. Each optionally takes the request body as an argument, so post({ name: 'Billie' }) is the same as body({ name: 'Billie' }).post(). Use method(name) when the verb itself is dynamic:
* def httpMethod = 'GET'
* def res = karate.http('https://api.example.com').path('users').method(httpMethod)
The returned response exposes status, statusText, body, bodyString, bodyBytes, headers, header(name), headerValues(name), responseTime and request.
The URL is retained after a call, so a builder can be re-used for several requests:
* def api = karate.http('https://api.example.com')
* def created = api.path('users').post({ name: 'Billie' })
* def fetched = api.path('users', created.body.id).get()
This is the same request builder the url, path, header and method keywords use, so the two styles do not mix cleanly within one scenario. karate.http(url) overwrites any URL set by the url keyword, headers set by header steps leak into the next karate.http() call, and every call clears the pending request state.
A karate.http() call also bypasses the DSL request pipeline: it does not set the response / responseStatus variables, and configure headers, configure cookies, the auto-sent cookie jar and retry until do not apply. Set what you need explicitly with header(...) / headers(...), and read the result off the returned response object.