HTTP Reference

The http object is available within Loadster Code Blocks and provides methods for making HTTP requests programmatically. This allows you to use JavaScript to control HTTP requests with loops, conditionals, and custom logic.

Understanding HTTP Requests in Loadster

In Loadster, HTTP requests are the foundation of Protocol Scripts. While regular HTTP steps provide a visual, step-by-step approach to building requests, the http object in code blocks gives you programmatic control over the same functionality.

The http object provides methods for all standard HTTP methods (GET, POST, PUT, etc.) and can handle authentication, headers, validation, and error handling. All HTTP methods are synchronous - no need for await or promise chains - and the HTTP client automatically maintains cookies and session state just like a real browser would.

Each bot has its own independent HTTP client, so requests made by one bot don’t affect others. This allows you to test realistic scenarios where multiple users interact with your application simultaneously.

HTTP Request Methods

These methods make HTTP requests using the standard HTTP verbs. Each method returns a response object that you can use for validation, variable capturing, or further processing. All methods accept an optional args parameter for customization - see HTTP Request Arguments for details.

http.get(url, args)

Make an HTTP GET request.

// GET simple request to fetch user data
const response = http.get('https://api.example.com/users');

// GET request with authentication headers and validation
const response = http.get('https://api.example.com/users', {
    headers: { 'Authorization': 'Bearer token123' },
    validators: [(response) => response.status === 200]
});

// GET request with timeout and error handling for unreliable endpoints
const response = http.get('https://api.example.com/slow-endpoint', {
    timeout: 10000,
    ignoreHttpErrors: true
});

// GET request with custom headers for API versioning and content type
const response = http.get('https://api.example.com/users/123', {
    headers: {
        'Accept': 'application/json',
        'API-Version': 'v2',
        'User-Agent': 'Loadster Test Client'
    },
    validators: [
        (response) => response.status === 200,
        (response) => response.headers['Content-Type'].includes('application/json')
    ]
});

// GET request with multiple validators for data integrity checks
const response = http.get('https://api.example.com/products', {
    headers: { 'Authorization': 'Bearer token123' },
    validators: [
        (response) => response.status === 200,
        (response) => {
            const data = JSON.parse(response.string());
            return Array.isArray(data.products) && data.products.length > 0;
        }
    ]
});

Parameters:

GET requests are used to retrieve data from a server and are the most common type of HTTP request. They should not modify server state and are typically used for fetching web pages, API data, or resources.

http.post(url, body, args)

Make an HTTP POST request with a body.

// POST create a new user with basic JSON data
const response = http.post('https://api.example.com/users', {
    name: 'John Doe',
    email: 'john@example.com'
});

// POST request with validation to ensure user was created successfully
const response = http.post('https://api.example.com/users', requestBody, {
    headers: { 'Content-Type': 'application/json' },
    validators: [(response) => response.status === 201]
});

// POST submit form data with authentication and timeout
const response = http.post('https://api.example.com/contact', {
    name: 'Jane Smith',
    message: 'Test message',
    category: 'support'
}, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json',
        'X-Request-ID': Math.random().toString(36)
    },
    timeout: 15000,
    validators: [(response) => response.status === 200]
});

// POST upload file data with multipart content type
const response = http.post('https://api.example.com/upload', fileData, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'multipart/form-data'
    },
    ignoreHttpErrors: true,
    validators: [
        (response) => response.status >= 200 && response.status < 300,
        (response) => {
            const result = JSON.parse(response.string());
            return result.uploadId && result.status === 'success';
        }
    ]
});

// POST create order with detailed validation and error handling
const response = http.post('https://api.example.com/orders', {
    items: [{ productId: 123, quantity: 2 }],
    customerId: 456,
    paymentMethod: 'credit_card'
}, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json',
        'Idempotency-Key': generateUniqueKey()
    },
    timeout: 30000,
    validators: [
        (response) => response.status === 201,
        (response) => {
            const order = JSON.parse(response.string());
            return order.orderId && order.status === 'pending';
        }
    ]
});

Parameters:

  • url - The URL to request
  • body - The request body data (JSON object, string, or other data)
  • args - Optional configuration object (see HTTP Request Arguments)

