### Quick Start: Initialize Session and Make Requests Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Initializes an Httpx session with a base URL and default headers, then demonstrates making simple GET, POST, and asynchronous GET requests. ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'MyApp/1.0' }, tags: { service: 'api' } }); // Simple GET const users = session.get('/api/users'); // POST with body const newUser = session.post('/api/users', { name: 'Alice', email: 'alice@example.com' }); // Async request const profile = await session.asyncGet('/api/profile'); ``` -------------------------------- ### Synchronous HTTP Request Examples Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Demonstrates how to perform GET, POST, PUT, and DELETE requests using the synchronous convenience methods. These examples show basic usage for fetching data, creating resources, updating resources, and deleting resources. ```javascript // GET request const users = session.get('/api/users'); // POST with body const newUser = session.post('/api/users', { name: 'Bob', email: 'bob@example.com' }); // PUT to update const updated = session.put('/api/users/1', { name: 'Bob Updated' }); // DELETE const deleted = session.delete('/api/users/1'); ``` -------------------------------- ### Httpx Class and Basic Usage Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Demonstrates creating an Httpx session with default configurations and making simple GET and POST requests, including an asynchronous GET request. ```APIDOC ## Httpx Class and Basic Usage ### Description This section shows how to instantiate the `Httpx` class to manage sessions with default configurations like `baseURL`, `headers`, and `tags`. It also demonstrates making synchronous `get` and `post` requests, as well as an asynchronous `asyncGet` request. ### Method `new Httpx(options)` `session.get(url, body, params)` `session.post(url, body, params)` `session.asyncGet(url, body, params)` ### Parameters #### Httpx Constructor Options - **baseURL** (string) - Optional - The base URL for all requests in the session. - **headers** (object) - Optional - Default headers to include in all requests. - **tags** (object) - Optional - Default tags to apply to all requests. - **errorMetric** (k6/metrics.Counter) - Optional - A k6 Counter metric to automatically increment on request failures. - **errorMetricCondition** (function) - Optional - A function that determines if a response should be considered an error for the `errorMetric`. - **timeout** (number) - Optional - Default timeout for all requests in milliseconds. #### `get`, `post`, `asyncGet` Parameters - **url** (string) - Required - The endpoint path or full URL for the request. - **body** (any) - Optional - The request body (for POST, PUT, etc.). - **params** (object) - Optional - Per-request parameters to merge with session defaults (e.g., `headers`, `tags`). ### Request Example ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'MyApp/1.0' }, tags: { service: 'api' } }); // Simple GET const users = session.get('/api/users'); // POST with body const newUser = session.post('/api/users', { name: 'Alice', email: 'alice@example.com' }); // Async request const profile = await session.asyncGet('/api/profile'); ``` ### Response - **Response Object** - The k6 Response object for the request. ``` -------------------------------- ### Batch Request Example Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Demonstrates using the `batch` method to send multiple GET and POST requests, along with a DELETE request with custom tags. It iterates through the responses to log the status of each individual request. ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const responses = session.batch([ new Get('/api/users/1'), new Get('/api/users/2'), new Post('/api/logs', { event: 'batch_test' }), ['DELETE', '/api/temp/1', null, { tags: { cleanup: true } }] ], { tags: { batch_id: 'batch_001' } }); responses.forEach((r, i) => { console.log(`Request ${i} status: ${r.status}`); }); ``` -------------------------------- ### Asynchronous POST Request Example Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Shows how to perform an asynchronous POST request to an API endpoint for login. The example logs the HTTP status code of the response after the promise resolves. ```javascript const response = await session.asyncPost('/api/login', { username: 'alice', password: 'secret' }); console.log(response.status); ``` -------------------------------- ### Httpx Constructor Mutation Example Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/configuration.md Demonstrates the mutation behavior of the Httpx constructor. Pass a spread copy of the options object to avoid mutation of the original. ```javascript const opts = { baseURL: 'https://api.example.com', headers: { 'User-Agent': 'Test' } }; // WRONG: opts is mutated const session1 = new Httpx(opts); console.log(opts.baseURL); // undefined! // CORRECT: use spread to create a new object const session2 = new Httpx({ ...opts }); console.log(opts.baseURL); // Still 'https://api.example.com' ``` -------------------------------- ### Configuring Httpx Session with Options Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/types.md Shows how to instantiate the Httpx class with custom options. This example configures a baseURL, default headers, default tags, a custom error metric, and a custom error condition. ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; import { Counter } from 'k6/metrics'; const errorCounter = new Counter('api_errors'); const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'TestClient/1.0', 'Authorization': 'Bearer token' }, tags: { service: 'user-service', environment: 'staging' }, errorMetric: errorCounter, errorMetricCondition: (r) => r.status < 400, timeout: 20000 }); ``` -------------------------------- ### Create a GET Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a Get request object for making HTTP GET calls. Supports chaining for adding tags. ```javascript import { Get } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const req = new Get('/api/users/1') .addTag('user_id', '1'); ``` -------------------------------- ### Batch with Absolute URL (Broken Example) Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md This example demonstrates a limitation of the `batch()` method: it always prepends the `baseURL` to all URLs, including absolute ones, which can lead to incorrect URLs. For requests to different domains, use individual `session.get()` calls. ```javascript const session = new Httpx({ baseURL: 'https://api.example.com' }); // BROKEN: becomes https://api.example.comhttps://other.com/data session.batch([ new Get('https://other.com/data') ]); // Use individual requests for other services: const response = session.get('https://other.com/data'); ``` -------------------------------- ### Batch Request Object Format Example Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/types.md Illustrates the Request object format for batch requests, using methods like Get, Post, and Delete. This format is internally converted to the array format. ```javascript Get | Head | Post | Put | Delete | Connect | Options | Trace | Patch ``` ```javascript [ new Get('/api/users/1').addTag('user_id', '1'), new Post('/api/logs', { body: { event: 'test' } }).addHeader('X-Log', 'true'), new Delete('/api/temp') ] ``` -------------------------------- ### Request Objects Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Demonstrates the creation and usage of reusable request objects (e.g., Get, Post) for defining request templates and executing them via a session or in a batch. ```APIDOC ## Request Objects ### Description This section explains how to use method-specific request classes (like `Get`, `Post`) to create reusable request templates. These templates can be executed directly via a session or included in batch requests. ### Method `new Get(url, body, params)` `new Post(url, body, params)` `requestObject.addTag(key, value)` `requestObject.addHeader(name, value)` `session.execute(requestObject)` `session.batch(arrayOfRequestObjects)` ### Parameters #### Request Object Constructors (e.g., `Get`, `Post`) - **url** (string) - Required - The endpoint path. - **body** (any) - Optional - The request body. - **params** (object) - Optional - Parameters for the request. #### `addTag(key, value)` - **key** (string) - The tag key. - **value** (string) - The tag value. #### `addHeader(name, value)` - **name** (string) - The header name. - **value** (string) - The header value. #### `session.execute(requestObject)` - **requestObject** (object) - A request object created using classes like `Get` or `Post`. #### `session.batch(arrayOfRequestObjects)` - **arrayOfRequestObjects** (array) - An array of request objects to execute in a batch. ### Request Example ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com' }); // Create request objects const getUserReq = new Get('/users/1') .addTag('user_id', '1') .addHeader('X-Custom', 'value'); // Execute via session const response = session.execute(getUserReq); // Or use in batch const responses = session.batch([ new Get('/users/1'), new Get('/users/2'), new Post('/logs', { body: { event: 'test' } }) ]); ``` ### Response - **Response Object** - The k6 Response object for a single execution or an array of Response objects for a batch execution. ``` -------------------------------- ### Get Class Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Convenience class for creating GET requests, inheriting from the base Request class. ```APIDOC ## Get ```javascript new Get(url: string, params: object): Get ``` Create a GET request. **Example:** ```javascript import { Get } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const req = new Get('/api/users/1') .addTag('user_id', '1'); ``` ``` -------------------------------- ### Using Request Objects for Reusable Templates Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Creates reusable request objects (Get, Post) with custom headers and tags, then executes them via a session or in a batch. ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com' }); // Create request objects const getUserReq = new Get('/users/1') .addTag('user_id', '1') .addHeader('X-Custom', 'value'); // Execute via session const response = session.execute(getUserReq); // Or use in batch const responses = session.batch([ new Get('/users/1'), new Get('/users/2'), new Post('/logs', { body: { event: 'test' } }) ]); ``` -------------------------------- ### Parameter Merging: Session and Per-Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Demonstrates how session-level default parameters (headers, tags) are merged with per-request parameters for a GET request. ```javascript // Session-level defaults const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'MyApp' }, tags: { service: 'api' } }); // Per-request parameters add to session defaults const response = session.get('/users', null, { headers: { 'X-Request-ID': 'req123' }, // Added to session headers tags: { action: 'list' } // Added to session tags }); // Final request has User-Agent, X-Request-ID, service, and action ``` -------------------------------- ### Batch Request Array Format Example Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/types.md Demonstrates the array format for defining batch requests, where each element is [method, url, body, params]. Note that baseURL is always prepended to URLs, including absolute ones. ```javascript [method: string, url: string, body: any, params?: object] ``` ```javascript [ ['GET', '/api/users/1', null, { tags: { user_id: '1' } }], ['POST', '/api/logs', { event: 'test' }, { headers: { 'X-Log': 'true' } }], ['DELETE', '/api/temp', null] ] ``` -------------------------------- ### Asynchronous Request Example Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Asynchronous requests using `session.asyncGet()` return a promise immediately without blocking. The `lastRequest` property is NOT updated by asynchronous requests. You must `await` the promise to get the response. ```javascript const promise = session.asyncGet('/users'); // Returns immediately const response = await promise; // Blocks on await console.log(session.lastRequest.responseObject); // Still undefined! ``` -------------------------------- ### execute Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Execute a Request object (such as Get, Post, Put, etc.) via the session. ```APIDOC ## execute ### Description Execute a Request object (such as Get, Post, Put, etc.) via the session. ### Method `execute(request: Request): Response` ### Parameters - **request** (Request) - Required - A Request object created from a method-specific class ### Return k6 Response object. ### Example ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const getReq = new Get('/api/users/1'); const response = session.execute(getReq); ``` ``` -------------------------------- ### Execute a Request Object with Session Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Use the `execute` method to send a pre-constructed `Request` object (like `Get` or `Post`) through the session. This method returns the k6 `Response` object. ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const getReq = new Get('/api/users/1'); const response = session.execute(getReq); ``` -------------------------------- ### Execute Batch Requests Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Use Request objects (like Get, Post) within a batch operation managed by the Httpx session. This allows for efficient execution of multiple requests. ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com' }); const batchRequests = [ new Get('/api/users/1').addTag('user_id', '1'), new Get('/api/users/2').addTag('user_id', '2'), new Post('/api/logs', { body: { event: 'batch_test' } }) ]; const responses = session.batch(batchRequests, { tags: { batch_id: 'test_001' } }); responses.forEach((r, i) => { console.log(`Request ${i}: ${r.status}`); }); ``` -------------------------------- ### Synchronous HTTP Methods Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Use these convenience methods for common HTTP verbs like GET, POST, PUT, and DELETE. They internally call the `request()` function with the specified method. Parameters include URL, optional body, and request-specific parameters. ```javascript get(url: string, body: any, params: RequestParams): Response head(url: string, body: any, params: RequestParams): Response post(url: string, body: any, params: RequestParams): Response put(url: string, body: any, params: RequestParams): Response delete(url: string, body: any, params: RequestParams): Response connect(url: string, body: any, params: RequestParams): Response options(url: string, body: any, params: RequestParams): Response trace(url: string, body: any, params: RequestParams): Response patch(url: string, body: any, params: RequestParams): Response ``` -------------------------------- ### Synchronous Request Example Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Synchronous requests using `session.get()` block execution until the request is complete and update the `lastRequest` property on the session object. This allows immediate access to request details like status and duration. ```javascript const response = session.get('/users'); // Blocks until response console.log(session.lastRequest.responseObject.status); console.log(session.lastRequest.responseChainDuration); ``` -------------------------------- ### Synchronous HTTP Methods Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Provides synchronous convenience methods for common HTTP verbs like GET, POST, PUT, DELETE, etc. Each method internally calls the `request()` function with the appropriate HTTP method. These methods are suitable for scenarios where immediate response handling is required. ```APIDOC ## Synchronous HTTP Methods ### Description Convenience methods for common HTTP verbs. Each calls `request()` internally with the appropriate method. ### Methods - `get(url: string, body: any, params: RequestParams): Response` - `head(url: string, body: any, params: RequestParams): Response` - `post(url: string, body: any, params: RequestParams): Response` - `put(url: string, body: any, params: RequestParams): Response` - `delete(url: string, body: any, params: RequestParams): Response` - `connect(url: string, body: any, params: RequestParams): Response` - `options(url: string, body: any, params: RequestParams): Response` - `trace(url: string, body: any, params: RequestParams): Response` - `patch(url: string, body: any, params: RequestParams): Response` ### Parameters - **url** (string | HttpUrl) - Required - Absolute or relative URL - **body** (any) - Optional - Request body (typically used for POST, PUT, PATCH) - **params** (object) - Optional - Request-specific parameters ### Return - k6 Response object. ### Example ```javascript // GET request const users = session.get('/api/users'); // POST with body const newUser = session.post('/api/users', { name: 'Bob', email: 'bob@example.com' }); // PUT to update const updated = session.put('/api/users/1', { name: 'Bob Updated' }); // DELETE const deleted = session.delete('/api/users/1'); ``` ``` -------------------------------- ### Batch URL Prepending Issue with Absolute URLs Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/errors.md The batch() method prepends baseURL to all URLs, including absolute ones starting with 'http://', causing incorrect URLs. Use relative URLs in batch or make requests to external services individually. ```javascript const session = new Httpx({ baseURL: 'https://api.example.com' }); const responses = session.batch([ new Get('/api/users'), // OK: becomes https://api.example.com/api/users new Get('https://other-service.com/api/data') // BROKEN: becomes https://api.example.comhttps://other-service.com/api/data ]); ``` ```javascript const session = new Httpx({ baseURL: 'https://api.example.com' }); const batchResponses = session.batch([ new Get('/api/users'), new Get('/api/settings') ]); // For requests to other services, use individual synchronous requests: const otherServiceResponse = session.get('https://other-service.com/api/data'); ``` -------------------------------- ### Basic httpx Usage with Authentication Source: https://github.com/grafana/k6-jslib-httpx/blob/master/README.md Demonstrates how to initialize the Httpx client, register a user, authenticate, and create a new resource. The session is configured with a base URL and headers, and the authorization token is added after login for subsequent requests. ```javascript import { test } from 'https://jslib.k6.io/functional/0.0.1/index.js'; import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; import { randomIntBetween, randomItem } from "https://jslib.k6.io/k6-utils/1.2.0/index.js"; const USERNAME = `user${randomIntBetween(1, 100000)}@example.com`; // random email address const PASSWORD = 'superCroc2021'; let session = new Httpx({ baseURL: 'https://test-api.k6.io', headers: { 'User-Agent': "My custom user agent", "Content-Type": 'application/x-www-form-urlencoded' }, timeout: 20000 // 20s timeout. }); export default function testSuite() { test(`Create a test user ${USERNAME}`, (t) => { let resp = session.post(`/user/register/`, { first_name: 'Crocodile', last_name: 'Owner', username: USERNAME, password: PASSWORD, }); t.expect(resp.status).as("status").toEqual(201) .and(resp).toHaveValidJson(); }) && test(`Authenticate the new user ${USERNAME}`, (t) => { let resp = session.post(`/auth/token/login/`, { username: USERNAME, password: PASSWORD }); t.expect(resp.status).as("Auth status").toBeBetween(200, 204) .and(resp).toHaveValidJson() .and(resp.json('access')).as("auth token").toBeTruthy(); let authToken = resp.json('access'); // set the authorization header on the session for the subsequent requests. session.addHeader('Authorization', `Bearer ${authToken}`); }) && test('Create a new crocodile', (t) => { let payload = { name: `Croc Name`, sex: randomItem(["M", "F"]), date_of_birth: '2019-01-01', }; let resp = session.post(`/my/crocodiles/`, payload); t.expect(resp.status).as("Croc creation status").toEqual(201) .and(resp).toHaveValidJson(); }) } ``` -------------------------------- ### Initialize Httpx Session with Options Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/configuration.md Configure a new httpx session with various options like baseURL, headers, tags, and error tracking. This sets up default parameters for all subsequent requests made with this session. ```javascript const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'MyApp/1.0' }, tags: { service: 'api' }, errorMetric: metricsObject, errorMetricCondition: (r) => r.status < 400, enableHttpReqErrorMetric: false, timeout: 30000, // ... other k6 HTTP module parameters }); ``` -------------------------------- ### Configuring Httpx with k6 Metrics for Error Tracking Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/types.md Demonstrates how to initialize Httpx with a k6 Counter metric and a condition for tracking HTTP errors. Errors are automatically incremented when the condition is false. ```javascript import { Counter } from 'k6/metrics'; import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const errors = new Counter('http_errors'); const session = new Httpx({ baseURL: 'https://api.example.com', errorMetric: errors, errorMetricCondition: (r) => r.status < 400 }); // Errors are automatically incremented when errorMetricCondition returns false ``` -------------------------------- ### Initialize Httpx Session Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Create a new Httpx session with default configurations for baseURL, headers, and tags. You can also specify a custom timeout. ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'My App/1.0', 'Authorization': 'Bearer token123' }, tags: { service: 'user-api', version: 'v1' }, timeout: 30000 }); ``` -------------------------------- ### Httpx Constructor Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Creates a new Httpx session with optional default configurations for requests. These defaults can include a base URL, headers, tags, and custom error metric tracking. ```APIDOC ## Constructor ```javascript new Httpx(opts: HttpxOptions): Httpx ``` Creates a new HTTP session with optional default configuration. ### Parameters #### Options (`opts`) - **baseURL** (string) - Optional - Base URL prepended to relative URLs in all requests. Defaults to `''`. - **headers** (object) - Optional - Default headers merged into every request. Defaults to `{}`. - **tags** (object) - Optional - Default tags merged into every request. Defaults to `{}`. - **errorMetric** (Metric \| null) - Optional - k6 Metric object to track request failures. Defaults to `null`. - **errorMetricCondition** (function) - Optional - Function determining if a response is successful (true = success, false = error). Defaults to `(r) => r.status >= 200 && r.status <= 399`. - **enableHttpReqErrorMetric** (boolean) - Optional - Reserved for internal k6 use. Defaults to `false`. - **...otherK6Params** (any) - Optional - Any additional k6-compatible parameters (timeout, TLS options, etc.). ### Example ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'My App/1.0', 'Authorization': 'Bearer token123' }, tags: { service: 'user-api', version: 'v1' }, timeout: 30000 }); ``` ``` -------------------------------- ### Session Configuration and Parameter Merging Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Illustrates how to configure an Httpx session with defaults and how per-request parameters merge with these session-level defaults. ```APIDOC ## Session Configuration and Parameter Merging ### Description This section details how to configure a session with `baseURL`, `headers`, and `tags`. It also explains how parameters provided at the individual request level are merged with the session's default configuration. ### Method `new Httpx(options)` `session.get(url, body, params)` ### Parameters #### Httpx Constructor Options - **baseURL** (string) - Required - The base URL for all requests in the session. - **headers** (object) - Optional - Default headers to include in all requests. - **tags** (object) - Optional - Default tags to apply to all requests. #### `get` Parameters - **url** (string) - Required - The endpoint path. - **params** (object) - Optional - Per-request parameters (e.g., `headers`, `tags`) that will be merged with session defaults. ### Request Example ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; // Session-level defaults const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'User-Agent': 'MyApp' }, tags: { service: 'api' } }); // Per-request parameters add to session defaults const response = session.get('/users', null, { headers: { 'X-Request-ID': 'req123' }, // Added to session headers tags: { action: 'list' } // Added to session tags }); // Final request has User-Agent, X-Request-ID, service, and action ``` ### Response - **Response Object** - The k6 Response object for the request. ``` -------------------------------- ### Authentication with Token Refresh Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md This pattern demonstrates how to perform an initial login to obtain an authentication token, add it to the session's headers, and then use that token for subsequent authenticated requests. Ensure the login response contains the token in a predictable format. ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com' }); // Initial login const loginResp = session.post('/auth/login', { username: 'user@example.com', password: 'password' }); if (loginResp.status === 200) { const token = loginResp.json('access_token'); session.addHeader('Authorization', `Bearer ${token}`); // Subsequent requests use the token const users = session.get('/users'); } ``` -------------------------------- ### Create an OPTIONS Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate an Options request object for making HTTP OPTIONS calls. ```javascript new Options(url: string, params: object): Options ``` -------------------------------- ### Get Last Synchronous Request Duration Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md The `lastRequestChainDuration` accessor returns the duration in milliseconds of the last synchronous request, providing a convenient way to retrieve this timing information. ```javascript session.get('/api/health'); const duration = session.lastRequestChainDuration; console.log(`Request took ${duration}ms`); ``` -------------------------------- ### HttpxOptions Constructor Options Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/types.md Defines the structure of the HttpxOptions object used to configure the Httpx class constructor. It includes options for baseURL, headers, tags, error tracking, and custom error conditions. ```javascript { baseURL?: string, headers?: Record, tags?: Record, errorMetric?: Metric | null, errorMetricCondition?: (response: Response) => boolean, enableHttpReqErrorMetric?: boolean, // ... any additional k6 parameters } ``` -------------------------------- ### Custom Error Metric Condition Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/errors.md Configures a custom condition for incrementing an error metric based on response status codes. This example treats only 200-299 as success, incrementing the metric for other codes. ```javascript import { Counter } from 'k6/metrics'; import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const httpErrors = new Counter('http_request_errors'); const session = new Httpx({ baseURL: 'https://api.example.com', errorMetric: httpErrors, // Only 200-299 is considered success; 300-399 are treated as errors errorMetricCondition: (r) => r.status >= 200 && r.status < 300 }); const response = session.post('/api/users', { name: 'Alice' }); if (response.status === 201) { console.log('Success'); } else if (response.status >= 300) { // errorMetric was incremented automatically console.log('Redirect treated as error per condition'); } ``` -------------------------------- ### Override Error Metric Condition for a Single Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/errors.md Demonstrates how to override the session-level error metric condition for a specific request using the 'expect' parameter. This example treats both 201 and 404 as success. ```javascript import { Counter } from 'k6/metrics'; import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const httpErrors = new Counter('http_errors'); const session = new Httpx({ baseURL: 'https://api.example.com', errorMetric: httpErrors, errorMetricCondition: (r) => r.status >= 200 && r.status <= 399 }); // Override for this single request: treat 404 as success const response = session.post('/api/users', { name: 'Alice' }, { expect: (r) => r.status === 201 || r.status === 404 } ); ``` -------------------------------- ### Using Request Objects with Batch Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Demonstrates how to use Request objects (including method-specific subclasses) with the `batch()` method for constructing complex batch operations. ```APIDOC ## Using Request Objects with Batch Request objects are commonly used with the `batch()` method to build complex batch operations: ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com' }); const batchRequests = [ new Get('/api/users/1').addTag('user_id', '1'), new Get('/api/users/2').addTag('user_id', '2'), new Post('/api/logs', { body: { event: 'batch_test' } }) ]; const responses = session.batch(batchRequests, { tags: { batch_id: 'test_001' } }); responses.forEach((r, i) => { console.log(`Request ${i}: ${r.status}`); }); ``` ``` -------------------------------- ### Create a HEAD Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a Head request object for making HTTP HEAD calls. ```javascript new Head(url: string, params: object): Head ``` -------------------------------- ### Create a CONNECT Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a Connect request object for making HTTP CONNECT calls. ```javascript new Connect(url: string, params: object): Connect ``` -------------------------------- ### Create a Request Object Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a base Request object with a method, URL, and optional parameters including headers and tags. This is useful for custom request construction. ```javascript import { Request } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const req = new Request('GET', '/api/users', { headers: { 'X-Custom': 'value' }, tags: { endpoint: 'users' } }); ``` -------------------------------- ### Session Configuration with Defaults and Error Metrics Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Configures an Httpx session with a base URL, custom headers, tags, an error metric counter, and a request timeout. ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; import { Counter } from 'k6/metrics'; const errorCounter = new Counter('http_errors'); const session = new Httpx({ baseURL: 'https://api.example.com', headers: { 'Authorization': 'Bearer token123', 'User-Agent': 'MyApp/1.0' }, tags: { service: 'user-api', environment: 'staging' }, errorMetric: errorCounter, timeout: 30000 }); // All requests use session defaults const users = session.get('/users'); const newUser = session.post('/users', { name: 'Bob' }); ``` -------------------------------- ### Create a TRACE Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a Trace request object for making HTTP TRACE calls. ```javascript new Trace(url: string, params: object): Trace ``` -------------------------------- ### Request Constructor Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Creates a base Request object with a specified HTTP method, URL, and optional parameters including headers, tags, and body. ```APIDOC ## Constructor ```javascript new Request(method: string, url: string, params: object): Request ``` Create a Request object with a specific HTTP method and URL. | Parameter | Type | Default | Description | |-----------|------|---------|-------------| | method | string | — | HTTP method (GET, HEAD, POST, PUT, DELETE, CONNECT, OPTIONS, TRACE, PATCH) | | url | string \| HttpUrl | — | Target URL (relative or absolute). If an http.url object, extracts the URL and name tag automatically | | params | object | `{}` | Request parameters including headers, tags, body, and other k6 options | **Example:** ```javascript import { Request } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const req = new Request('GET', '/api/users', { headers: { 'X-Custom': 'value' }, tags: { endpoint: 'users' } }); ``` ``` -------------------------------- ### Create a PUT Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a Put request object for making HTTP PUT calls. ```javascript new Put(url: string, params: object): Put ``` -------------------------------- ### Handle Relative and Absolute URLs Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md The `Httpx` session class supports both relative and absolute URLs. Relative URLs are prepended with the `baseURL` defined in the session. Absolute URLs bypass the `baseURL`. k6's `http.url` template tag is also supported for automatic tag extraction. ```javascript const session = new Httpx({ baseURL: 'https://api.example.com' }); // Relative URLs get baseURL prepended session.get('/users'); // https://api.example.com/users // Absolute URLs bypass baseURL session.get('https://other.com/data'); // https://other.com/data // k6's http.url template tag is supported import http from 'k6/http'; const id = '123'; session.get(http.url`/users/${id}`); // Name tag is extracted automatically ``` -------------------------------- ### Using HttpUrl in Requests Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/types.md Demonstrates how to use an HttpUrl object with the httpx library. The library automatically detects HttpUrl objects and uses their name as a tag for the request. ```javascript import http from 'k6/http'; import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const session = new Httpx({ baseURL: 'https://api.example.com' }); const userId = '123'; const response = session.get(http.url`/users/${userId}/profile`); // The name tag is extracted and applied automatically ``` -------------------------------- ### Create a POST Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a Post request object for making HTTP POST calls. Allows setting a request body and adding headers. ```javascript import { Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const req = new Post('/api/users', { body: { name: 'Alice', email: 'alice@example.com' } }).addHeader('Content-Type', 'application/json'); ``` -------------------------------- ### Asynchronous HTTP Methods Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md These asynchronous convenience methods (e.g., `asyncPost`, `asyncGet`) allow for non-blocking HTTP requests. They return a Promise that resolves to a k6 Response object. Similar to synchronous methods, they accept URL, body, and parameters. ```javascript asyncGet(url: string, body: any, params: RequestParams): Promise asyncHead(url: string, body: any, params: RequestParams): Promise asyncPost(url: string, body: any, params: RequestParams): Promise asyncPut(url: string, body: any, params: RequestParams): Promise asyncDelete(url: string, body: any, params: RequestParams): Promise asyncConnect(url: string, body: any, params: RequestParams): Promise asyncOptions(url: string, body: any, params: RequestParams): Promise asyncTrace(url: string, body: any, params: RequestParams): Promise asyncPatch(url: string, body: any, params: RequestParams): Promise ``` -------------------------------- ### Connect Class Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Convenience class for creating CONNECT requests, inheriting from the base Request class. ```APIDOC ## Connect ```javascript new Connect(url: string, params: object): Connect ``` Create a CONNECT request. ``` -------------------------------- ### Options Class Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Convenience class for creating OPTIONS requests, inheriting from the base Request class. ```APIDOC ## Options ```javascript new Options(url: string, params: object): Options ``` Create an OPTIONS request. ``` -------------------------------- ### Multi-Endpoint Testing with Multiple Sessions Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md Manage requests to different API endpoints or services by creating separate `Httpx` session instances, each configured with its own `baseURL`. This approach helps in organizing and isolating requests to distinct services. ```javascript import { Httpx } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const sessions = { api: new Httpx({ baseURL: 'https://api.example.com' }), auth: new Httpx({ baseURL: 'https://auth.example.com' }), data: new Httpx({ baseURL: 'https://data.example.com' }) }; const user = sessions.api.get('/users/1'); const token = sessions.auth.post('/login', { user: 'test' }); const data = sessions.data.get('/data'); ``` -------------------------------- ### Create a PATCH Request Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Instantiate a Patch request object for making HTTP PATCH calls. ```javascript new Patch(url: string, params: object): Patch ``` -------------------------------- ### Inspect Request and Response Details Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/README.md After making a request, you can inspect various details of the response, including status, headers, body, and timings. The `Httpx` session also provides access to `lastRequestChainDuration` for inspecting the duration of the last completed request. ```javascript const session = new Httpx({ baseURL: 'https://api.example.com' }); const response = session.post('/users', { name: 'Alice' }); // Inspect response console.log('Status:', response.status); console.log('Headers:', response.headers); console.log('Body:', response.body); console.log('Timings:', response.timings); // Parse JSON const user = response.json(); console.log('Created user:', user); // Inspect session state console.log('Last request duration:', session.lastRequestChainDuration); ``` -------------------------------- ### Configure Request Parameters with Merged Session Defaults Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/configuration.md Send requests with parameters that merge session-level defaults with request-specific overrides. This includes headers, tags, timeouts, and custom error conditions. ```javascript const response = session.post('/api/users', { name: 'Alice', email: 'alice@example.com' }, { headers: { 'X-Request-ID': 'req123' }, tags: { action: 'create', entity: 'user' }, timeout: 15000, expect: (r) => r.status === 201 } ); ``` -------------------------------- ### Post Class Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/request.md Convenience class for creating POST requests, inheriting from the base Request class. ```APIDOC ## Post ```javascript new Post(url: string, params: object): Post ``` Create a POST request. **Example:** ```javascript import { Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const req = new Post('/api/users', { body: { name: 'Alice', email: 'alice@example.com' } }).addHeader('Content-Type', 'application/json'); ``` ``` -------------------------------- ### Batch Request Execution Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Allows executing multiple HTTP requests in a single batch operation for improved efficiency. All requests in the batch will have the `baseURL` prepended, including absolute URLs, which requires careful handling to avoid double-prefixing. ```APIDOC ## Batch Request Execution ### Description Execute multiple requests in a single batch operation. All requests always have baseURL prepended, even absolute URLs. ### Method Signature `batch(array_of_requests: Array, batch_shared_params: object): Array` ### Parameters - **array_of_requests** (Array) - Required - Array of batch request elements. Each element is either a 4-element array `[method, url, body, params]` or a Request object instance. - **batch_shared_params** (object) - Optional - Parameters shared across all requests in the batch, merged with per-request and session-level params. ### Return - Array of k6 Response objects, one per request in the same order. ### Details The batch method processes each request element and prepends baseURL to every URL. Request objects are converted to the internal batch format. Headers and tags from batch_shared_params are merged with session defaults and per-request values. After the batch completes, `lastRequest.responseObject` is set to the entire response array and `lastRequest.responseChainDuration` is set to the total batch duration. **Important caveat:** batch always prepends baseURL to all URLs, including absolute URLs. This differs from individual request methods, which skip baseURL for absolute URLs. Passing absolute URLs to batch may produce broken double-prefixed URLs. ### Example ```javascript import { Httpx, Get, Post } from 'https://jslib.k6.io/httpx/0.0.6/index.js'; const responses = session.batch([ new Get('/api/users/1'), new Get('/api/users/2'), new Post('/api/logs', { event: 'batch_test' }), ['DELETE', '/api/temp/1', null, { tags: { cleanup: true } }] ], { tags: { batch_id: 'batch_001' } }); responses.forEach((r, i) => { console.log(`Request ${i} status: ${r.status}`); }); ``` ``` -------------------------------- ### Asynchronous HTTP Methods Source: https://github.com/grafana/k6-jslib-httpx/blob/master/_autodocs/api-reference/httpx.md Provides asynchronous convenience methods for common HTTP verbs, returning Promises that resolve to a k6 Response object. These methods are ideal for non-blocking operations, allowing other code to execute while waiting for the HTTP response. ```APIDOC ## Asynchronous HTTP Methods ### Description Asynchronous convenience methods for common HTTP verbs. Each calls `asyncRequest()` internally with the appropriate method. ### Methods - `asyncGet(url: string, body: any, params: RequestParams): Promise` - `asyncHead(url: string, body: any, params: RequestParams): Promise` - `asyncPost(url: string, body: any, params: RequestParams): Promise` - `asyncPut(url: string, body: any, params: RequestParams): Promise` - `asyncDelete(url: string, body: any, params: RequestParams): Promise` - `asyncConnect(url: string, body: any, params: RequestParams): Promise` - `asyncOptions(url: string, body: any, params: RequestParams): Promise` - `asyncTrace(url: string, body: any, params: RequestParams): Promise` - `asyncPatch(url: string, body: any, params: RequestParams): Promise` ### Parameters - **url** (string | HttpUrl) - Required - Absolute or relative URL - **body** (any) - Optional - Request body - **params** (object) - Optional - Request-specific parameters ### Return - Promise that resolves to a k6 Response object. ### Example ```javascript const response = await session.asyncPost('/api/login', { username: 'alice', password: 'secret' }); console.log(response.status); ``` ```