Skip to content

Scripting Engine

Anes Berbic edited this page Mar 13, 2026 · 1 revision

Scripting Engine

ApiArk includes a JavaScript/TypeScript scripting engine powered by the ark API. Add pre-request and post-response scripts to automate workflows, chain requests, and validate responses.


Script Types

Script When it Runs Use Case
Pre-request Before the request is sent Set variables, generate tokens, compute signatures
Post-response After the response is received Extract data, set variables, validate responses
Tests After post-response scripts Assert response correctness

Execution Order

Scripts execute in a specific order when using collections with folder inheritance:

1. Collection pre-request script
2. Folder pre-request script
3. Request pre-request script
4. ──── HTTP REQUEST SENT ────
5. Request post-response script
6. Folder post-response script
7. Collection post-response script
8. Declarative assertions (assert block)
9. JavaScript tests (tests block)

The ark API

ark.request — Access the Request

Available in pre-request (read/write) and post-response (read-only).

// Read properties
ark.request.url          // Full URL
ark.request.method       // HTTP method
ark.request.headers      // Headers object
ark.request.body         // Body content

// Modify (pre-request only)
ark.request.setUrl("https://api.example.com/v2/users");
ark.request.setMethod("POST");
ark.request.setHeader("X-Custom", "value");
ark.request.removeHeader("X-Unwanted");
ark.request.setBody(JSON.stringify({ key: "value" }));

ark.response — Access the Response

Available in post-response scripts and tests only.

ark.response.status       // HTTP status code (e.g., 200)
ark.response.statusText   // Status text (e.g., "OK")
ark.response.headers      // Response headers object
ark.response.cookies      // Response cookies
ark.response.body         // Raw body string
ark.response.time         // Response time in ms
ark.response.size         // Response size in bytes

// Parse body
ark.response.json()       // Parse as JSON
ark.response.text()       // Get as text

ark.env — Environment Variables

ark.env.get("baseUrl")              // Get variable
ark.env.set("userId", "usr_123")    // Set variable
ark.env.unset("tempVar")            // Remove variable
ark.env.toObject()                  // Get all as object

ark.globals — Global Variables

Same API as ark.env but for global scope (shared across collections).

ark.globals.get("globalApiKey")
ark.globals.set("sharedToken", token)

ark.variables — Request-scoped Variables

Temporary variables that exist only for the current request execution.

ark.variables.set("requestId", uuid)
ark.variables.get("requestId")

ark.test & ark.expect — Testing

ark.test("should return 200", () => {
  ark.expect(ark.response.status).to.equal(200);
});

ark.test("should have users array", () => {
  const body = ark.response.json();
  ark.expect(body.users).to.be.an("array");
  ark.expect(body.users.length).to.be.greaterThan(0);
});

ark.test("response time under 2 seconds", () => {
  ark.expect(ark.response.time).to.be.below(2000);
});

ark.expect uses Chai.js assertion syntax. See Testing & Assertions for full details.

ark.sendRequest — Chain Requests

Send additional HTTP requests from within a script.

// In pre-request: get a fresh token
const authResponse = await ark.sendRequest({
  method: "POST",
  url: `${ark.env.get("baseUrl")}/auth/token`,
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify({
    client_id: ark.env.get("clientId"),
    client_secret: ark.env.get("clientSecret"),
    grant_type: "client_credentials"
  })
});

const token = authResponse.json().access_token;
ark.env.set("accessToken", token);

ark.utils — Utility Functions

ark.utils.uuid()                    // Generate UUID v4
ark.utils.timestamp()               // Unix timestamp (seconds)
ark.utils.base64Encode("hello")     // Base64 encode
ark.utils.base64Decode("aGVsbG8=")  // Base64 decode
ark.utils.sha256("data")            // SHA-256 hash
ark.utils.md5("data")               // MD5 hash
ark.utils.hmac("sha256", "key", "data")  // HMAC

ark.info — Execution Context

ark.info.requestName      // Current request name
ark.info.collectionName   // Current collection name
ark.info.environment      // Active environment name
ark.info.iteration        // Current iteration number (collection runner)

ark.visualize — Custom Response Views

Render HTML templates in the response panel.

const users = ark.response.json().users;
const template = `
  <table>
    <tr><th>Name</th><th>Email</th></tr>
    ${users.map(u => `<tr><td>${u.name}</td><td>${u.email}</td></tr>`).join("")}
  </table>
`;
ark.visualize(template);

Built-in Libraries

Available in all scripts without imports:

Library Usage
Chai.js ark.expect(value).to.equal(expected)
CryptoJS CryptoJS.AES.encrypt(data, key)
Lodash _.groupBy(users, 'role')
Ajv JSON Schema validation
Faker faker.person.fullName(), faker.internet.email()
moment moment().format('YYYY-MM-DD')

Common Patterns

Login → Use Token

// Pre-request script on the auth/login.yaml request
// (nothing needed)

// Post-response script on the auth/login.yaml request
const body = ark.response.json();
ark.env.set("accessToken", body.token);
ark.env.set("refreshToken", body.refreshToken);

Generate HMAC Signature

// Pre-request script
const timestamp = Date.now().toString();
const body = ark.request.body || "";
const signature = ark.utils.hmac("sha256", ark.env.get("secretKey"), timestamp + body);

ark.request.setHeader("X-Timestamp", timestamp);
ark.request.setHeader("X-Signature", signature);

Retry on 429 (Rate Limit)

// Post-response script
if (ark.response.status === 429) {
  const retryAfter = parseInt(ark.response.headers["retry-after"] || "1");
  console.log(`Rate limited. Retry after ${retryAfter}s`);
  // The next collection runner iteration will retry
  ark.env.set("retryDelay", retryAfter * 1000);
}

Data Extraction Chain

// Post-response: Extract IDs for the next request
const users = ark.response.json().data;
const userIds = users.map(u => u.id);
ark.env.set("userIds", JSON.stringify(userIds));
ark.env.set("firstUserId", userIds[0]);

YAML Script Blocks

In request YAML files:

preRequestScript: |
  const timestamp = Date.now();
  ark.request.setHeader("X-Timestamp", timestamp.toString());

postResponseScript: |
  const body = ark.response.json();
  ark.env.set("userId", body.id);

tests: |
  ark.test("status is 200", () => {
    ark.expect(ark.response.status).to.equal(200);
  });

Console Output

  • console.log(), console.warn(), console.error() output appears in the Console panel (bottom bar)
  • Useful for debugging scripts during development
  • Console output is also visible in collection runner results

Clone this wiki locally