POST requests are used to send data to a server, typically to create new resources or submit forms. The request body can be JSON, form data, or any other content type your API expects.

http.put(url, body, args)

Make an HTTP PUT request with a body.

// PUT update user profile with complete data replacement
const response = http.put('https://api.example.com/users/123', {
    name: 'John Smith',
    email: 'johnsmith@example.com'
});

// PUT request with error handling for non-critical updates
const response = http.put('https://api.example.com/users/123', body, {
    ignoreHttpErrors: true // treat HTTP 4xx/5xx as ok
});

// PUT replace entire product configuration with validation
const response = http.put('https://api.example.com/products/456', {
    name: 'Updated Product',
    price: 99.99,
    category: 'electronics',
    inventory: 50
}, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json',
        'If-Match': '"revision-123"'
    },
    validators: [
        (response) => response.status === 200,
        (response) => {
            const product = JSON.parse(response.string());
            return product.name === 'Updated Product';
        }
    ]
});

// PUT update configuration with timeout and retry handling
const response = http.put('https://api.example.com/config/settings', configData, {
    headers: { 'Authorization': 'Bearer token123' },
    timeout: 20000,
    ignoreHttpErrors: true,
    validators: [
        (response) => response.status >= 200 && response.status < 300
    ]
});

// PUT replace document with version control headers
const response = http.put('https://api.example.com/documents/789', documentContent, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json',
        'X-Document-Version': '2.1',
        'Last-Modified': new Date().toISOString()
    },
    validators: [
        (response) => response.status === 200,
        (response) => response.headers['ETag'] !== undefined
    ]
});

Parameters:

  • url - The URL to request
  • body - The request body data (JSON object, string, or other data)
  • args - Optional configuration object (see HTTP Request Arguments)

PUT requests are used to update or replace entire resources on the server. They’re commonly used in RESTful APIs to update existing records with complete new data.

http.patch(url, body, args)

Make an HTTP PATCH request with a body.

// PATCH update only the email field of a user
const response = http.patch('https://api.example.com/users/123', {
    email: 'newemail@example.com'
});

// PATCH request with timeout and validation for partial updates
const response = http.patch('https://api.example.com/users/123', patchData, {
    timeout: 5000,
    validators: [(response) => response.status === 200]
});

// PATCH update user preferences with authentication and content type
const response = http.patch('https://api.example.com/users/456/preferences', {
    theme: 'dark',
    notifications: false,
    language: 'en-US'
}, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json',
        'User-Agent': 'Loadster'
    },
    validators: [
        (response) => response.status === 200,
        (response) => {
            const prefs = JSON.parse(response.string());
            return prefs.theme === 'dark';
        }
    ]
});

// PATCH partial product update with optimistic locking
const response = http.patch('https://api.example.com/products/789', {
    price: 149.99,
    inStock: true
}, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/merge-patch+json',
        'If-Unmodified-Since': lastModified
    },
    timeout: 10000,
    ignoreHttpErrors: true
});

// PATCH update order status with validation and error handling
const response = http.patch('https://api.example.com/orders/101112', {
    status: 'shipped',
    trackingNumber: 'TRACK123456',
    shippedAt: Date.now()
}, {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json',
        'Idempotency-Key': `order-update-${Date.now()}`
    },
    validators: [
        (response) => response.status === 200,
        (response) => {
            const order = JSON.parse(response.string());
            return order.status === 'shipped' && order.trackingNumber;
        }
    ],
    timeout: 15000
});

Parameters:

  • url - The URL to request
  • body - The request body data (JSON object, string, or other data)
  • args - Optional configuration object (see HTTP Request Arguments)

PATCH requests are used to make partial updates to resources. Unlike PUT, which replaces the entire resource, PATCH only updates the specific fields you provide.

http.delete(url, args)

Make an HTTP DELETE request.

// DELETE simple request to remove a user
const response = http.delete('https://api.example.com/users/123');

// DELETE request with authentication and validation for successful deletion
const response = http.delete('https://api.example.com/users/123', {
    headers: { 'Authorization': 'Bearer token123' },
    validators: [(response) => response.status === 204]
});

