RESTKDocs

Scripting

Automate API workflows with JavaScript scripts - modify requests, test responses, manage variables, and chain requests together.

8 min read

RESTK provides a powerful JavaScript scripting API using the nova.* namespace to automate your API workflows. Write pre-scripts to modify requests before sending, and post-scripts to test responses and extract data.

Quick Start

Open Scripts Tab

Select a request and navigate to the Scripts tab.

Write a Pre-script

Add code that runs before the request is sent:

nova.request.setHeader("X-Timestamp", String(Date.now()));

Write a Post-script

Add code to test and process the response:

nova.test("Status is 200", function() {
  nova.expect(nova.response.status).toBe(200);
});

Send and View Results

Click Send - scripts run automatically. Check the console and test results.


Script Execution Flow

Scripts run at multiple levels in a specific order:

1. Collection pre-script
2. Folder pre-script (root → leaf if nested)
3. Request pre-script
4. ─── HTTP Request Sent ───
5. Request post-script
6. Folder post-script (leaf → root if nested)
7. Collection post-script

Skip Parent Scripts

Check Skip Parent Scripts on a request to run only that request's scripts, bypassing collection and folder scripts entirely.


Core Utilities

Console Logging

Five log levels are available, all supporting multiple arguments:

console.log("Message", data);     // Standard log
console.info("Info message");     // Info level
console.warn("Warning message");  // Warning level
console.error("Error message");   // Error level
console.debug("Debug message");   // Debug level

nova.log("Nova log message");     // Alias for console.log

Built-in Helpers

// Generate UUID
nova.uuid()

// Get timestamp (seconds)
nova.timestamp()

// Get timestamp (milliseconds)
nova.timestampMs()

// Get ISO date string
nova.isoDate()

// Random integer (inclusive range)
nova.randomInt(1, 100)

Global Functions

// Base64 encoding/decoding (browser-standard)
btoa("string to encode")    // Encode to Base64
atob("encoded-string")      // Decode from Base64

Request API (Pre-scripts)

Modify requests before they're sent using the nova.request object.

URL and Method

// Access URL (read/write)
nova.request.url       // Full URL string

// Access method (read/write)
nova.request.method    // "GET", "POST", etc.

Headers

// Set a header
nova.request.setHeader("Content-Type", "application/json");
nova.request.setHeader("Authorization", "Bearer " + nova.variable.get("token"));

// Get a specific header (case-insensitive)
nova.request.getHeader("Content-Type");

// Get all headers
nova.request.getHeaders();

// Remove a header
nova.request.removeHeader("X-Custom");

Query Parameters

// Set a query parameter
nova.request.setParam("page", "1");

// Get a specific parameter
nova.request.getParam("page");

// Get all query parameters
nova.request.getParams();

// Remove a parameter
nova.request.removeParam("debug");

Body

// Access request body (read/write)
nova.request.body

// Get body type and content type
nova.request.getBodyType();
nova.request.getBodyContentType();

// Set JSON body
nova.request.setJsonBody({
  username: "john",
  timestamp: Date.now()
});

// Set URL-encoded body
nova.request.setUrlEncodedBody({
  grant_type: "client_credentials",
  client_id: nova.variable.get("client_id")
});

// Set form data body
nova.request.setFormBody([
  { key: "name", value: "John", type: "text" },
  { key: "file", value: "/path/to/file", type: "file" }
]);

// Set raw body with content type
nova.request.setRawBody("<xml>data</xml>", "application/xml");

// Set GraphQL body
nova.request.setGraphQLBody(
  "query GetUser($id: ID!) { user(id: $id) { name } }",
  { id: "123" },          // variables (optional)
  "GetUser"               // operationName (optional)
);

// Clear body entirely
nova.request.clearBody();

Authentication Helpers

// Set Bearer token
nova.request.setBearerToken(nova.variable.get("access_token"));

// Set Basic auth
nova.request.setBasicAuth("username", "password");

// Set API Key
nova.request.setApiKey("X-API-Key", "your-key", "header");

// Get current auth type
nova.request.getAuthType();

// Check if auth is inherited from parent
nova.request.isAuthInherited();

// Remove auth
nova.request.removeAuth();

Response API (Post-scripts)

Read response data after receiving it using the nova.response object.

Properties

nova.response.status        // 200
nova.response.code          // 200 (alias for status)
nova.response.body          // Response body
nova.response.responseTime  // 150 (milliseconds)
nova.response.size          // Response size in bytes

Methods

// Get body as JSON (returns null if invalid JSON)
const data = nova.response.json();

// Get body as text
const text = nova.response.text();

// Get a specific header (case-insensitive)
nova.response.getHeader("Content-Type");

