Processors Tab

The Processors tab contains advanced features for request automation and validation: scripts that run before and after the request, and assertions that verify the response. These tools are essential for API testing and automation workflows.

Processor Types

The Processors tab contains three sub-tabs:

Pre-Script

Runs before the request is sent

Post-Script

Runs after the response is received

Assertions

Validates response conditions

Pre-Script

Pre-scripts execute JavaScript code before the request is sent. Use them to dynamically modify the request, set environment variables, log information for debugging, or perform pre-flight validation.

Available APIs

APIDescription
tg.request.methodHTTP method (read-only)
tg.request.urlFull request URL (read/write)
tg.request.headersRequest headers (read-only copy). Use setHeader() / removeHeader() to modify.
tg.request.bodyRequest body as string (read/write)
tg.request.setHeader(key, value)Add or update a request header
tg.request.removeHeader(key)Remove a request header
tg.environment.get(key)Read an environment variable
tg.environment.set(key, value)Set an environment variable (persisted)
tg.environment.has(key)Check if an environment variable exists
console.log() / info() / warn() / error()Log messages to script output
fetch(url, options)Make HTTP requests (async)
setTimeout(fn, ms)Delay execution

Example: Log Request Details

// Log request information for debugging
console.log('Method:', tg.request.method);
console.log('URL:', tg.request.url);
console.log('Headers:', JSON.stringify(tg.request.headers, null, 2));

if (tg.request.body) {
  console.log('Body:', tg.request.body);
}

Example: Modify Request Dynamically

// Add a dynamic header
tg.request.setHeader('X-Request-Id', crypto.randomUUID());

// Inject token from environment
const token = tg.environment.get('auth_token');
if (token) {
  tg.request.setHeader('Authorization', 'Bearer ' + token);
}

// Modify the URL dynamically
const baseUrl = tg.environment.get('base_url');
if (baseUrl) {
  tg.request.url = baseUrl + '/api/v2/users';
}

// Remove a header
tg.request.removeHeader('X-Debug');

Example: Validate Request Before Sending

// Check if required headers are present
if (!tg.request.headers['Authorization']) {
  console.warn('Warning: No Authorization header set');
}

// Validate JSON body structure
if (tg.request.body) {
  try {
    const body = JSON.parse(tg.request.body);
    if (!body.name) {
      console.error('Error: name field is required');
    }
  } catch (e) {
    console.error('Body is not valid JSON');
  }
}
Note: Pre-scripts run before the request is sent. All modifications made via tg.request are applied to the actual request. If the script throws an error, the error is logged but the request is still sent with the original values.

Post-Script

Post-scripts execute after the response is received. Use them to inspect response data, save values to environment variables, log results for debugging, or perform custom validation.

Available APIs

APIDescription
tg.response.statusHTTP status code (e.g., 200, 404)
tg.response.statusTextHTTP status text (e.g., "OK", "Not Found")
tg.response.headersResponse headers object
tg.response.bodyResponse body as string
tg.response.json()Parse body as JSON (cached — safe to call multiple times)
tg.response.timingTiming object: total, dns, tls, ttfb
tg.request.*Request data (read-only in post-scripts)
tg.environment.get(key)Read an environment variable
tg.environment.set(key, value)Set an environment variable (persisted)
tg.environment.has(key)Check if an environment variable exists
console.log() / info() / warn() / error()Log messages to script output
fetch(url, options)Make HTTP requests (async)
setTimeout(fn, ms)Delay execution

Example: Inspect Response

// Log response information for debugging
console.log('Status:', tg.response.status, tg.response.statusText);
console.log('Headers:', JSON.stringify(tg.response.headers, null, 2));

// Parse JSON body using the built-in json() helper
const data = tg.response.json();
console.log('Response data:', data);

Example: Save Values to Environment

// Extract token from login response and save for subsequent requests
if (tg.response.status === 200) {
  const data = tg.response.json();
  tg.environment.set('auth_token', data.access_token);
  tg.environment.set('user_id', String(data.user.id));
  console.log('Token saved to environment');
}

Example: Validate Response Structure