// DELETE with conditional headers and error handling
const response = http.delete('https://api.example.com/products/456', {
    headers: {
        'Authorization': 'Bearer token123',
        'If-Match': '"product-revision-xyz"',
        'X-Reason': 'discontinued'
    },
    timeout: 10000,
    ignoreHttpErrors: true,
    validators: [
        (response) => response.status === 204 || response.status === 404
    ]
});

// DELETE with confirmation requirement
const response = http.delete('https://api.example.com/orders/789', {
    headers: {
        'Authorization': 'Bearer token123',
        'X-Confirm-Delete': 'true',
        'X-Delete-Reason': 'customer_request'
    },
    validators: [
        (response) => response.status === 200,
        (response) => {
            const result = JSON.parse(response.string());
            return result.deleted === true;
        }
    ]
});

// DELETE with timeout and validation
const response = http.delete('https://api.example.com/bulk/cleanup', {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json',
        'X-Bulk-Operation': 'true'
    },
    timeout: 30000,
    validators: [
        (response) => response.status === 200,
        (response) => {
            const result = JSON.parse(response.string());
            return result.deletedCount > 0;
        }
    ]
});

Parameters:

DELETE requests are used to remove resources from the server. They’re commonly used in RESTful APIs to delete records or cancel operations.

http.options(url, args)

Make an HTTP OPTIONS request.

// OPTIONS check available HTTP methods for an endpoint
const response = http.options('https://api.example.com/users');

// OPTIONS CORS preflight request to check allowed methods and headers
const response = http.options('https://api.example.com/users', {
    headers: { 'Access-Control-Request-Method': 'POST' }
});

// OPTIONS check CORS policy for cross-origin requests
const response = http.options('https://api.example.com/data', {
    headers: {
        'Access-Control-Request-Method': 'PUT',
        'Access-Control-Request-Headers': 'Authorization, Content-Type',
        'Origin': 'https://myapp.com'
    },
    validators: [
        (response) => response.status === 200,
        (response) => response.headers['Access-Control-Allow-Methods'].includes('PUT')
    ]
});

// OPTIONS probe server capabilities with timeout
const response = http.options('https://api.example.com/v2/capabilities', {
    timeout: 5000,
    ignoreHttpErrors: true,
    validators: [
        (response) => response.status === 200 || response.status === 405
    ]
});

// OPTIONS check API versioning support
const response = http.options('https://api.example.com/endpoint', {
    headers: {
        'Accept': 'application/json',
        'User-Agent': 'API-Explorer/1.0'
    },
    validators: [
        (response) => response.status === 200,
        (response) => response.headers['Allow'] !== undefined
    ]
});

Parameters:

OPTIONS requests are used to retrieve information about the communication options available for a resource or server. They’re commonly used in CORS (Cross-Origin Resource Sharing) preflight requests.

http.trace(url, args)

Make an HTTP TRACE request.

// TRACE basic request to debug request path
const response = http.trace('https://api.example.com/users');

// TRACE request with extended timeout for network debugging
const response = http.trace('https://api.example.com/users', {
    timeout: 10000
});

// TRACE request with custom headers to debug proxy behavior
const response = http.trace('https://api.example.com/debug', {
    headers: {
        'X-Debug-Mode': 'true',
        'User-Agent': 'Loadster-Tracer/1.0'
    },
    timeout: 15000,
    ignoreHttpErrors: true
});

// TRACE debug network path with validation for trace data
const response = http.trace('https://api.example.com/path-test', {
    headers: { 'X-Trace-ID': generateTraceId() },
    validators: [
        (response) => response.status === 200,
        (response) => response.string().includes('TRACE')
    ],
    timeout: 8000
});

// TRACE network diagnostics with comprehensive error handling
const response = http.trace('https://api.example.com/network-test', {
    headers: {
        'X-Network-Test': 'true',
        'Max-Forwards': '10'
    },
    timeout: 20000,
    ignoreHttpErrors: true,
    validators: [
        (response) => response.status >= 200 && response.status < 500
    ]
});

Parameters:

TRACE requests are used for diagnostic purposes to see what changes or additions are made by intermediate servers. They’re rarely used in typical web applications but may be needed for specific debugging scenarios.

HTTP Header Management

These methods manage HTTP headers that are sent with requests. Headers can be set globally for all requests, for specific hosts, or per-request using the args parameter.

http.addHostHeader(host, name, value)

