Karate DSL: Complete Guide to API Testing

Karate DSL: Complete Guide to API Testing

Karate DSL is an open-source API testing framework that combines API test automation, mocks, performance testing, and UI automation into a single tool. Unlike most testing frameworks, Karate uses its own language built on Gherkin syntax — so tests read like plain English but execute with the precision of code.

This guide covers Karate from first principles through production usage.

What Makes Karate Different

Most API testing frameworks require you to write tests in a general-purpose language (Java, Python, JavaScript). Karate takes a different approach: it gives you a domain-specific language purpose-built for HTTP testing.

The payoff is significant:

  • No Java boilerplate. No setup classes, no annotations, no dependency injection.
  • Assertions are built-in. match response.name == 'Alice' works without imports.
  • JSON/XML are first-class. No serialization/deserialization code.
  • Parallel execution out of the box. No TestNG or JUnit runner configuration needed.

The tradeoff: you're learning a new language. Karate's syntax is not standard Gherkin — it's Gherkin extended with dozens of Karate-specific keywords.

Architecture

Karate runs on the JVM. The project structure follows Maven/Gradle conventions:

src/
  test/
    java/
      karate-config.js       # Global configuration
      features/
        users/
          users.feature      # Test features
          users-mock.feature # Service mocks
    resources/
      logback.xml
pom.xml

Each .feature file is a Karate test. Features contain scenarios. Scenarios contain steps. Steps use Karate's built-in keywords.

Core Syntax

Making Requests

Feature: User API

Scenario: Get a user by ID
  Given url 'https://api.example.com'
  And path '/users/1'
  When method GET
  Then status 200
  And match response == { id: 1, name: 'Alice', email: '#string' }

Key keywords:

  • url — base URL
  • path — appended to url
  • method — HTTP verb (GET, POST, PUT, DELETE, PATCH)
  • status — assert HTTP status code
  • match — assert response content

Request Headers and Auth

Scenario: Authenticated request
  Given url 'https://api.example.com'
  And path '/protected'
  And header Authorization = 'Bearer ' + token
  When method GET
  Then status 200

For reusable auth, define it in karate-config.js:

function fn() {
  var config = {
    baseUrl: 'https://api.example.com',
    authToken: 'Bearer abc123'
  };
  return config;
}

Then reference in tests:

Given url baseUrl
And header Authorization = authToken

POST with Request Body

Scenario: Create a user
  Given url 'https://api.example.com'
  And path '/users'
  And request { name: 'Bob', email: 'bob@example.com', role: 'admin' }
  When method POST
  Then status 201
  And match response.id == '#number'
  And match response.name == 'Bob'

JSON is written inline — no serialization needed. Karate handles Content-Type automatically.

Assertions and Matching

Karate's match keyword is its most powerful feature. It supports fuzzy matching, wildcards, and nested assertions.

Exact Match

And match response == { id: 1, name: 'Alice' }

Fuzzy Match with Wildcards

And match response == { id: '#number', name: '#string', email: '#regex .+@.+' }

Wildcards:

  • #string — any string
  • #number — any number
  • #boolean — any boolean
  • #null — null
  • #present — field exists (any value)
  • #notpresent — field does not exist
  • #regex .+ — matches regex
  • #? _ > 0 — JavaScript predicate

Array Matching

And match response.users == '#[3]'           # exactly 3 elements
And match response.users[0].name == 'Alice'  # first element
And match each response.users == { id: '#number', name: '#string' }  # all elements

Contains

And match response.tags contains 'api'
And match response.tags contains only ['api', 'testing']
And match response !contains { error: '#present' }

Variables and Reuse

Extracting Values

Scenario: Create then fetch
  Given url 'https://api.example.com'
  And path '/users'
  And request { name: 'Charlie' }
  When method POST
  Then status 201
  
  * def userId = response.id
  
  Given path '/users/' + userId
  When method GET
  Then status 200
  And match response.name == 'Charlie'

Calling Other Features

# auth.feature
Feature: Auth
Scenario: Get token
  Given url 'https://api.example.com/auth'
  And request { username: 'admin', password: 'secret' }
  When method POST
  Then status 200
  * def token = response.token
# users.feature
Feature: Users