// Validate the response matches expected structure
if (tg.response.status === 200) {
  const data = tg.response.json();

  if (!data.id) {
    console.error('Missing required field: id');
  }

  if (!Array.isArray(data.items)) {
    console.error('items should be an array');
  } else {
    console.log('Found', data.items.length, 'items');
  }
}

Example: Log Timing Information

// Analyze request performance
const timing = tg.response.timing;

console.log('Total time:', timing.total, 'ms');
console.log('DNS lookup:', timing.dns, 'ms');
console.log('TLS handshake:', timing.tls, 'ms');
console.log('Time to first byte:', timing.ttfb, 'ms');
Note: Use tg.response.json() instead of JSON.parse(tg.response.body). The result is cached, so calling json() multiple times is safe and efficient. Environment variables set via tg.environment.set() are persisted immediately and available in subsequent requests.

Script Results

After execution, scripts show their results including:

SuccessScript completed without errors. Console output is displayed.
ErrorScript threw an error. Error message and stack trace are displayed.

Execution Duration

The time taken to execute the script is shown in milliseconds. Scripts have a 30-second timeout to prevent infinite loops.

Assertions

Assertions are declarative tests that validate the response. They provide a visual way to define expected conditions without writing code. Each assertion runs automatically after the request completes.

Assertion Structure

Each assertion consists of up to four parts:

TypeWhat to check: Status Code, Response Time, Header, JSON Path, or Body
PropertyFor Header and JSON Path types only: the header name or JSONPath expression
OperatorHow to compare: equals, contains, exists, less than, etc.
ExpectedThe value to compare against (not needed for exists, is empty, etc.)

Assertion Types

Status Code

Validates the HTTP status code returned by the server.

Available operators:
equalsnot equals><
Status Code equals 200
Status Code < 400// Any success (1xx, 2xx, 3xx)
Status Code > 199// Not informational

Response Time

Validates the total response time in milliseconds. Useful for performance testing.

Available operators:
<>equals
Response Time < 500 ms// Fast response
Response Time < 2000 ms// Acceptable for complex queries
Response Time < 100 ms// Cache hit expected

Header

Validates response headers. Header name matching is case-insensitive.

Available operators:
equalsnot equalscontainsnot containsexistsnot existsmatches regex
Header Content-Type contains "application/json"
Header Cache-Control contains "max-age"
Header X-RateLimit-Remaining exists
Header Set-Cookie matches regex "session=.*; HttpOnly"

JSON Path

Extracts a value from the JSON response body using JSONPath syntax, then validates it. This is the most flexible assertion type with access to all operators.

Available operators:
equalsnot equalscontainsnot contains><existsnot existsis emptyis not emptyis typematches regex
JSON Path $.success equals true
JSON Path $.data.id exists
JSON Path $.items is type array
JSON Path $.items.length > 0
JSON Path $.user.email matches regex "^[^@]+@[^@]+$"
JSON Path $.error not exists

JSONPath Syntax Reference

PathDescription
$Root object
$.propertyTop-level property
$.user.nameNested property
$.items[0]First array element (0-indexed)
$.items[-1]Last array element
$.items[0:3]Array slice (elements 0, 1, 2)
$.items[*]All array elements
$.items[*].idProperty from all array elements
$.items.lengthArray length
$..nameRecursive search for "name" at any depth
$.items[?(@.active)]Filter: items where active is truthy
$.items[?(@.price>100)]Filter: items where price > 100

Body

Validates the entire response body as raw text. Useful for non-JSON responses or full-body matching.

Available operators:
containsnot containsequalsis emptyis not emptymatches regex
Body contains "success"
Body not contains "error"
Body is not empty
Body matches regex "<html>.*</html>"

Operators Reference

Complete list of all comparison operators. Not all operators are available for all assertion types.

OperatorDescriptionExpects Value
equalsExact match. For JSON, compares normalized structure.Yes
not equalsPasses if values are different.Yes
containsSubstring match. For JSON, supports partial object matching.Yes
not containsPasses if value is not found.Yes
> (greater than)Numeric comparison. Both values converted to numbers.Yes
< (less than)Numeric comparison. Both values converted to numbers.Yes
existsPasses if value is not undefined or null.No
not existsPasses if value is undefined or null.No
is emptyPasses if: empty string, empty array [], empty object {}, null, or undefined.No
is not emptyPasses if value has content.No
matches regexRegular expression match. Supports multiline and cross-platform newlines.Yes (pattern)
is typeChecks JSON type: string, number, boolean, array, object, or null.Yes (type)
Smart Comparison: The equals and contains operators normalize JSON before comparison. This means {"a":1} equals { "a": 1 } regardless of whitespace.