Add a header to all future requests to a specific host.

http.addHostHeader('petstore.loadster.app', 'Authorization', 'Bearer 5a830a310b5ca38a');

This is useful for setting authentication tokens or other headers that should be sent to a specific API or domain throughout your test. The header will be automatically included in all subsequent requests to that host.

http.removeHostHeaders(host, name, value)

Remove host headers matching a host/name/value combination.

// Remove all headers for a host
http.removeHostHeaders('petstore.loadster.app');

// Remove all headers with a specific name for a host
http.removeHostHeaders('petstore.loadster.app', 'Authorization');

// Remove a specific header with exact name/value for a host
http.removeHostHeaders('petstore.loadster.app', 'Authorization', 'Bearer 5a830a310b5ca38a');

This provides flexible control over previously set host headers. You can remove all headers for a host, all headers with a specific name, or headers with exact name/value combinations.

http.addGlobalHeader(name, value)

Add a global header for all requests to all hosts.

http.addGlobalHeader('X-Automated-Testing', 'yes');

Global headers are sent with every HTTP request made by this bot, regardless of the destination host. This is useful for headers that should identify your load test traffic or provide consistent metadata across all requests.

http.removeGlobalHeader(name)

Remove a global header.

http.removeGlobalHeader('X-Automated-Testing');

This removes a previously set global header from all future requests. Useful for changing test behavior or removing headers that are no longer needed.

HTTP Request Arguments

The optional args parameter allows you to customize HTTP requests with headers, validation, error handling, and timeouts. This provides the same functionality as regular HTTP steps but with programmatic control. The args parameter is available on all HTTP request methods.

The args parameter for HTTP methods can include:

  • headers: Object or array of custom headers
  • validators: Array of validation functions
  • ignoreHttpErrors: Boolean to ignore HTTP 4xx/5xx errors
  • timeout: Request timeout in milliseconds

Using args with Different HTTP Methods

// GET request with headers and validation
http.get('https://api.example.com/data', {
    headers: { 'Authorization': 'Bearer token' },
    validators: [(response) => response.status === 200]
});

// POST request with headers and error handling
http.post('https://api.example.com/users', userData, {
    headers: { 'Content-Type': 'application/json' },
    ignoreHttpErrors: true
});

// PUT request with timeout
http.put('https://api.example.com/users/123', updateData, {
    timeout: 5000
});

// DELETE request with multiple options
http.delete('https://api.example.com/users/123', {
    headers: { 'Authorization': 'Bearer token' },
    validators: [(response) => response.status === 204],
    ignoreHttpErrors: true
});

Example with Custom Headers

// Headers as object
const response = http.get('https://api.example.com/data', {
    headers: {
        'Authorization': 'Bearer token123',
        'Content-Type': 'application/json'
    }
});

// Headers as array
const response = http.post('https://api.example.com/data', requestBody, {
    headers: [
        { name: 'Authorization', value: 'Bearer token123' },
        { name: 'Content-Type', value: 'application/json' }
    ]
});

Example with Validators

const response = http.get('https://api.example.com/users', {
    validators: [
        (response) => response.status === 200,
        (response) => {
            const data = JSON.parse(response.string());
            return data.users.length > 0;
        }
    ]
});

Example with Error Handling

const response = http.get('https://api.example.com/might-fail', {
    ignoreHttpErrors: true
});

if (response.status >= 400) {
    console.log('Request failed with status:', response.status);
}

HTTP Response Object

All HTTP methods return a response object that provides access to the server’s response data, headers, and status information.

HTTP methods return a response object with the following properties and methods:

  • response.status: HTTP status code
  • response.headers: Response headers
  • response.string(): Response body as string
  • response.json(): Response body parsed as JSON
  • response.size: Response size in bytes

HTTP Object Usage Notes

  • All HTTP methods are synchronous - no need for await or promise chains
  • The HTTP client maintains cookies and session state automatically throughout the bot’s execution
  • Use validators for response validation and variable capturing, just like regular HTTP steps
  • Set ignoreHttpErrors: true to handle HTTP error codes manually instead of treating them as failures
  • The http object is available in both Protocol Scripts and Browser Scripts
  • Each bot has its own independent HTTP client with separate session state