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
at.request.methodHTTP method (read-only)
at.request.urlFull request URL (read/write)
at.request.headersRequest headers (read-only copy). Use setHeader() / removeHeader() to modify.
at.request.bodyRequest body as string (read/write)
at.request.setHeader(key, value)Add or update a request header
at.request.removeHeader(key)Remove a request header
at.environment.get(key)Read an environment variable
at.environment.set(key, value)Set an environment variable (persisted)
at.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:', at.request.method);
console.log('URL:', at.request.url);
console.log('Headers:', JSON.stringify(at.request.headers, null, 2));

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

Example: Modify Request Dynamically

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

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

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

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

Example: Validate Request Before Sending

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

// Validate JSON body structure
if (at.request.body) {
  try {
    const body = JSON.parse(at.request.body);
    if (!body.name) {
      console.error('Error: name field is required');
    }
  } catch (e) {
    console.error('Body is not valid JSON');
  }
}

Example: Fetch a Token Before the Request (async/await)

Scripts run inside an async wrapper, so you can use top-level await directly. The injected fetch is routed through Atrahasis's backend, so it is not affected by browser CORS restrictions.

// Exchange credentials for a short-lived token, then attach it
const tokenUrl = at.environment.get('token_url');
const clientId = at.environment.get('client_id');
const clientSecret = at.environment.get('client_secret');

const res = await fetch(tokenUrl, {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ clientId, clientSecret }),
});

const data = await res.json();
at.environment.set('access_token', data.token);
at.request.setHeader('Authorization', 'Bearer ' + data.token);

Execution Limits

  • 30-second timeout — Scripts are aborted after 30 seconds of wall-clock time. This protects the app against infinite loops or a hung fetch. A script that exceeds the limit fails with the error Script timeout: exceeded 30 seconds.
  • 1000-character log buffer — The total console output collected during a script run is capped at 1000 characters. When the cap is reached, Atrahasis appends a [WARN] Log limit reached (1000 chars) line and silently drops any further output. Keep log calls short when iterating over large payloads.

Using Variables from Inside Scripts

The {{varName}} substitution syntax only runs on URL, header, body, and param fields — it is not processed inside script source code. If you accidentally write {{foo}} inside a pre-script, Atrahasis detects it at runtime and prints a helpful hint in the script output telling you to use at.environment.get("foo") instead. Always use the at.environment API to read and write environment variables from scripts.

Error behavior: If a pre-script throws, the error is logged and the request is still sent — but only with the original URL, headers, and body. Any at.request.* mutations made before the error are discarded. However, any at.environment.set() calls that completed before the error are still persisted, so a partially-executed script can leave behind env var changes. If that is a problem, wrap risky sections in try/catch and only call at.environment.set after the risky work succeeds.

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
at.response.statusHTTP status code (e.g., 200, 404)
at.response.statusTextHTTP status text (e.g., "OK", "Not Found")
at.response.headersResponse headers object
at.response.bodyResponse body as string
at.response.json()Parse body as JSON (cached — safe to call multiple times)
at.response.timingTiming object: total, dns, tls, ttfb
at.request.*Request data (read-only in post-scripts)
at.environment.get(key)Read an environment variable
at.environment.set(key, value)Set an environment variable (persisted)
at.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:', at.response.status, at.response.statusText);
console.log('Headers:', JSON.stringify(at.response.headers, null, 2));

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

Example: Save Values to Environment

// Extract token from login response and save for subsequent requests
if (at.response.status === 200) {
  const data = at.response.json();
  at.environment.set('auth_token', data.access_token);
  at.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 (at.response.status === 200) {
  const data = at.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 = at.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');

Example: Forward the Response to Another Endpoint (async/await)

Post-scripts run inside an async wrapper, so you can use top-level await. The injected fetch is routed through Atrahasis's backend and is not affected by browser CORS restrictions.

// Mirror a successful response to a webhook for auditing
if (at.response.status === 200) {
  const data = at.response.json();
  const webhookUrl = at.environment.get('audit_webhook');

  await fetch(webhookUrl, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      at: Date.now(),
      path: at.request.url,
      id: data.id,
    }),
  });

  console.log('Audit event forwarded');
}
Note: Use at.response.json() instead of JSON.parse(at.response.body). The result is cached, so calling json() multiple times is safe and efficient. Environment variables set via at.environment.set() are persisted immediately and available in subsequent requests.

Execution Limits

