π Modular Component Engineering for Scale in Karate API Testing
In enterprise API automation suites spanning dozens of microservices, repetitive setup codeβsuch as OAuth 2.0 token acquisition, database test-tenant seeding, or generating authenticated headersβquickly bloats test repositories. Duplicating these multi-step handshakes across every feature file violates the DRY (Don't Repeat Yourself) principle and creates maintenance bottlenecks whenever an authentication contract changes. Karate Framework treats feature files as reusable, parameterized functions through its built-in calling engine: karate.call() and karate.callonce(). By decoupling operational workflows into isolated helper features (tagged with @ignore), passing dynamic JSON input arguments, caching idempotent tokens across entire test execution runs, and chaining scenario outputs, engineering teams construct robust, composable, and blazing-fast end-to-end API testing pipelines.
call (re-executed per invocation) and callonce (executed once and cached in memory across scenarios), showing the variable scope and lifecycle pipeline.
REUSABLE FEATURE CALL LIFECYCLE ARCHITECTURE:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CALLER FEATURE (e.g. course_management.feature) β
β β
β Background: β
β * def auth = callonce read('classpath:helpers/auth_generator.feature') β
β * def createStudent = read('classpath:helpers/create_student.feature') β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β β
(Executed ONLY ONCE) (Executed PER INVOCATION)
βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββ
β callonce read('auth_generator.feature') β β call read('create_student.feature') arg β
β β β β
β 1. Executes HTTP POST /oauth/token β β 1. Receives input: { name: 'Aarav' } β
β 2. Yields response.access_token β β 2. Provisions fresh DB entity β
β 3. CACHES output map in memory β β 3. Yields unique generated student ID β
β 4. Reused across Scenarios 1, 2, 3... β β 4. Isolated scope; fresh entity per callβ
βββββββββββββββββββββββββββββββββββββββββββββ βββββββββββββββββββββββββββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β CONSUMING SCENARIOS IN CALLER FEATURE: β
β β
β Scenario: Enroll Student Alpha β
β * header Authorization = 'Bearer ' + auth.token <-- Zero redundant login network latency! β
β * def s1 = call createStudent { name: 'Aarav' } <-- Dedicated test entity provisioned! β
β β
β Scenario: Enroll Student Beta β
β * header Authorization = 'Bearer ' + auth.token <-- Read directly from in-memory cache β
β * def s2 = call createStudent { name: 'Rohan' } <-- Fresh independent entity provisioned β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
src/test/java/helpers/token_generator.feature. Marked with @ignore to prevent standalone execution, this helper requests an OAuth 2.0 Bearer token and exports it for caller features.
@ignore
Feature: Reusable Enterprise Token Generator Helper
# @ignore tag ensures this feature does NOT run standalone during test suite discovery.
# It is designed solely to be invoked via 'call' or 'callonce'.
Background:
* url authUrl
* configure ssl = true
Scenario: Acquire short-lived OAuth 2.0 Bearer Token
Given form field grant_type = 'client_credentials'
And form field client_id = clientId
And form field client_secret = clientSecret
And form field scope = 'courses.write students.manage'
When method post
Then status 200
# Explicitly define variables to be exported to calling features:
* def bearerToken = response.access_token
* def tokenType = response.token_type
* def tokenExpiry = response.expires_in
* def authHeader = tokenType + ' ' + bearerToken
# Debug print statement visible in Karate test report logs:
* print '[+] Helper successfully minted fresh token expiring in:', tokenExpiry, 'seconds'
# ==============================================================================
# HELPER FEATURE: src/test/java/helpers/create_student_helper.feature
# ==============================================================================
@ignore
Feature: Parameterized Student Creation Helper
Background:
* url baseUrl
Scenario: Provision new student using caller-provided argument dictionary
# When an argument is passed into 'call', it becomes directly accessible as variables!
# Caller passes: { targetName: 'Nikita Sharma', targetCourse: 'API-PRO-101', targetAge: 24 }
* def uniqueEmail = 'test.' + java.util.UUID.randomUUID().toString().substring(0, 8) + '@nikita-infotech.com'
Given path 'students'
And header Authorization = activeAuthHeader
And request
"""
{
"fullName": '#(targetName)',
"email": '#(uniqueEmail)',
"courseCode": '#(targetCourse)',
"age": '#(targetAge)',
"status": "ENROLLED"
}
"""
When method post
Then status 201
# Export created ID and full payload for caller assertions
* def generatedId = response.id
* def studentRecord = response
# ==============================================================================
# CALLER FEATURE: src/test/java/features/enrollment_test.feature
# ==============================================================================
Feature: Verify Enrollment Using Parameterized Helper
Background:
* url baseUrl
* def auth = callonce read('classpath:helpers/token_generator.feature')
* def activeAuthHeader = auth.authHeader
Scenario: Provision two distinct students with custom parameters
# Call 1: Provision Candidate Alpha
* def student1 = call read('classpath:helpers/create_student_helper.feature') { targetName: 'Nikita Sharma', targetCourse: 'API-PRO-101', targetAge: 24 }
* match student1.generatedId == '#regex ^STU-[0-9]{5}$'
* match student1.studentRecord.fullName == 'Nikita Sharma'
# Call 2: Provision Candidate Beta with different parameters
* def student2 = call read('classpath:helpers/create_student_helper.feature') { targetName: 'Aarav Deshmukh', targetCourse: 'PY-ML-202', targetAge: 22 }
* match student2.generatedId == '#regex ^STU-[0-9]{5}$'
* match student2.studentRecord.courseCode == 'PY-ML-202'
# Assert entities are completely distinct
* match student1.generatedId != student2.generatedId
@create, @delete, @query). Calling specific scenarios within a feature using tag filtering avoids creating dozens of single-scenario files.
# ==============================================================================
# MULTI-SCENARIO HELPER: src/test/java/helpers/student_operations.feature
# ==============================================================================
@ignore
Feature: Consolidated Student Entity Operations Helper
Background:
* url baseUrl
* header Authorization = activeAuthHeader
@create
Scenario: Create Student Entity
Given path 'students'
And request { fullName: targetName, courseCode: targetCourse, email: 'auto@nikita-infotech.com' }
When method post
Then status 201
* def newId = response.id
@query
Scenario: Retrieve Student Entity by ID
Given path 'students', targetId
When method get
Then status 200
* def fetchedStudent = response
@delete
Scenario: Purge Student Entity
Given path 'students', targetId
When method delete
Then status 204
# ==============================================================================
# CALLER FEATURE: Calling specific tagged scenarios
# ==============================================================================
Feature: Execute Tag-Targeted Helper Calls
Background:
* url baseUrl
* def auth = callonce read('classpath:helpers/token_generator.feature')
* def activeAuthHeader = auth.authHeader
Scenario: Execute complete lifecycle using single tagged helper file
# 1. Invoke ONLY the @create scenario:
* def createRes = call read('classpath:helpers/student_operations.feature@create') { targetName: 'Rohan Verma', targetCourse: 'API-PRO-101' }
* def studentId = createRes.newId
# 2. Invoke ONLY the @query scenario:
* def queryRes = call read('classpath:helpers/student_operations.feature@query') { targetId: studentId }
* match queryRes.fetchedStudent.fullName == 'Rohan Verma'
# 3. Invoke ONLY the @delete scenario:
* def deleteRes = call read('classpath:helpers/student_operations.feature@delete') { targetId: studentId }
karate.call() executes the target helper feature iteratively in a loopβonce for each element in the arrayβreturning a list of collected results.
Feature: Batch Entity Provisioning via Iterative Feature Calling
Background:
* url baseUrl
* def auth = callonce read('classpath:helpers/token_generator.feature')
* def activeAuthHeader = auth.authHeader
Scenario: Seed an entire batch of students by calling helper with an array of records
# 1. Define array of input parameter dictionaries
* def studentSeedList =
"""
[
{ targetName: 'Student Alpha', targetCourse: 'API-PRO-101', targetAge: 21 },
{ targetName: 'Student Beta', targetCourse: 'PY-ML-202', targetAge: 23 },
{ targetName: 'Student Gamma', targetCourse: 'SEC-303', targetAge: 25 }
]
"""
# 2. When 'call' receives an ARRAY, it executes the feature once per array item!
* def batchResults = call read('classpath:helpers/create_student_helper.feature') studentSeedList
# 3. 'batchResults' is now an array containing the outputs of all 3 executions:
* match batchResults == '#[3]'
# Extract all generated IDs across the loop
* def createdIds = $batchResults[*].generatedId
* print '[+] Generated Batch Student IDs:', createdIds
* match createdIds == '#[3] #string'
# Assert all 3 records were successfully stored
* match batchResults[0].studentRecord.fullName == 'Student Alpha'
* match batchResults[1].studentRecord.fullName == 'Student Beta'
* match batchResults[2].studentRecord.fullName == 'Student Gamma'
Feature: End-to-End Multi-Microservice Workflow Chaining
Background:
* url baseUrl
* def auth = callonce read('classpath:helpers/token_generator.feature')
* def activeAuthHeader = auth.authHeader
Scenario: Complete Student Registration, Course Allocation, and Invoice Generation Chain
# ==========================================================================
# STEP 1: Provision Student Record via Student Microservice Helper
# ==========================================================================
* def studentSetup = call read('classpath:helpers/create_student_helper.feature') { targetName: 'Nikita Sharma', targetCourse: 'API-PRO-101', targetAge: 24 }
* def studentId = studentSetup.generatedId
# ==========================================================================
# STEP 2: Query Course Details from Catalog Microservice
# ==========================================================================
Given path 'catalog', 'courses', 'API-PRO-101'
And header Authorization = activeAuthHeader
When method get
Then status 200
* def courseFee = response.price
* def courseTitle = response.title
# ==========================================================================
# STEP 3: Issue Financial Invoice via Billing Microservice Helper
# ==========================================================================
* def billingPayload =
"""
{
"studentId": '#(studentId)',
"courseCode": "API-PRO-101",
"billedAmount": '#(courseFee)',
"currency": "INR",
"dueDate": "2026-12-01"
}
"""
Given path 'billing', 'invoices'
And header Authorization = activeAuthHeader
And request billingPayload
When method post
Then status 201
* def invoiceId = response.invoiceId
* match response.status == 'UNPAID'
# ==========================================================================
# STEP 4: Settle Invoice and Confirm Active Enrollment
# ==========================================================================
Given path 'billing', 'invoices', invoiceId, 'pay'
And header Authorization = activeAuthHeader
And request { "paymentMethod": "UPI", "upiId": "nikita@upi" }
When method post
Then status 200
* match response.status == 'SETTLED'
# Final query verifying student record reflects active paid enrollment
Given path 'students', studentId, 'status'
And header Authorization = activeAuthHeader
When method get
Then status 200
And match response.enrollmentStatus == 'CONFIRMED'
karate.env) or dynamic response flags using Karate's inline JavaScript ternary operator.
Feature: Conditional Feature Invocation Based on Runtime State
Background:
* url baseUrl
* def auth = callonce read('classpath:helpers/token_generator.feature')
* def activeAuthHeader = auth.authHeader
Scenario: Conditionally seed database ONLY if running on Staging or Dev
# Check environment variable configured in karate-config.js
* def isLocalOrStaging = (env === 'dev' || env === 'staging')
# CONDITIONAL CALL PATTERN:
# If isLocalOrStaging is true, execute database seed helper; else, return empty dummy object
* def seedResult = isLocalOrStaging ? karate.call('classpath:helpers/seed_mock_db.feature') : {}
Given path 'courses'
And header Authorization = activeAuthHeader
When method get
Then status 200
And match response == '#notnull'
Scenario: Conditionally reset cache only if response header flags stale cache
Given path 'analytics', 'realtime'
And header Authorization = activeAuthHeader
When method get
Then status 200
# Check if server emitted cache refresh flag
* def isCacheStale = response.staleDataFlag == true
# Conditionally invoke cache clearing helper:
* def cacheReset = isCacheStale ? karate.call('classpath:helpers/purge_cache.feature', { cluster: 'IN-WEST-1' }) : null
* print '[+] Cache reset execution result:', cacheReset
read(), mutating target keys in memory via karate.set(), and passing the updated object to reusable features.
Feature: External Data File Ingestion and Payload Mutation
Background:
* url baseUrl
* def auth = callonce read('classpath:helpers/token_generator.feature')
* def activeAuthHeader = auth.authHeader
Scenario: Ingest canonical JSON template, mutate specific fields, and call helper
# 1. Read static JSON template file from classpath
* def studentTemplate = read('classpath:data/canonical_student_template.json')
# Canonical Template contents:
# { "fullName": "DEFAULT", "email": "TEMP", "courseCode": "TEMP", "metadata": { "tier": "FREE" } }
# 2. Mutate specific fields in memory for this specific test case:
* set studentTemplate.fullName = 'Nikita Sharma'
* set studentTemplate.email = 'nikita.sharma@nikita-infotech.com'
* set studentTemplate.courseCode = 'API-PRO-101'
* set studentTemplate.metadata.tier = 'ENTERPRISE'
* set studentTemplate.credits = 4
# 3. Dispatch request with mutated template
Given path 'students'
And header Authorization = activeAuthHeader
And request studentTemplate
When method post
Then status 201
And match response.fullName == 'Nikita Sharma'
And match response.metadata.tier == 'ENTERPRISE'
# 4. Ingest CSV file as list of maps and pass to batch processing helper
* def coursesDataset = read('classpath:data/courses_catalog.csv')
* def batchCreation = call read('classpath:helpers/register_course_helper.feature') coursesDataset
* match batchCreation == '#[3]'
Feature: Automated Entity Provisioning and Teardown Orchestration
Background:
* url baseUrl
* def auth = callonce read('classpath:helpers/token_generator.feature')
* def activeAuthHeader = auth.authHeader
Scenario: Execute student enrollment with guaranteed cleanup
# 1. Provision ephemeral entity
* def setup = call read('classpath:helpers/create_student_helper.feature') { targetName: 'Temporary Cleanup Student', targetCourse: 'API-PRO-101', targetAge: 20 }
* def studentId = setup.generatedId
# 2. Execute functional test steps
Given path 'students', studentId, 'courses'
And header Authorization = activeAuthHeader
When method get
Then status 200
And match response == '#[]'
# 3. TEARDOWN EXECUTION: Invoke cleanup helper passing the provisioned ID
* def cleanupResult = call read('classpath:helpers/purge_student_helper.feature') { targetId: studentId }
* match cleanupResult.responseStatus == 204
# 4. Verification Check: Confirm entity no longer exists
Given path 'students', studentId
And header Authorization = activeAuthHeader
When method get
Then status 404
# ==============================================================================
# HELPER FEATURE: src/test/java/helpers/purge_student_helper.feature
# ==============================================================================
# @ignore
# Feature: Purge Student Entity
# Scenario:
# Given url baseUrl
# And path 'students', targetId
# And header Authorization = activeAuthHeader
# When method delete
# Then status 204
# * def responseStatus = responseStatus
KARATE FEATURE REUSABILITY REFERENCE MATRIX:
βββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββ¬βββββββββββββββββββββββββββββββββββββββββββββββββββ
β KEYWORD / FUNCTION β SYNTAX EXAMPLE β PRIMARY PURPOSE & BEHAVIOR β
βββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββΌβββββββββββββββββββββββββββββββββββββββββββββββββββ€
β call read('file.feature')β def res = call read('x.feat')β Re-executes helper feature on every invocation β
β callonce read('..') β def res = callonce read('..')β Executes feature ONCE; caches output in memory β
β Passing JSON Argument β call read('..') { k: 'v' } β Injects parameter dictionary into called feature β
β Passing Array (Loop) β call read('..') [ {..}, {..} ]β Iterates feature once per item in JSON array β
β Tag-Targeted Call β call read('file.feature@tag')β Invokes only the scenario matching the @tag β
β @ignore Tag β @ignore on Feature line β Excludes helper feature from standalone discoveryβ
β read('classpath:..') β def json = read('path/f.json')β Reads external JSON/CSV/JS files into memory β
β set payload.field β set payload.user.name = 'x' β Mutates specific fields in an in-memory JSON treeβ
β karate.call(feat, args) β karate.call('file.feature') β Programmatic JavaScript execution equivalent β
βββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββ΄βββββββββββββββββββββββββββββββββββββββββββββββββββ€
β TOP 5 MODULAR FEATURE DESIGN BEST PRACTICES: β
β 1. Always tag helpers with @ignore: Prevents test runners from executing helpers without required inputs. β
β 2. Cache auth with callonce: Run login handshakes once per feature to avoid rate limits and save time. β
β 3. Pass explicit arguments: Pass inputs as { key: value } rather than relying on global variable leaks. β
β 4. Group helpers by domain: Consolidate CRUD operations in one file using tags (@create, @delete). β
β 5. Clean up after mutating tests: Call teardown helpers to purge created entities and maintain isolation. β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