π₯ Unified, Step-Definition-Free API Automation
Traditional Behavior-Driven Development (BDD) frameworks like standard Cucumber require writing Gherkin feature files backed by laborious, repetitive Java step definition glue code, POJO serialization classes, and external HTTP clients. Karate Framework fundamentally disrupts this complexity by treating HTTP transactions, JSON documents, and XML payloads as native first-class citizens directly inside .feature files with zero Java step definitions required. Built on an embedded GraalVM JavaScript engine, Karate enables test engineers to construct dynamic request bodies, inject query parameters, execute JSONPath assertions, invoke reusable feature files via karate.call(), and match complex schemas using concise fuzzy matchers ('#string', '#regex'). With built-in parallel test execution, environment switching via karate-config.js, and rich HTML reporting, Karate significantly reduces the lines of code needed to maintain enterprise API regression suites.
TRADITIONAL BDD AUTOMATION STACK (Cucumber + RestAssured):
ββββββββββββββββββββββββββ ββββββββββββββββββββββββββ ββββββββββββββββββββββββββ
β Gherkin Feature File β βββββΊ β Java Step Definitions β βββββΊ β Java POJO Models & β
β (Given / When / Then) β β (@When("I post data")) β β RestAssured Glue Code β
ββββββββββββββββββββββββββ ββββββββββββββββββββββββββ ββββββββββββββββββββββββββ
* High maintenance: Any text change in Gherkin requires updating regex bindings in Java step files!
KARATE FRAMEWORK ARCHITECTURE (Zero Step-Definitions):
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β SINGLE UNIFIED FEATURE FILE: student_enrollment.feature β
β β
β Given url 'https://api.nikita-infotech.com/v1/students' β
β And header Authorization = 'Bearer ' + authToken β
β And request { fullName: 'Nikita Sharma', courseCode: 'API-PRO-101', age: 24 } β
β When method post β
β Then status 201 β
β And match response == { id: '#regex ^STU-[0-9]{5}$', fullName: 'Nikita Sharma', status: '#present' } β
ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β
βΌ (Direct GraalVM Execution Engine)
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BUILT-IN KARATE ENGINE PIPELINE: β
β * Native JSON/XML Parser * Embedded JavaScript Engine (GraalVM) * Apache HTTP Client Pool β
β * Fuzzy Matchers Engine * karate-config.js Environment Hub * HTML & Cucumber Reports β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
Feature: Student Management Enterprise CRUD API Regression
Background:
# Background executes before every Scenario in this feature
* url baseUrl
* header Accept = 'application/json'
* header Authorization = 'Bearer ' + authToken
* def uniqueTimestamp = function(){ return java.lang.System.currentTimeMillis() }
Scenario: Execute complete lifecycle: Create, Read, Update, and Purge Student
# 1. CREATE RESOURCE (POST)
Given path 'students'
And def studentEmail = 'student.' + uniqueTimestamp() + '@nikita-infotech.com'
And request
"""
{
"fullName": "Nikita Sharma",
"email": "#(studentEmail)",
"courseCode": "API-PRO-101",
"credits": 4
}
"""
When method post
Then status 201
And match response.id == '#present'
# Capture dynamic primary key for downstream calls
* def createdStudentId = response.id
# 2. READ CREATED RESOURCE (GET)
Given path 'students', createdStudentId
When method get
Then status 200
And match response.fullName == 'Nikita Sharma'
And match response.email == studentEmail
# 3. FULL REPLACEMENT UPDATE (PUT)
Given path 'students', createdStudentId
And request { "fullName": "Nikita Sharma", "email": "#(studentEmail)", "courseCode": "PY-ML-202", "credits": 5 }
When method put
Then status 200
And match response.courseCode == 'PY-ML-202'
And match response.credits == 5
# 4. TEARDOWN RESOURCE (DELETE)
Given path 'students', createdStudentId
When method delete
Then status 204
# 5. VERIFY 404 ON SUBSEQUENT RETRIEVAL
Given path 'students', createdStudentId
When method get
Then status 404
match statements.
Feature: Contract Schema Validation via Karate Fuzzy Matchers
Scenario: Assert student profile schema structure and data types
Given url 'https://api.nikita-infotech.com/v1/students/STU-88219'
When method get
Then status 200
# Define reusable JSON Schema template using Karate Fuzzy Matchers
* def studentSchema =
"""
{
"id": "#regex ^STU-[0-9]{5}$",
"fullName": "#string",
"email": "#regex ^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$",
"age": "#number? _ >= 18 && _ <= 65",
"gpa": "#number",
"isActive": "#boolean",
"phoneNumber": "##string",
"enrolledCourses": "#[] #string",
"metadata": {
"createdAt": "#? isValidDate(_)",
"accountTier": "#? _ == 'PRO' || _ == 'ENTERPRISE'"
}
}
"""
# Single-line full contract assertion:
And match response == studentSchema
# Granular Assertions on Array Elements:
# Asserts enrolledCourses contains at least 1 string item
And match response.enrolledCourses == '#[? _ != null]'
# Asserts that 'API-PRO-101' is an element within the array
And match response.enrolledCourses contains 'API-PRO-101'
karate-config.js is the central configuration engine for Karate. Executed before every test, it detects the active environment (karate.env), sets base URLs, and manages service credentials.
function fn() {
// 1. Detect active environment passed via CLI: mvn test -Dkarate.env=staging
var env = karate.env;
karate.log('[*] Initializing Karate Configuration for Environment:', env);
if (!env) {
env = 'staging'; // Default environment fallback
}
// 2. Base Configuration Dictionary
var config = {
env: env,
baseUrl: 'https://staging-api.nikita-infotech.com/v1',
authUrl: 'https://staging-auth.nikita-infotech.com/oauth/token',
authToken: 'initial_mock_token_99214',
requestTimeout: 6000
};
// 3. Environment-Specific Overrides
if (env === 'dev') {
config.baseUrl = 'http://localhost:8080/v1';
config.authUrl = 'http://localhost:8080/oauth/token';
} else if (env === 'staging') {
config.baseUrl = 'https://staging-api.nikita-infotech.com/v1';
config.authToken = 'eyStagingSecretToken9912048';
} else if (env === 'prod') {
config.baseUrl = 'https://api.nikita-infotech.com/v1';
// Production tokens injected via system environment variables
config.authToken = karate.properties['PROD_API_TOKEN'];
}
// 4. Configure Global HTTP Client Timeouts and Retries
karate.configure('connectTimeout', config.requestTimeout);
karate.configure('readTimeout', config.requestTimeout);
karate.configure('logPrettyRequest', true);
karate.configure('logPrettyResponse', true);
return config;
}
karate.call() and karate.callonce() to invoke helper feature files and pass parameters between scenarios.
# ==============================================================================
# HELPER FEATURE FILE: src/test/java/helpers/authenticate.feature
# ==============================================================================
@ignore
Feature: Reusable OAuth 2.0 Token Generation Helper
Scenario: Acquire fresh Bearer Token
Given url authUrl
And form field grant_type = 'client_credentials'
And form field client_id = 'qa_runner_01'
And form field client_secret = 'SecretKey#2026'
When method post
Then status 200
# Export variable to caller feature
* def sessionToken = response.access_token
# ==============================================================================
# CONSUMING FEATURE FILE: src/test/java/features/course_enrollment.feature
# ==============================================================================
Feature: Course Enrollment Scenarios Consuming Auth Helper
Background:
* url baseUrl
# callonce executes authenticate.feature ONLY ONCE and caches the result for the entire feature!
* def authResult = callonce read('classpath:helpers/authenticate.feature')
* def bearerToken = authResult.sessionToken
* header Authorization = 'Bearer ' + bearerToken
Scenario: Enroll student into course track using shared token
Given path 'enrollments'
And request { "studentId": "STU-88219", "courseCode": "API-PRO-101" }
When method post
Then status 201
And match response.enrollmentId == '#present'
Scenario Outline and Examples: blocks. Karate natively supports in-line Gherkin tables, external CSV files, and external JSON datasets.
Feature: Parameterized Student Enrollment Matrix
# OPTION 1: INLINE GHERKIN EXAMPLES TABLE
Scenario Outline: Validate course fee calculations for course <courseCode>
Given url baseUrl
And path 'courses', '<courseCode>', 'calculate-fee'
And param scholarship = '<isScholarship>'
When method get
Then status <expectedStatus>
And match response.totalFee == <expectedFee>
Examples:
| courseCode | isScholarship | expectedStatus | expectedFee |
| API-PRO-101 | false | 200 | 14999.00 |
| API-PRO-101 | true | 200 | 7499.50 |
| PY-ML-202 | false | 200 | 19999.00 |
# OPTION 2: EXTERNAL CSV FILE INGESTION (Dynamically loops over all CSV rows!)
Scenario Outline: Ingest boundary cases from external CSV dataset
Given url baseUrl
And path 'students'
And request { fullName: '<name>', courseCode: '<code>', age: <age> }
When method post
Then status <status>
# Ingests external CSV file located at src/test/resources/data/boundary_students.csv
Examples:
| read('classpath:data/boundary_students.csv') |
Feature: Java Interoperability and Custom JS Helpers
Scenario: Generate custom cryptographic tokens using Java classes directly
# 1. Calling standard Java JDK methods directly:
* def javaUUID = java.util.UUID.randomUUID().toString()
* def currentTime = java.lang.System.currentTimeMillis()
* print 'Generated Dynamic UUID:', javaUUID
# 2. Instantiating custom framework Java classes:
# Points to com.nikitainfotech.api.util.HashGenerator
* def HashUtil = Java.type('com.nikitainfotech.api.util.HashGenerator')
* def computedHmac = HashUtil.generateHmacSha256("payload_data", "secret_key_2026")
* print 'Computed HMAC Signature:', computedHmac
# 3. Inline JavaScript function for date validation:
* def isValidDate =
"""
function(dateStr) {
var SimpleDateFormat = Java.type('java.text.SimpleDateFormat');
var sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
try {
sdf.parse(dateStr);
return true;
} catch(e) {
return false;
}
}
"""
# 4. Use inline JS function in request validation:
Given url 'https://api.nikita-infotech.com/v1/health'
When method get
Then status 200
And match response.timestamp == '#? isValidDate(_)'
Results runner. Configures thread count, tags filtering, and generates aggregated HTML reports.
package com.nikitainfotech.api.runners;
import com.intuit.karate.Results;
import com.intuit.karate.Runner;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
public class KarateParallelTest {
@Test
void testAllFeaturesInParallel() {
// Configure parallel execution runner
Results results = Runner.path("classpath:features")
.outputCucumberJson(true) // Generates JSON for Cucumber reports
.tags("~@ignore", "@regression") // Skip @ignore tags, execute @regression
.parallel(5); // Run across 5 concurrent worker threads
System.out.println("==========================================================");
System.out.println("KARATE PARALLEL EXECUTION METRICS AUDIT:");
System.out.println(" Total Scenarios Executed : " + results.getScenariosTotal());
System.out.println(" Passed Scenarios : " + results.getScenariosPassed());
System.out.println(" Failed Scenarios : " + results.getFailCount());
System.out.println(" Execution Duration : " + results.getTimeTakenMillis() + " ms");
System.out.println(" HTML Report Path : " + results.getReportDir());
System.out.println("==========================================================");
// Assert zero test failures for CI/CD deployment gating
assertEquals(0, results.getFailCount(),
results.getErrorMessages() + " - Karate regression run had test failures!");
}
}
.feature files to stub third-party dependencies during testing.
Feature: Mock Third-Party Payment Gateway Service
Background:
* def port = 8085
# Scenario matching incoming HTTP POST calls to /gateway/charge
Scenario: pathMatches('/gateway/charge') && methodIs('post')
* def requestAmount = request.amount
# Conditional logic based on payload amount
* def responseStatus = requestAmount > 50000 ? 'DECLINED' : 'SETTLED'
* def responseCode = requestAmount > 50000 ? 402 : 200
* responseStatus responseCode
* response =
"""
{
"transactionId": "TXN-MOCK-" + java.util.UUID.randomUUID().toString().substring(0, 8),
"status": "#(responseStatus)",
"amount": "#(requestAmount)",
"gatewayTimestamp": java.lang.System.currentTimeMillis()
}
"""
# Fallback 404 for unhandled mock endpoints
Scenario:
* responseStatus 404
* response = { "error": "Endpoint not matched in mock server" }
KARATE DSL SYNTAX & MATCHERS REFERENCE MATRIX:
βββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ
β KEYWORD / MATCHER β SYNTAX EXAMPLE β PRIMARY PURPOSE & BEHAVIOR β
βββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββ€
β url / path β Given url '..'; path 'user' β Assembles full target HTTP request endpoint URI β
β param / params β And param limit = 20 β Sets single or multiple query parameters (?p=20) β
β header / headers β And header Accept = 'app/jsonβ Sets request headers (supports JS object maps) β
β request β And request { name: 'Nikita'}β Sets payload body (JSON, XML, or multi-line text)β
β method β When method post / get / del β Dispatches the HTTP request method over wire β
β status β Then status 200 / 201 / 404 β Asserts expected HTTP response status code β
β match == β And match response == {..} β Deep equality assertion on response body β
β match contains β And match response contains β Partial subset assertion (checks declared fields)β
β match != β And match response.id != nullβ Negation inequality assertion β
β #string / #number β "id": "#string", "age": "#numβ Fuzzy matchers asserting field data types β
β #present / #null β "tag": "#present" β Asserts key exists vs. explicitly null β
β call / callonce β def res = call read('x.feat')β Reusable feature file invocation and chaining β
β karate.env β var env = karate.env β Reads target environment property from CLI/runnerβ
βββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 KARATE FRAMEWORK BEST PRACTICES: β
β 1. Zero Java step definitions: Write all assertions and logic directly in .feature files. β
β 2. Use fuzzy matchers (#string, #number): Validate contracts without hardcoding transient values. β
β 3. Manage state in karate-config.js: Decouple base URLs and credentials by environment tier. β
β 4. Cache auth with callonce: Run login features once per suite to minimize redundant token requests. β
β 5. Run tests in parallel: Use Runner.path().parallel(N) to maximize test throughput across CPU cores. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