Skip to main content

HTTP RESPONSES

Response Time

Monitor and validate API response times for performance testing and SLA compliance using the responseTime variable.

Benefits of Response Time Monitoring

  • SLA validation: Ensure APIs meet performance requirements and service level agreements
  • Performance tracking: Identify slow endpoints before they impact production
  • Regression detection: Catch performance degradation during development and testing

Basic Response Time

Access response time after any HTTP request using the responseTime variable:

Scenario: Simple response time check
Given url 'https://api.example.com'
And path 'users'
When method get
Then status 200
And assert responseTime < 1000
* print 'Response time:', responseTime, 'ms'

The responseTime variable contains the response time in milliseconds and is available immediately after each HTTP request completes.

Response Time Assertions

Validate API performance against SLA requirements:

Scenario: SLA compliance check
Given url baseUrl
And path 'api/search'
And param query = 'products'
When method get
Then status 200
And assert responseTime < 2000
And assert response.results.length > 0

* def timing = responseTime
* print 'Search completed in', timing, 'ms'

Use assertions to enforce performance requirements and fail tests when APIs respond too slowly.

Performance Categorization

Categorize API performance using conditional logic:

Scenario: Performance category validation
Given url baseUrl
And path 'api/users'
When method get
Then status 200

* def category = responseTime < 500 ? 'excellent' : responseTime < 1000 ? 'good' : responseTime < 2000 ? 'acceptable' : 'poor'
* print 'Performance category:', category
* assert category != 'poor'

* if (responseTime > 1000) karate.log('Warning: slow response detected')

Ternary operators provide concise performance categorization for different response time thresholds.

Tracking Multiple Endpoints

Monitor performance across different API endpoints:

Scenario: Multi-endpoint monitoring
* def timings = []

Given url baseUrl
And path 'users'
When method get
Then status 200
* timings.push({ endpoint: 'users', time: responseTime })

And path 'products'
When method get
Then status 200
* timings.push({ endpoint: 'products', time: responseTime })

And path 'orders'
When method get
Then status 200
* timings.push({ endpoint: 'orders', time: responseTime })

* def avgTime = timings.reduce((sum, t) => sum + t.time, 0) / timings.length
* print 'Average response time:', avgTime, 'ms'
* assert avgTime < 1000

Store timing data in arrays to analyze performance across multiple endpoints and calculate averages.

Advanced Performance Analysis

Use functions to analyze and report performance metrics:

Scenario: Performance analysis with functions
* def performanceLog = []
* def recordTiming =
"""
function(endpoint) {
performanceLog.push({
endpoint: endpoint,
time: karate.get('responseTime'),
timestamp: new Date().toISOString()
});
}
"""

Given url baseUrl
And path 'api/users'
When method get
Then status 200
* recordTiming('/api/users')

And path 'api/products'
When method get
Then status 200
* recordTiming('/api/products')

* def slowEndpoints = performanceLog.filter(x => x.time > 1000)
* def avgTime = performanceLog.reduce((sum, x) => sum + x.time, 0) / performanceLog.length
* print 'Slow endpoints:', slowEndpoints.length
* assert avgTime < 1500

JavaScript functions enable sophisticated performance tracking and analysis patterns for complex test scenarios.

Request Timestamp

Compare responseTime with requestTimeStamp for detailed timing analysis:

Scenario: Timing correlation analysis
* def clientStart = new Date().getTime()

Given url baseUrl
And path 'api/operation'
When method post
And request { data: 'test' }
Then status 200

* def clientEnd = new Date().getTime()
* def clientElapsed = clientEnd - clientStart
* def networkTime = responseTime
* def overhead = clientElapsed - networkTime

* print 'Network time:', networkTime, 'ms'
* print 'Test overhead:', overhead, 'ms'
* print 'Request timestamp:', requestTimeStamp
* assert overhead < 100

The requestTimeStamp variable captures when the request was initiated, useful for correlating with external timing measurements.

Key Points
  • responseTime measures network round-trip time in milliseconds
  • Timing variables reset after each HTTP request
  • Use requestTimeStamp for detailed timing correlation

Common Gotchas

Timing includes network latency

# responseTime = network latency + server processing
* assert responseTime < 1000

The responseTime variable measures total round-trip time, not just server processing.

Variables reset after requests

* def firstTiming = responseTime
When method get
* print responseTime # Different value from firstTiming

Store timing values in variables before making new requests if you need to compare them.

Next Steps

Master response time monitoring and continue with: