Karate DSL: The Complete Guide to API Testing with BDD Syntax
API testing has a reputation for being complex — you need to understand HTTP internals, craft JSON payloads, handle authentication, and write assertion logic, all before you've even tested your first endpoint. Karate DSL changes that equation.
Karate is an open-source API testing framework that combines BDD-style syntax with powerful HTTP capabilities. You write tests in plain English (mostly), and Karate handles the rest. No Java boilerplate. No custom HTTP clients. Just readable, executable specs.
This guide covers everything you need to go from zero to productive with Karate DSL.
What Makes Karate Different
Most API testing frameworks are libraries bolted onto a programming language. Rest Assured is Java. Requests is Python. Supertest is JavaScript. You bring the language; the library gives you HTTP verbs.
Karate flips this. It's a domain-specific language built specifically for API testing. The syntax is designed around HTTP operations, JSON/XML handling, and assertions — not around generic programming constructs.
Here's what a Karate test looks like:
Feature: User API
Scenario: Create and retrieve a user
Given url 'https://api.example.com'
And path '/users'
And request { name: 'Alice', email: 'alice@example.com' }
When method post
Then status 201
And match response.id == '#notnull'
And match response.name == 'Alice'
Given path '/users/' + response.id
When method get
Then status 200
And match response == { id: '#string', name: 'Alice', email: 'alice@example.com' }That's the whole test. No imports, no class definitions, no HTTP client configuration. Just the scenario.
Setting Up Karate
Karate runs on the JVM but you don't need to write Java. You need Maven or Gradle and a test runner.
Maven setup (pom.xml):
<dependency>
<groupId>com.intuit.karate</groupId>
<artifactId>karate-junit5</artifactId>
<version>1.4.1</version>
<scope>test</scope>
</dependency>Test runner (Java):
import com.intuit.karate.junit5.Karate;
class ApiTests {
@Karate.Test
Karate testAll() {
return Karate.run("classpath:features").relativeTo(getClass());
}
}Feature file structure:
src/test/
├── java/
│ └── ApiTests.java
└── resources/
└── features/
├── users.feature
└── products.featureThat's the minimum viable setup. Run mvn test and Karate discovers all .feature files under the configured path.
Core Syntax
HTTP Methods
Given url 'https://api.example.com'
And path '/products'
When method get
Then status 200
# POST with body
And request { name: 'Widget', price: 9.99 }
When method post
# PUT with ID
Given path '/products/123'
And request { name: 'Updated Widget' }
When method put
# DELETE
Given path '/products/123'
When method delete
Then status 204Headers and Query Parameters
# Headers
And header Content-Type = 'application/json'
And header Authorization = 'Bearer ' + authToken
# Query parameters
And param status = 'active'
And param page = 1
And param limit = 20
# Or inline in the URL
Given url 'https://api.example.com/products?status=active&page=1'Variables
# Define variables
* def baseUrl = 'https://api.example.com'
* def userId = 42
# Use them
Given url baseUrl
And path '/users/' + userId
When method get
Then status 200Variables can be strings, numbers, booleans, JSON objects, or arrays.
JSON Inline
Karate treats JSON as a first-class citizen. No quoting required:
* def user = { name: 'Bob', age: 30, active: true }
* def tags = ['admin', 'user']
* def nested = { address: { city: 'NYC', zip: '10001' } }Assertions: The Match Keyword
match is Karate's assertion engine. It's more powerful than most assertion libraries.
Exact Match
Then match response == { id: 1, name: 'Alice' }Fuzzy Match
# Match structure, not exact values
Then match response == { id: '#number', name: '#string', created: '#ignore' }
# Notnull check
Then match response.token == '#notnull'
# Optional field
Then match response.middleName == '##string'Array Matching
# At least these elements exist
Then match response contains { id: 1, name: 'Alice' }
# Array length
Then match response == '#[5]'
# Each element matches a pattern
Then match each response == { id: '#number', name: '#string' }Regex and Custom
Then match response.email == '#regex .+@.+\\..+'
Then match response.uuid == '#uuid'
Then match response.timestamp == '#? _ > 0'The #? syntax lets you write inline JavaScript predicates. _ refers to the current value.
Reusing Setup with Background and Scenarios
Feature: User CRUD
Background:
* url 'https://api.example.com'
* header Authorization = 'Bearer test-token'
Scenario: Create user
Given path '/users'
And request { name: 'Alice' }
When method post
Then status 201
Scenario: List users
Given path '/users'
When method get
Then status 200
And match response == '#[]'The Background section runs before every scenario. Use it for URL setup, auth headers, and shared configuration.
Calling Other Features
You can reuse feature files as functions:
# auth.feature
Feature: Get auth token
Scenario:
Given url 'https://api.example.com/auth'
And request { username: 'test', password: 'secret' }
When method post
Then status 200
* def token = response.token# users.feature
Feature: User tests
Background:
* def auth = call read('classpath:features/auth.feature')
* def authToken = auth.token
Scenario: Get user profile
Given url 'https://api.example.com'
And path '/users/me'
And header Authorization = 'Bearer ' + authToken
When method get
Then status 200call executes another feature and returns its final state. This is how you chain scenarios and share setup logic.
Data-Driven Testing
Feature: Create multiple users
Scenario Outline: Create user <name>
Given url 'https://api.example.com'
And path '/users'
And request { name: '<name>', role: '<role>' }
When method post
Then status 201
Examples:
| name | role |
| Alice | admin |
| Bob | user |
| Carol | user |Or with a JSON data table:
* def users =
"""
[
{ name: 'Alice', role: 'admin' },
{ name: 'Bob', role: 'user' }
]
"""
* call read('create-user.feature') usersPassing an array to call runs the feature once per element, with each element available as the implicit __arg.
Configuration and Environments
Create karate-config.js in your test resources root:
function fn() {
var env = karate.env || 'dev';
var config = {
baseUrl: 'https://dev.api.example.com',
authToken: 'dev-token'
};
if (env === 'staging') {
config.baseUrl = 'https://staging.api.example.com';
config.authToken = karate.properties['staging.token'];
}
if (env === 'prod') {
config.baseUrl = 'https://api.example.com';
}
return config;
}Run with: mvn test -Dkarate.env=staging
Variables defined in karate-config.js are available in all feature files automatically.
Parallel Execution
Karate has built-in parallel execution — no additional configuration needed:
@Test
void testParallel() {
Results results = Runner.path("classpath:features")
.parallel(10); // 10 threads
assertThat(results.getFailCount()).isEqualTo(0);
}Tests in the same feature file run sequentially. Tests across different feature files run in parallel. For large test suites, this can cut execution time by 80% or more.
Reporting
Karate generates HTML reports by default in target/karate-reports/. Each scenario shows:
- Request headers, URL, and body
- Response headers, status, and body
- Assertion results
- Timeline across parallel runs
Add Cucumber reporting for CI integration:
<dependency>
<groupId>net.masterthought</groupId>
<artifactId>cucumber-reporting</artifactId>
<version>5.7.7</version>
<scope>test</scope>
</dependency>Where Karate Fits in Your Test Strategy
Karate excels at:
- Contract testing: Validate API behavior matches documented specs
- Integration testing: Test service-to-service interactions
- Regression testing: Catch API regressions before deployment
- Data setup: Seed test data via API calls before UI tests
For continuous monitoring and catching issues in production, Karate's file-based tests work well alongside always-on monitoring. HelpMeTest complements Karate by running your API scenarios on a schedule — every 5 minutes, 24/7 — alerting you when production endpoints behave differently than your Karate specs expect.
Karate DSL Strengths and Limitations
Strengths:
- Minimal setup, readable syntax
- Powerful JSON/XML matching
- Built-in parallel execution
- No programming language required for most tests
- Strong community and active maintenance
Limitations:
- JVM dependency (not ideal for non-Java shops)
- Complex logic requires JavaScript or Java interop
- Less flexible than code-first approaches for unusual test scenarios
- Report customization is limited without extra tooling
Practical Patterns
Wait for async operations:
* def response = karate.call('classpath:poll.feature', { maxWait: 5000, interval: 500 })Extract and reuse data:
When method post
Then status 201
* def createdId = response.id
Given path '/items/' + createdId
When method get
Then status 200Schema validation from file:
* def schema = read('classpath:schemas/user-schema.json')
Then match response == schemaConditional logic:
* if (env == 'prod') karate.set('baseUrl', prodUrl)Summary
Karate DSL solves a real problem: API tests that are readable, maintainable, and powerful without requiring deep programming expertise. The BDD syntax makes tests comprehensible to non-developers. The built-in HTTP client, JSON matching, and parallel execution remove friction that slows down other frameworks.
If your team writes API tests and the current approach feels heavy — too much boilerplate, too much test-support code, too much language-specific knowledge required — Karate is worth evaluating seriously. The learning curve is shallow. The capability ceiling is high.