Background:
  * def auth = call read('classpath:features/auth/auth.feature')
  * def token = auth.token

Scenario: Get users with auth
  Given url 'https://api.example.com'
  And path '/users'
  And header Authorization = 'Bearer ' + token
  When method GET
  Then status 200

Query Parameters and Path Parameters

Scenario: Search with query params
  Given url 'https://api.example.com'
  And path '/users'
  And param role = 'admin'
  And param page = 1
  And param limit = 10
  When method GET
  Then status 200
Scenario: Dynamic path
  * def userId = 42
  Given url 'https://api.example.com'
  And path '/users/' + userId + '/orders'
  When method GET
  Then status 200

Data-Driven Tests

Scenario Outline: Create users with different roles
  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     | viewer  |
    | Charlie | editor  |

For larger datasets, use external JSON or CSV:

* def users = read('classpath:features/users/test-data.json')

Scenario Outline: Create users from JSON
  Given url 'https://api.example.com'
  And path '/users'
  And request __row
  When method POST
  Then status 201
  
  Examples:
    | karate.setup()  |
    | users           |

Parallel Execution

Karate runs feature files in parallel by default when you use the runner:

@RunWith(Karate.class)
public class TestRunner {
  @Test
  public void testAll() {
    Results results = Runner.path("classpath:features")
      .parallel(5);  // 5 threads
    assertEquals(0, results.getFailCount(), results.getErrorMessages());
  }
}

No test ordering issues because each feature file is independent. Karate doesn't share state between features unless you explicitly pass data.

Service Mocks

Karate can act as a mock server using the same feature file format:

Feature: Users Mock

Scenario: pathMatches('/users/{id}') && methodIs('GET')
  * def userId = pathParams.id
  * def response = { id: '#(userId)', name: 'Mock User', email: 'mock@example.com' }
  * def responseStatus = 200

Start the mock in tests:

Background:
  * def mockServer = karate.start('classpath:mocks/users-mock.feature', 8080)
  * def baseUrl = 'http://localhost:8080'

This is particularly useful for testing microservices in isolation or when the real backend isn't available.

Configuration Environments

karate-config.js supports environment switching:

function fn() {
  var env = karate.env;  // reads karate.env system property
  
  var config = {
    env: env,
    baseUrl: 'https://api.example.com'
  };
  
  if (env == 'staging') {
    config.baseUrl = 'https://staging.api.example.com';
  } else if (env == 'local') {
    config.baseUrl = 'http://localhost:8080';
  }
  
  return config;
}

Run with: mvn test -Dkarate.env=staging

Reporting

Karate generates HTML reports automatically. With the Maven Surefire plugin:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <argLine>-Dkarate.env=${karate.env}</argLine>
  </configuration>
</plugin>

Reports appear in target/karate-reports/. Each report shows request/response details, timing, and pass/fail per scenario.

For CI/CD dashboards, use the JUnit XML output in target/surefire-reports/.

Performance Testing

Karate integrates with Gatling for performance tests. The same feature files run as load scenarios:

class UsersSimulation extends Simulation {
  setUp(
    scenario("Create users").exec(karateFeature("classpath:features/users/create.feature"))
      .inject(rampUsers(100).during(60))
  ).protocols(karateProtocol(
    uri("/users").method("POST").tag("create")
  ));
}

When to Use Karate

Karate is the right tool when:

  • Your team writes API tests but struggles with Java boilerplate
  • You want mocking, performance testing, and functional tests in one framework
  • Your APIs are JSON/XML-heavy and you want assertion power without custom matchers
  • You need parallel execution without framework configuration

Karate is less suitable when:

  • You need tight integration with an existing Java test suite using JUnit/TestNG patterns
  • Your team prefers code over DSL (REST Assured fits better)
  • You're doing end-to-end browser tests (Playwright/Cypress is better)
  • Non-technical stakeholders need to write or maintain tests (the learning curve is real)

What HelpMeTest Adds

Karate tests are comprehensive but they still require setup, maintenance, and a developer to write them. HelpMeTest lets non-technical team members define and run API checks in plain English — no Karate feature files, no JVM setup. The two tools complement each other: use Karate for deep API automation in CI, use HelpMeTest for ongoing monitoring and smoke checks that PMs and QA leads can run themselves.

Read more

Start now free