// Get all headers
nova.response.getHeaders();

Example

if (nova.response.status === 200) {
  const data = nova.response.json();
  if (data && data.token) {
    nova.variable.set("access_token", data.token);
    console.log("Token saved!");
  }
}

Variables API

Variable Methods

// Get variable (searches all scopes in priority order)
nova.variable.get(key)

// Set variable (runtime-only — not persisted)
nova.variable.set(key, value)

// Check if variable exists
nova.variable.has(key)

// Remove variable
nova.variable.unset(key)

Variable Scopes

You can access specific scopes:

// Environment variables (persists as currentValue, local only)
nova.environment.get("api_url")
nova.environment.set("api_url", "https://api.example.com")

// Collection variables (persists, syncs)
nova.collectionVariables.get("collection_var")
nova.collectionVariables.set("collection_var", "value")

// Folder variables (persists, syncs)
nova.folderVariables.get("folder_var")
nova.folderVariables.set("folder_var", "value")

// Request variables (persists, syncs)
nova.requestVariables.get("request_var")
nova.requestVariables.set("request_var", "value")

Resolution Priority (Highest to Lowest)

  1. Runtime variables (set via nova.variable.set during script execution)
  2. Request variables
  3. Folder variables (includes parent folders if nested)
  4. Collection variables
  5. Environment variables (lowest)

Examples

// Set environment variable (persists locally as currentValue)
nova.environment.set("base_url", "https://api.example.com");

// Set collection variable (persisted, shared in collection)
nova.collectionVariables.set("access_token", data.token);

// Get variable (auto-resolves from all scopes)
const url = nova.variable.get("base_url");

// IMPORTANT: nova.variable.set() is runtime-only (not persisted)
// Use scope-specific methods to persist values:
// nova.environment.set() → writes to currentValue (local only)
// nova.collectionVariables.set() → persists in collection
// nova.folderVariables.set() → persists in folder

Scope-Specific set() Limitation

nova.environment.set(), nova.collectionVariables.set(), nova.folderVariables.set(), and nova.requestVariables.set() can only update existing variables — they cannot create new ones. Pre-define variables in the UI before referencing them in scripts.

Using Variables in UI

Reference variables with double curly braces:

URL: {{base_url}}/users/{{user_id}}
Header: Authorization: Bearer {{access_token}}
Body: {"api_key": "{{api_key}}"}

Testing API

Define Tests

nova.test("Test name", function() {
  // Assertions go here
});

Assertions with nova.expect()

// Equality
nova.expect(value).toBe(expected);       // Strict equality
nova.expect(value).toEqual(expected);     // Deep equality

// Truthiness
nova.expect(value).toBeDefined();
nova.expect(value).toBeUndefined();
nova.expect(value).toBeNull();
nova.expect(value).toBeNotNull();
nova.expect(value).toBeTruthy();
nova.expect(value).toBeFalsy();

// Comparison
nova.expect(value).toBeGreaterThan(10);
nova.expect(value).toBeLessThan(100);

// Collections
nova.expect(array).toContain(item);
nova.expect(array).toHaveLength(10);

// Pattern matching
nova.expect(string).toMatch(/pattern/);

// Negation (works with any matcher)
nova.expect(value).not.toBe(other);

Examples

nova.test("Status is 200", function() {
  nova.expect(nova.response.status).toBe(200);
});

nova.test("Response time is fast", function() {
  nova.expect(nova.response.responseTime).toBeLessThan(1000);
});

nova.test("Response has data", function() {
  const data = nova.response.json();
  nova.expect(data).toBeDefined();
  nova.expect(data.items.length).toBe(10);
});

Crypto API

Hashing

// MD5 hash
nova.crypto.md5("string to hash")

// SHA256 hash
nova.crypto.sha256("string to hash")

// SHA512 hash
nova.crypto.sha512("string to hash")

// HMAC SHA256
nova.crypto.hmacSha256("message", "secret-key")

// HMAC SHA512
nova.crypto.hmacSha512("message", "secret-key")

Encoding

// Base64 encode
nova.crypto.base64Encode("string to encode")

// Base64 decode
nova.crypto.base64Decode("encoded-string")

Parent Auth API

Set authentication on parent containers from scripts — useful for OAuth token refresh workflows where you need to update the collection or folder auth after obtaining a new token.

Collection Auth

// Set Bearer token on collection
nova.collectionAuth.setBearerToken(token);

// Set Basic auth on collection
nova.collectionAuth.setBasicAuth("username", "password");

// Set API Key on collection
nova.collectionAuth.setApiKey("X-API-Key", "your-key", "header");