Post-scripts run under the same sandbox constraints as pre-scripts:

  • 30-second timeout — Scripts are aborted after 30 seconds of wall-clock time, protecting the app against infinite loops or a hung fetch. Exceeding the limit fails with Script timeout: exceeded 30 seconds.
  • 1000-character log buffer — Total console output during a single run is capped at 1000 characters. When the cap is reached, Atrahasis appends [WARN] Log limit reached (1000 chars) and drops further output.

Using Variables from Inside Scripts

The {{varName}} substitution syntax does not run inside script source code. If you accidentally write {{foo}} inside a post-script, Atrahasis detects it at runtime and prints a helpful hint in the script output telling you to use at.environment.get("foo") instead. Always use the at.environment API to read and write environment variables from scripts.

Error behavior: A post-script runs after the response is already received and displayed, so throwing an error never affects the response shown in the Response panel. The error is logged to the script output, but any at.environment.set() calls that completed before the error are still persisted. Wrap risky sections in try/catch if you need atomic env updates.

Script Results

After execution, both pre-scripts and post-scripts surface their outcome in the Processors panel:

SuccessThe script completed without throwing. Any collected console output is shown (up to the 1000-character cap).
ErrorThe script threw an error. Only the error message is displayed — Atrahasis does not expose the stack trace. Logs produced before the error are still shown.

Execution Duration

The time taken to execute the script is shown in milliseconds next to the outcome badge. Combined with the 30-second timeout, this makes it easy to spot scripts that are approaching the limit.

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 row consists of up to five parts:

EnabledA checkbox on the left side of each assertion. Unchecked assertions stay in the list but are skipped when the request runs — useful for temporarily silencing a flaky or situational check without losing its configuration.
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.).

Enabling and Disabling Assertions

Assertions can be toggled at two independent levels:

  • Per-assertion checkbox — each row has its own Enabled toggle. Disabled rows are skipped on send but stay in the tab and on the saved request, so you can re-enable them later.
  • Master toggle — the Assertions sub-tab has a single switch that turns every assertion on or off at once. When the master toggle is off, no assertion runs regardless of its individual checkbox. This is handy when you want to send a request without any validation noise in the results, then flip validation back on without re-enabling each row one by one.

Variables in Expected Values

Expected values support the same substitution syntax as the rest of the request. Right before each assertion runs, Atrahasis resolves environment variables and random variables inside the Expected field, so you can reuse the value your request just produced or pin an assertion to an env-specific constant:

JSON Path $.userId equals {{currentUserId}}
Header X-Tenant equals {{tenantId}}
JSON Path $.correlationId matches regex {{random.uuid}}

Substitution happens only for string-typed Expected values, so numeric comparisons like Status Code equals 200 are unaffected.

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

Supported Types for "is type"

The is type operator compares the JavaScript type of the extracted value against one of six known types:

stringnumberbooleanarrayobjectnull

Arrays are reported as array (not object), and null is its own type (not object), which lets you distinguish between a missing field and a nullified one.

Deep Partial Match with "contains"

When both the extracted value and the Expected field parse as JSON, contains performs a structural partial match rather than a plain substring search. That means you can assert "this object has these fields with these values" without listing every unrelated field:

JSON Path $.user contains {"role":"admin"}

If $.user returns {"id":1,"role":"admin","name":"Alice"}, the assertion passes — the extra id and name fields are ignored. If the Expected value is not valid JSON, Atrahasis falls back to substring matching, so simple checks like contains "admin" still work as expected. not contains applies the same logic in reverse.

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 regexJavaScript regular expression match. The pattern is tested first as-is; if that does not match, Atrahasis retries with the dotall flag (so . matches newlines) to cover patterns that span multi-line content. If the pattern contains \n, it is additionally retried with cross-platform newline alternatives (\r\n, \n, \r).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 button in the main request panel tabs (Body / Params / Vars / Headers / Auth / Processors) displays a live badge so you can see assertion status without opening the Processors tab. The badge has three possible states:

  • Gray badge (before sending) — When the tab has one or more assertions but the request has not been sent yet (or no results exist), a gray badge shows the total assertion count.
  • Green badge (passed) — After a request completes, a green badge shows the number of assertions that passed. Hidden when zero.
  • Red badge (failed) — After a request completes, a red badge shows the number of assertions that failed. Hidden when zero. If at least one assertion passed and one failed, both green and red badges appear side-by-side.

No badge is rendered at all when Enable Assertions is off or the tab has no assertions. This keeps the tab strip clean when assertions are not in use.

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