### Example API Request with Environment Variables Source: https://docs.echolon.app/getting-started/quick-start Demonstrates how to use environment variables within an API request in Echolon. This allows for easy switching between different configurations like development and production without modifying the request itself. It shows a GET request utilizing placeholders for baseUrl and userId, followed by example environment configurations. ```echolon // Example: Using environment variables GET {{baseUrl}}/users/{{userId}} // Development environment baseUrl = http://localhost:3000 userId = 1 // Production environment baseUrl = https://api.example.com userId = 12345 ``` -------------------------------- ### Create Authenticated Requests with Timestamps (GET Request) Source: https://docs.echolon.app/features/variables Demonstrates creating authenticated GET requests by including an API token, a unique request ID, and a Unix timestamp in the headers. ```http GET /api/data Authorization: Bearer {{apiToken}} X-Request-ID: {{uuid.v4}} X-Timestamp: {{timestamp.unix}} ``` -------------------------------- ### URL-Encoded Query Parameters (GET Request) Source: https://docs.echolon.app/features/variables Illustrates how to use URL encoding for query parameters in a GET request to handle spaces and special characters correctly, combined with a Unix timestamp. ```http GET /api/search?q={{url.encode(value="hello world")}}×tamp={{timestamp.unix}} ``` -------------------------------- ### Generate Unique User Data for Testing (POST Request) Source: https://docs.echolon.app/features/variables Example of generating unique user data for a POST request using functions like uuid.v4, random.firstName, random.lastName, random.email, and timestamp.iso8601. ```json POST /api/users Content-Type: application/json { "id": "{{uuid.v4}}", "firstName": "{{random.firstName}}", "lastName": "{{random.lastName}}", "email": "{{random.email}}", "createdAt": "{{timestamp.iso8601}}" } ``` -------------------------------- ### Random Data Generation Functions Source: https://docs.echolon.app/features/variables Provides examples of using Echolon's random data generation functions. These functions are useful for creating test data, mock responses, and ensuring unique values in requests. ```text {{random.range(min=1, max=100)}} {{random.integer(min=10, max=20)}} {{random.float(min=0.1, max=0.9, decimals=2)}} {{random.boolean}} {{random.firstName}} {{random.lastName}} {{random.fullName}} {{random.email(domain="example.com")}} {{random.phone(format="(###) ###-####")}} {{random.username}} {{random.password(length=12)}} {{random.alphanumeric(length=8)}} {{random.word}} {{random.sentence(words=10)}} {{random.paragraph(sentences=5)}} {{random.company}} {{random.address}} {{random.city}} {{random.country}} {{random.hexColor}} {{random.ipv4}} {{random.ipv6}} {{random.url}} {{random.date(start="2023-01-01", end="2023-12-31")}} {{random.creditCard}} ``` -------------------------------- ### Using Environment Variables in Requests Source: https://docs.echolon.app/features/environments Demonstrates how to reference environment variables within request URLs and headers using double curly braces. These variables can be dynamically substituted with their active values from the selected environments. ```http GET {{baseUrl}}/api/users Authorization: Bearer {{apiToken}} ``` -------------------------------- ### Referencing Variables and Functions in URLs Source: https://docs.echolon.app/features/variables Demonstrates how to reference variables and call dynamic functions within a URL string. This allows for dynamic endpoint construction based on predefined variables or generated values. ```text {{baseUrl}}/users/{{userId}} {{random.range(min=1, max=100)}} {{timestamp.format(format="YYYY-MM-DD")}} {{uuid.v4}} {{timestamp.iso8601}} ``` -------------------------------- ### Base64-Encoded Credentials (Authorization Header) Source: https://docs.echolon.app/features/variables Shows how to create Basic Authentication credentials by Base64 encoding a username and password combination. ```http Authorization: Basic {{base64.encode(value="{{username}}:{{password}}")}} ``` -------------------------------- ### Generate API Signatures (POST Request) Source: https://docs.echolon.app/features/variables Demonstrates generating an API signature using SHA256 hashing, combining a secret key and a Unix timestamp for request verification. ```http POST /api/webhook X-Signature: {{hash.sha256(input="{{secretKey}}{{timestamp.unix}}")}} X-Timestamp: {{timestamp.unix}} ``` -------------------------------- ### Interact with Environment Variables using echo Object (JavaScript) Source: https://docs.echolon.app/features/scripts Demonstrates using the `echo` object to retrieve environment variables with `echo.getEnvVar` and set environment variables with `echo.setEnvVar`. This is useful for managing configuration and session data. ```javascript // Get base URL from environment const baseUrl = echo.getEnvVar('baseUrl'); console.log('Using base URL:', baseUrl); // Set a variable for later use echo.setEnvVar('lastRequestTime', Date.now().toString()); ``` -------------------------------- ### Log Response Details (Echolon Script) Source: https://docs.echolon.app/features/scripts Logs key details of the response, including status code, status text, response time in milliseconds, and a preview of the response body (first 200 characters). This is helpful for debugging and understanding the response. ```javascript // Log response details console.log('Status:', res.status, res.statusText); console.log('Response time:', res.responseTime, 'ms'); console.log('Body preview:', res.body.substring(0, 200)); ``` -------------------------------- ### Timestamp Generation Functions Source: https://docs.echolon.app/features/variables Shows how to generate timestamps in various formats using Echolon's timestamp functions. This is useful for logging, tracking, and time-sensitive operations. ```text {{timestamp.now}} {{timestamp.unix}} {{timestamp.unixMillis}} {{timestamp.iso8601}} {{timestamp.date}} {{timestamp.time}} {{timestamp.format(format="YYYY/MM/DD HH:mm:ss.SSS")}} {{timestamp.format(format="DD-MM-YYYY")}} {{timestamp.format(format="HH:mm")}} {{timestamp.format(format="YYYY")}} {{timestamp.format(format="MM")}} {{timestamp.format(format="DD")}} {{timestamp.format(format="HH")}} {{timestamp.format(format="mm")}} {{timestamp.format(format="ss")}} {{timestamp.format(format="SSS")}} {{timestamp.format()}} ``` -------------------------------- ### Hashing Functions Source: https://docs.echolon.app/features/variables Demonstrates how to generate cryptographic hashes using Echolon's built-in functions. These can be used for data integrity checks or security-related operations. If no input is provided, a random string is hashed. ```text {{hash.md5("mySecretData")}} {{hash.sha1("mySecretData")}} {{hash.sha256("mySecretData")}} {{hash.sha512("mySecretData")}} {{hash.md5}} {{hash.sha256}} ``` -------------------------------- ### Generate Random Test Data for Orders (POST Request) Source: https://docs.echolon.app/features/variables Shows how to generate random data for an order, including order ID, amount, item count, and shipping address, using functions like random.alphanumeric, random.range, random.integer, and random.address. ```json POST /api/orders Content-Type: application/json { "orderId": "ORD-{{random.alphanumeric(length=8)}}", "amount": {{random.range(min=10, max=500, decimals=2)}}, "items": {{random.integer(min=1, max=10)}}, "shippingAddress": "{{random.address}}, {{random.city}}" } ``` -------------------------------- ### Encode and Decode Strings (Base64, URL) Source: https://docs.echolon.app/features/variables Provides functions for Base64 and URL encoding and decoding. These are useful for preparing data for transmission or storage. ```javascript base64.encode(value) base64.decode(value) url.encode(value) url.decode(value) ``` -------------------------------- ### UUID Generation Functions Source: https://docs.echolon.app/features/variables Illustrates the usage of Echolon's UUID generation functions. These functions are essential for creating unique identifiers for resources or requests. ```text {{uuid.v1}} {{uuid.v4}} ``` -------------------------------- ### Modify Request Details using req Object (JavaScript) Source: https://docs.echolon.app/features/scripts This script shows how to access and modify request details like URL, method, headers, and body using the `req` object. It demonstrates adding an 'Authorization' header and updating the request body. ```javascript // Log current request details console.log('Making', req.method, 'request to', req.url); // Add authentication header const token = echo.getEnvVar('auth_token'); if (token) { req.setHeader('Authorization', 'Bearer ' + token); } // Modify the request body const body = JSON.parse(req.getBody() || '{}'); body.timestamp = Date.now(); req.setBody(JSON.stringify(body)); ``` -------------------------------- ### Process Response Data using res Object (JavaScript) Source: https://docs.echolon.app/features/scripts This script utilizes the `res` object in post-request scripts to check the response status, parse the JSON body, extract data, and log performance metrics. It demonstrates error handling for JSON parsing and setting environment variables based on response data. ```javascript // Check response status if (res.status !== 200) { console.error('Request failed with status:', res.status, res.statusText); } // Parse JSON response try { const data = JSON.parse(res.body); console.log('Response data:', data); // Store user ID for next request if (data.id) { echo.setEnvVar('userId', data.id.toString()); } } catch (e) { console.error('Failed to parse response as JSON'); } // Log performance console.log('Request completed in', res.responseTime, 'ms'); ``` -------------------------------- ### Add Authentication Header (Echolon Script) Source: https://docs.echolon.app/features/scripts Adds a Bearer token authentication header to the request. It retrieves the token from environment variables using `echo.getEnvVar` and sets the 'Authorization' header if the token exists. Logs a warning if the token is not found. ```javascript // Add Bearer token authentication const token = echo.getEnvVar('auth_token'); if (token) { req.setHeader('Authorization', 'Bearer ' + token); console.log('Added auth header'); } else { console.warn('No auth token found in environment'); } ``` -------------------------------- ### Extract and Store Token in Post-request Script (JavaScript) Source: https://docs.echolon.app/features/scripts This script parses the response body, extracts an authentication token if present, and stores it in an environment variable using `echo.setEnvVar`. It also logs the response status. ```javascript // Parse response and store auth token const data = JSON.parse(res.body); if (data.token) { echo.setEnvVar('auth_token', data.token); console.log('Token saved to environment'); } console.log('Response status:', res.status); ``` -------------------------------- ### Access Current Context Information Source: https://docs.echolon.app/features/variables Allows access to contextual information within the Echolon App, such as the current workspace, environment, collection, and request IDs. ```javascript ctx.workspace ctx.environment ctx.collection ctx.request ``` -------------------------------- ### Manipulate JSON Data Source: https://docs.echolon.app/features/variables Offers utilities for working with JSON data, including minification, escaping special characters for JSON compatibility, and converting values to JSON strings. ```javascript json.minify(json) json.escape(value) json.stringify(value) ``` -------------------------------- ### Generate Timestamp (Echolon Script) Source: https://docs.echolon.app/features/scripts Generates a current timestamp and adds it as an 'X-Timestamp' header to the request. It uses the `Date.now()` method for timestamp generation and `toISOString()` for formatting. The timestamp is also logged to the console. ```javascript // Add timestamp to request const timestamp = Date.now(); req.setHeader('X-Timestamp', timestamp.toString()); console.log('Timestamp:', new Date(timestamp).toISOString()); ``` -------------------------------- ### Generate UUID (Echolon Script) Source: https://docs.echolon.app/features/scripts Generates a UUID v4 and sets it as both an environment variable 'requestId' and an 'X-Request-ID' header. This is useful for tracking requests. The generated UUID is also logged to the console. ```javascript // Generate a simple UUID v4 const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => { const r = Math.random() * 16 | 0; const v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); echo.setVar('requestId', uuid); req.setHeader('X-Request-ID', uuid); console.log('Generated UUID:', uuid); ``` -------------------------------- ### Extract Token from Response (Echolon Script) Source: https://docs.echolon.app/features/scripts Extracts an authentication token from the JSON response body and saves it to environment variables using `echo.setEnvVar`. It handles potential JSON parsing errors and looks for tokens named 'token' or 'access_token'. ```javascript // Extract and store auth token from response try { const data = JSON.parse(res.body); if (data.token || data.access_token) { const token = data.token || data.access_token; echo.setEnvVar('auth_token', token); console.log('Token extracted and saved'); } } catch (e) { console.error('Could not parse response:', e.message); } ``` -------------------------------- ### Set Environment Variable (Echolon Script) Source: https://docs.echolon.app/features/scripts Sets an environment variable using the `echo.setEnvVar` function. This is useful for storing configuration values or secrets that can be reused across requests. It takes the variable name and its value as arguments. ```javascript // Set an environment variable echo.setEnvVar('my_env_variable', 'my_env_value'); console.log('Environment variable set: my_env_variable'); ``` -------------------------------- ### Add Timestamp Header in Pre-request Script (JavaScript) Source: https://docs.echolon.app/features/scripts This script adds a timestamp to the 'X-Request-Time' header of an outgoing request. It demonstrates modifying request headers using the `req` object and logging information using `console.log`. ```javascript // Add a timestamp to every request req.setHeader('X-Request-Time', Date.now().toString()); console.log('Request will be sent at:', new Date().toISOString()); ``` -------------------------------- ### Validate Response (Echolon Script) Source: https://docs.echolon.app/features/scripts Validates the response status code and content type. If the status code is 400 or greater, it logs an error. Otherwise, it logs success and checks if the 'content-type' header indicates JSON, logging the number of fields if it is. ```javascript // Validate response status and content if (res.status >= 400) { console.error('Request failed:', res.status, res.statusText); } else { console.log('Request successful'); // Check content type const contentType = res.getHeader('content-type'); if (contentType && contentType.includes('application/json')) { const data = JSON.parse(res.body); console.log('Response contains', Object.keys(data).length, 'fields'); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.