Assertion Results

After sending a request, each assertion displays its result:

PassedThe assertion condition was met. A green checkmark appears next to the assertion, and a green left border highlights the row.
FailedThe assertion condition was not met. A red X appears next to the assertion, a red left border highlights the row, and an error message appears below showing expected vs actual values.

Tab Badge

The Processors tab header shows pass/fail counts as colored badges. A green badge shows passed count, a red badge shows failed count. This provides at-a-glance test status without opening the tab.

Summary Bar

At the bottom of the assertions panel, a summary shows the total count: "Results: X passed, Y failed". This appears only after a request has been sent.

Managing Assertions

Enable/Disable All

The "Enable Assertions" checkbox at the top controls whether assertions run at all. When unchecked, no assertions are evaluated regardless of individual assertion settings. This is useful for temporarily skipping validation during debugging.

Enable/Disable Individual

Each assertion row has its own checkbox. Unchecked assertions are skipped during evaluation but remain in the list. Use this to temporarily disable specific assertions without deleting them.

Add Assertion

Click the "Add" button to create a new assertion. New assertions default to:

  • Type: Status Code
  • Operator: equals
  • Expected: 200

Delete Assertion

Click the trash icon on any assertion row to delete it. This action is immediate and cannot be undone. If you accidentally delete an assertion, you will need to recreate it manually.

Assertion Order

Assertions are evaluated in the order they appear in the list. All enabled assertions run regardless of previous failures (unlike short-circuit evaluation). Results are independent of each other.

Common Testing Patterns

These patterns cover the most common API testing scenarios. Use them as a starting point and customize based on your API's response structure.

GET - Success Response

Basic validation for a successful GET request:

Status Code equals 200
Header Content-Type contains "application/json"
Body is not empty

POST - Created Resource

Validation for POST that creates a new resource:

Status Code equals 201
JSON Path $.id exists
JSON Path $.id is type number
JSON Path $.createdAt exists

PUT/PATCH - Update Resource

Validation for update operations:

Status Code equals 200
JSON Path $.updatedAt exists
JSON Path $.name equals "Updated Name"

DELETE - Remove Resource

Validation for DELETE operations (varies by API):

Status Code equals 204// No Content
Body is empty

Or if the API returns the deleted resource:

Status Code equals 200
JSON Path $.deleted equals true

GET - List with Pagination

Validation for paginated list endpoints:

Status Code equals 200
JSON Path $.data is type array
JSON Path $.data.length > 0
JSON Path $.meta.total is type number
JSON Path $.meta.page exists

POST - Login/Authentication

Validation for authentication endpoints:

Status Code equals 200
JSON Path $.access_token exists
JSON Path $.access_token is type string
JSON Path $.access_token is not empty
JSON Path $.expires_in > 0

400 - Validation Error

Testing that invalid input returns proper errors:

Status Code equals 400
JSON Path $.errors is type array
JSON Path $.errors.length > 0
JSON Path $.errors[0].field exists
JSON Path $.errors[0].message exists

404 - Not Found

Testing behavior when resource doesn't exist:

Status Code equals 404
JSON Path $.error exists
JSON Path $.message contains "not found"

401 - Unauthorized

Testing authentication requirement:

Status Code equals 401
Header WWW-Authenticate exists
JSON Path $.data not exists// No data leak

Performance Testing

Validate response time requirements:

Status Code < 400// Any non-error
Response Time < 200 ms// Fast (cached)
Response Time < 500 ms// Normal
Response Time < 2000 ms// Acceptable for heavy queries

Security Headers Check

Validate security-related response headers:

Header X-Content-Type-Options equals "nosniff"
Header X-Frame-Options exists
Header Strict-Transport-Security exists
Header Content-Security-Policy exists