Folder Auth

// Set Bearer token on folder
nova.folderAuth.setBearerToken(token);

// Set Basic auth on folder
nova.folderAuth.setBasicAuth("username", "password");

// Set API Key on folder
nova.folderAuth.setApiKey("X-API-Key", "your-key", "header");

Authentication Workflows

Store Token from Login Response

// Post-script on login request
const data = nova.response.json();

nova.test("Login successful", function() {
  nova.expect(nova.response.status).toBe(200);
  nova.expect(data.access_token).toBeDefined();
});

if (data && data.access_token) {
  // Store in variable - all requests can use it
  nova.variable.set("access_token", data.access_token);

  // Store expiry
  const expiresAt = Date.now() + ((data.expires_in || 3600) * 1000);
  nova.variable.set("token_expires", String(expiresAt));

  console.log("Token stored successfully");
}

Dynamic Variables Based on Environment

// Pre-script
const env = nova.environment.get("ENV");

if (env === "production") {
  nova.request.setBearerToken(nova.environment.get("prod_token"));
} else {
  nova.request.setBearerToken(nova.environment.get("dev_token"));
}

Common Patterns

Chain Requests

Extract data from one response for the next request:

// Post-script: Save user ID
const user = nova.response.json();
nova.variable.set("user_id", String(user.id));

Then use {{user_id}} in subsequent requests.

Extract Multiple Values

// Post-script
const data = nova.response.json();

if (data) {
  nova.variable.set("user_id", String(data.id));
  nova.variable.set("user_email", data.email);

  if (data.organization) {
    nova.variable.set("org_id", String(data.organization.id));
  }
}

Test Array Items

nova.test("All items have required fields", function() {
  const items = nova.response.json();

  items.forEach((item, i) => {
    nova.expect(item.id).toBeDefined();
    nova.expect(item.name).toBeDefined();
  });
});

Handle Errors

nova.test("Error has message", function() {
  if (nova.response.status >= 400) {
    const error = nova.response.json();
    nova.expect(error.message).toBeDefined();
  }
});

Quick Reference

┌─────────────────────────────────────────────────────┐
│ VARIABLES (.get/.set/.has/.unset)                   │
│   nova.variable           (all scopes, runtime)     │
│   nova.environment        (environment only)        │
│   nova.collectionVariables (collection only)        │
│   nova.folderVariables    (folder only)             │
│   nova.requestVariables   (request only)            │
├─────────────────────────────────────────────────────┤
│ REQUEST (Pre-scripts)                               │
│   nova.request.url / .method / .body                │
│   .setHeader / .getHeader / .getHeaders             │
│   .removeHeader                                     │
│   .setParam / .getParam / .getParams / .removeParam │
│   .setJsonBody / .setUrlEncodedBody / .setFormBody  │
│   .setRawBody / .setGraphQLBody / .clearBody        │
│   .setBearerToken / .setBasicAuth / .setApiKey      │
│   .getAuthType / .isAuthInherited / .removeAuth     │
├─────────────────────────────────────────────────────┤
│ RESPONSE (Post-scripts)                             │
│   nova.response.status / .code / .body / .size      │
│   nova.response.responseTime                        │
│   nova.response.json() / .text()                    │
│   nova.response.getHeader(key) / .getHeaders()      │
├─────────────────────────────────────────────────────┤
│ TESTING                                             │
│   nova.test(name, fn)                               │
│   nova.expect(val).toBe / .toEqual                  │
│   nova.expect(val).toBeDefined / .toBeUndefined     │
│   nova.expect(val).toBeNull / .toBeNotNull          │
│   nova.expect(val).toBeTruthy / .toBeFalsy          │
│   nova.expect(val).toBeGreaterThan / .toBeLessThan  │
│   nova.expect(arr).toContain / .toHaveLength        │
│   nova.expect(str).toMatch(regex)                   │
│   nova.expect(val).not.toBe(other)                  │
├─────────────────────────────────────────────────────┤
│ UTILITIES                                           │
│   nova.uuid() / nova.timestamp() / nova.isoDate()  │
│   nova.timestampMs() / nova.randomInt(min, max)     │
│   btoa() / atob()      (Base64 globals)             │
│   nova.crypto.md5 / sha256 / sha512                 │
│   nova.crypto.hmacSha256 / hmacSha512               │
│   nova.crypto.base64Encode / base64Decode           │
├─────────────────────────────────────────────────────┤
│ PARENT AUTH (.setBearerToken/.setBasicAuth/.setApiKey)│
│   nova.collectionAuth                               │
│   nova.folderAuth                                   │
└─────────────────────────────────────────────────────┘

Next Steps