2
API Reference
Pavel Baksy edited this page 2026-01-13 16:59:00 +01:00

API Reference

Complete JavaScript API reference for Roster preprocessing and postprocessing scripts.

Overview

Roster provides a JavaScript API accessible from Scripts for automating request modifications and response processing.

Language: JavaScript (ES5+) Runtime: GJS (GNOME JavaScript) Context: Sandboxed, synchronous execution

Global Objects

Preprocessing Script Context

Available in preprocessing scripts only:

request    // Modifiable request object
roster     // Roster API (with getVariable)
console    // Console output

Postprocessing Script Context

Available in postprocessing scripts only:

response   // Read-only response object
roster     // Roster API (without getVariable)
console    // Console output

Request Object

Available in: Preprocessing scripts only Type: Mutable

Properties

request.method

Type: string Values: "GET", "POST", "PUT", "DELETE" Description: HTTP method for the request

Example:

// Change method from GET to POST
request.method = "POST";
console.log('Method changed to:', request.method);

request.url

Type: string Description: Complete URL for the request

Example:

// Add query parameter
request.url = request.url + '?timestamp=' + Date.now();

// Replace placeholder
const userId = roster.getVariable('user_id');
request.url = request.url.replace('{userId}', userId);

// Change domain
request.url = request.url.replace('localhost', 'api.example.com');

request.headers

Type: object Description: HTTP headers as key-value pairs

Example:

// Add header
request.headers['Authorization'] = 'Bearer ' + token;

// Modify existing header
request.headers['Content-Type'] = 'application/json';

// Delete header
delete request.headers['X-Old-Header'];

// Read header
const contentType = request.headers['Content-Type'];

request.body

Type: string Description: Request body content

Example:

// Set body
request.body = JSON.stringify({ name: "John", age: 30 });

// Modify existing body
const data = JSON.parse(request.body);
data.timestamp = new Date().toISOString();
request.body = JSON.stringify(data);

// Clear body
request.body = "";

Response Object

Available in: Postprocessing scripts only Type: Immutable (read-only)

Properties

response.body

Type: string Description: Response body content

Example:

// Parse JSON response
const data = JSON.parse(response.body);
console.log('User name:', data.name);

// Check if response contains text
if (response.body.includes('error')) {
    console.error('Response contains error');
}

// Get response length
console.log('Response size:', response.body.length, 'bytes');

response.headers

Type: object Description: Response headers as key-value pairs (read-only)

Example:

// Read header
const contentType = response.headers['Content-Type'];
console.log('Content type:', contentType);

// Check if header exists
if (response.headers['X-Rate-Limit-Remaining']) {
    const remaining = response.headers['X-Rate-Limit-Remaining'];
    console.log('Rate limit remaining:', remaining);
}

// List all headers
for (const key in response.headers) {
    console.log(key + ':', response.headers[key]);
}

response.statusCode

Type: number Description: HTTP status code (200, 404, 500, etc.)

Example:

// Check if successful
if (response.statusCode === 200) {
    console.log('Success!');
} else if (response.statusCode >= 400 && response.statusCode < 500) {
    console.error('Client error:', response.statusCode);
} else if (response.statusCode >= 500) {
    console.error('Server error:', response.statusCode);
}

// Handle specific status codes
switch (response.statusCode) {
    case 200:
        console.log('OK');
        break;
    case 201:
        console.log('Created');
        break;
    case 401:
        console.error('Unauthorized');
        break;
    case 404:
        console.error('Not found');
        break;
    default:
        console.log('Status:', response.statusCode);
}

response.statusText

Type: string Description: HTTP status text ("OK", "Not Found", etc.)

Example:

console.log('Response:', response.statusCode, response.statusText);
// Output: "Response: 200 OK"

if (response.statusText === "OK") {
    // Process successful response
}

response.responseTime

Type: number Description: Response time in milliseconds

Example:

console.log('Response took', response.responseTime, 'ms');

if (response.responseTime > 1000) {
    console.warn('Slow response:', response.responseTime, 'ms');
}

// Store for monitoring
roster.setVariable('last_response_time', response.responseTime.toString());

Roster API

Available in: Both preprocessing and postprocessing scripts Namespace: roster

Methods

roster.getVariable(name)

Available in: Preprocessing scripts only Returns: string or undefined Description: Get variable value from selected environment

Parameters:

  • name (string): Variable name

Example:

// Get variable
const apiKey = roster.getVariable('api_key');
if (apiKey) {
    request.headers['X-API-Key'] = apiKey;
} else {
    console.error('API key not defined');
}

// Get with default value
const timeout = roster.getVariable('timeout') || '30';
console.log('Using timeout:', timeout);

Notes:

  • Returns undefined if variable doesn't exist
  • Gets value from selected environment
  • Sensitive variables are automatically decrypted

roster.setVariable(name, value)

Available in: Both preprocessing and postprocessing scripts Returns: undefined Description: Set or update variable in selected environment

Parameters:

  • name (string): Variable name (must match /^\w+$/)
  • value (string): Variable value

Example:

// Set variable
roster.setVariable('user_id', '12345');
console.log('Saved user ID');

// Update existing variable
const token = data.access_token;
roster.setVariable('auth_token', token);

// Create new variable (auto-created if doesn't exist)
roster.setVariable('session_id', generateSessionId());

Notes:

  • Creates variable if it doesn't exist
  • Updates value in selected environment
  • Variable name must be alphanumeric + underscore
  • Sensitive variables automatically routed to keyring
  • Value converted to string

