Karate DSL API Testing: Getting Started Guide

Karate DSL API Testing: Getting Started Guide

Karate DSL is an open-source framework that lets you write API tests in plain Gherkin-like syntax without writing any Java. The same .feature files you use to describe behavior also execute HTTP requests, assert responses, and chain calls together. This guide walks through setup and your first real tests.

What Karate Actually Is

Karate is built on top of Cucumber-JVM but replaces the need for step definitions. Every Karate keyword (Given, When, Then, And) maps directly to built-in HTTP and assertion functionality. You describe what the API should do and Karate handles the execution.

The key distinction from standard Cucumber: you don't write Java glue code. The DSL is the test.

Setup

Maven

Add the dependency to pom.xml:

<dependency>
    <groupId>com.intuit.karate</groupId>
    <artifactId>karate-junit5</artifactId>
    <version>1.4.1</version>
    <scope>test</scope>
</dependency>

Create a JUnit 5 runner class:

import com.intuit.karate.junit5.Karate;

class ApiTests {
    @Karate.Test
    Karate testAll() {
        return Karate.run("classpath:api").relativeTo(getClass());
    }
}

Gradle

testImplementation 'com.intuit.karate:karate-junit5:1.4.1'

Place your .feature files under src/test/resources. Karate picks them up from the classpath.

Your First GET Test

Create src/test/resources/api/users.feature:

Feature: Users API

  Background:
    * url 'https://jsonplaceholder.typicode.com'

  Scenario: Get a single user
    Given path '/users/1'
    When method GET
    Then status 200
    And match response.id == 1
    And match response.name == 'Leanne Graham'
    And match response.email == '#notnull'

Background runs before every scenario in the file. url sets the base URL. path appends to it. method GET fires the request. status 200 asserts the HTTP status code. match does deep equality or fuzzy matching.

Run it with:

mvn test -Dtest=ApiTests

Writing a POST Test

Scenario: Create a post
  Given url 'https://jsonplaceholder.typicode.com/posts'
  And request { title: 'foo', body: 'bar', userId: 1 }
  When method POST
  Then status 201
  And match response.title == 'foo'
  And match response.id == '#number'

request sets the request body. Karate automatically sets Content-Type: application/json when the body is a JSON object literal.

Assertions

Karate's match keyword is its strongest feature. It handles exact values, type checks, regex, and partial matching.

Exact match

And match response.status == 'active'

Type check

And match response.id == '#number'
And match response.name == '#string'
And match response.createdAt == '#notnull'

Fuzzy match in arrays

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

Array contains

And match response contains { id: 1 }

Each element in array

And match each response == { id: '#number', name: '#string' }

Schema validation

* def userSchema = { id: '#number', name: '#string', email: '#string' }
And match response == userSchema

Chaining Requests

A common need is using a response value in the next request — for example, creating a resource and then fetching it.

Scenario: Create and retrieve post
  # Create
  Given url 'https://jsonplaceholder.typicode.com/posts'
  And request { title: 'test post', body: 'content', userId: 1 }
  When method POST
  Then status 201

  * def postId = response.id

  # Retrieve
  Given path '/posts/' + postId
  When method GET
  Then status 200
  And match response.title == 'test post'

* def postId = response.id captures the value into a variable. The * prefix means "execute this step regardless of Given/When/Then position."

Headers and Authentication

Set headers globally in Background:

Background:
  * url 'https://api.example.com'
  * header Authorization = 'Bearer ' + token
  * header Content-Type = 'application/json'

Or per-request:

Given header X-Custom-Header = 'value'

For token-based auth where you need to fetch the token first:

Background:
  * url 'https://api.example.com'
  * def authResult = call read('auth.feature')
  * def token = authResult.token
  * header Authorization = 'Bearer ' + token

call read('auth.feature') executes another feature file and returns its last response. This is how you share auth setup across test files.

Query Parameters

Given path '/users'
And param role = 'admin'
And param page = 1
When method GET
Then status 200

Or inline:

Given url 'https://api.example.com/users?role=admin&page=1'

Configuration and Environments

Create src/test/resources/karate-config.js:

function fn() {
  var env = karate.env; // read from -Dkarate.env
  var config = {
    baseUrl: 'https://api.dev.example.com'
  };
  if (env === 'staging') {
    config.baseUrl = 'https://api.staging.example.com';
  }
  if (env === 'prod') {
    config.baseUrl = 'https://api.example.com';
  }
  return config;
}

Karate automatically loads this file before any tests run. Variables defined here are available in all feature files.

Switch environments:

mvn test -Dkarate.env=staging

Running Tests in Parallel

Karate supports parallel execution natively:

import com.intuit.karate.Results;
import com.intuit.karate.Runner;

class ParallelTests {
    @Test
    void testParallel() {
        Results results = Runner.path("classpath:api")
            .parallel(5); // 5 threads
        assertEquals(0, results.getFailCount(), results.getErrorMessages());
    }
}

Each scenario runs independently. Karate manages thread safety for you.

Reports

After running tests, Karate generates HTML reports at target/karate-reports/. The default report shows each scenario, each step, the request sent, and the response received. Failed assertions show the actual vs expected values inline.

For CI integration, Karate also outputs JUnit XML (target/surefire-reports/) compatible with Jenkins, GitHub Actions, and most CI systems.

Project Structure

A typical Karate project looks like:

src/test/
  java/
    ApiTests.java           # JUnit runner
  resources/
    karate-config.js        # global config
    api/
      users.feature
      posts.feature
      auth.feature          # shared auth
    helpers/
      common.feature        # reusable steps

What Karate Is Good At

  • APIs where you want readable test specs without Java boilerplate
  • Teams where non-Java developers need to write tests
  • Scenarios with response chaining and complex JSON matching
  • Projects that need data-driven tests (Karate supports Scenario Outline with Examples tables)

What It's Not

Karate is not a substitute for contract testing (use Pact for that). It doesn't have built-in test data management — you handle fixtures yourself via JSON files or * def variables. And while it supports UI testing via Karate UI, that's a separate concern from API testing.

The learning curve is low for the basics and steeper for advanced JavaScript expressions in match predicates. Start with simple match assertions and add complexity only when the test requires it.

Could not load content
Start now free