roster.setVariables(object)

Available in: Both preprocessing and postprocessing scripts Returns: undefined Description: Set or update multiple variables at once (batch operation)

Parameters:

  • object (object): Key-value pairs of variable names and values

Example:

// Set multiple variables
roster.setVariables({
    user_id: data.user.id,
    user_name: data.user.name,
    user_email: data.user.email,
    session_id: data.session_id
});

// Extract response data
const data = JSON.parse(response.body);
roster.setVariables({
    access_token: data.access_token,
    refresh_token: data.refresh_token,
    expires_at: data.expires_at
});
console.log('Saved authentication tokens');

Notes:

  • More efficient than multiple setVariable() calls
  • Same validation rules as setVariable()

Properties

roster.project.name

Available in: Preprocessing scripts only Type: string Description: Current project name

Example:

const projectName = roster.project.name;
console.log('Project:', projectName);

// Add project name to request
request.headers['X-Project'] = projectName;

roster.project.environments

Available in: Preprocessing scripts only Type: string[] (array of strings) Description: Array of environment names in current project

Example:

const envs = roster.project.environments;
console.log('Available environments:', envs.join(', '));
// Output: "Available environments: Production, Staging, Development"

// Check if environment exists
if (envs.includes('Production')) {
    console.log('Production environment available');
}

// Log count
console.log('Environment count:', envs.length);

Console API

Available in: Both preprocessing and postprocessing scripts Namespace: console

Methods

console.log(...args)

Returns: undefined Description: Print message to script output

Example:

console.log('Simple message');
console.log('User ID:', userId);
console.log('Request sent to', request.url);
console.log('Response status:', response.statusCode, response.statusText);

// Multiple arguments
const name = 'John';
const age = 30;
console.log('User:', name, 'Age:', age);

Output location:

  • Preprocessing: "Preprocessing" tab in request panel
  • Postprocessing: "Postprocessing" tab in request panel

console.error(...args)

Returns: undefined Description: Print error message to script output

Example:

if (response.statusCode !== 200) {
    console.error('Request failed with status:', response.statusCode);
}

if (!data.access_token) {
    console.error('No access token in response');
}

try {
    const data = JSON.parse(response.body);
} catch (e) {
    console.error('JSON parse error:', e.message);
}

Visual difference:

  • May be styled differently than console.log() in output
  • Indicates errors or warnings

Built-in JavaScript Objects

Standard JavaScript objects available in GJS:

Date

// Current timestamp
const now = new Date();
console.log('Current time:', now.toISOString());

// Unix timestamp
const timestamp = Date.now();
console.log('Timestamp:', timestamp);

// Date arithmetic
const expiresAt = new Date(Date.now() + 3600000); // +1 hour
roster.setVariable('token_expires', expiresAt.toISOString());

JSON

// Parse JSON
const data = JSON.parse(response.body);
console.log('Parsed data:', data.name);

// Stringify JSON
const body = { name: "John", age: 30 };
request.body = JSON.stringify(body);

// Pretty print
request.body = JSON.stringify(body, null, 2);

Math

// Random number
const requestId = Math.floor(Math.random() * 1000000);
roster.setVariable('request_id', requestId.toString());

// Rounding
const responseTimeSeconds = Math.round(response.responseTime / 1000);
console.log('Response time:', responseTimeSeconds, 'seconds');

String

// String manipulation
const url = request.url.replace('http://', 'https://');
const uppercase = data.name.toUpperCase();
const trimmed = data.description.trim();

// String methods
if (response.body.includes('error')) {
    console.error('Response contains error');
}

const parts = request.url.split('/');
const lastPart = parts[parts.length - 1];

Array

// Array methods
const data = JSON.parse(response.body);
const itemIds = data.items.map(item => item.id);
console.log('Item IDs:', itemIds.join(', '));

// Filter
const active = data.items.filter(item => item.active);
console.log('Active items:', active.length);

// Find
const firstItem = data.items.find(item => item.id === '123');
if (firstItem) {
    console.log('Found item:', firstItem.name);
}

Object

// Object methods
const headers = Object.keys(response.headers);
console.log('Header count:', headers.length);

// Merge objects
const defaults = { timeout: 30, retries: 3 };
const config = Object.assign({}, defaults, userConfig);

// Check property
if (data.hasOwnProperty('access_token')) {
    roster.setVariable('auth_token', data.access_token);
}

Error Handling

Scripts should handle errors gracefully:

// Try-catch for parsing
try {
    const data = JSON.parse(response.body);
    roster.setVariable('user_id', data.user.id);
} catch (e) {
    console.error('Failed to parse JSON:', e.message);
    console.error('Response body:', response.body);
}

// Check before accessing
if (data && data.user && data.user.id) {
    roster.setVariable('user_id', data.user.id);
} else {
    console.error('Invalid response structure');
}

// Validate response status
if (response.statusCode === 200) {
    const data = JSON.parse(response.body);
    // Process data
} else {
    console.error('Request failed:', response.statusCode);
}

Limitations

Scripts run in a sandboxed, synchronous environment:

  • No async operations (setTimeout, Promises, async/await)
  • No external libraries or npm packages
  • No file system or shell access
  • No network requests (use Roster's request system)
  • Only built-in JavaScript objects available

Type Reference

Variable names must match /^\w+$/ (alphanumeric + underscore only).

Variables are always strings. Convert numbers and booleans when setting/getting:

roster.setVariable('count', data.count.toString());
const count = parseInt(roster.getVariable('count'), 10);

Next Steps