# Changelog Source: https://docs.liteclient.com/community/changelog Recent release highlights for LiteClient This page highlights recent releases. The canonical full changelog lives in the repository at [`CHANGELOG.md`](https://github.com/liteclienthq/liteclient/blob/main/CHANGELOG.md). ## 0.16.0 * Added pre-request and post-response scripting * Added a dedicated tests tab for script results * Added script persistence through Postman import and export ## 0.15.0 * Added response formatting improvements for JSON, HTML, and XML * Added a manual format action in the response toolbar ## 0.14.0 * Added the environment manager panel * Added current-value overrides for environment variables * Added secret-variable masking and related variable actions For the full release history, including older versions and detailed entries, see [`CHANGELOG.md`](https://github.com/liteclienthq/liteclient/blob/main/CHANGELOG.md). # Contributing Guide Source: https://docs.liteclient.com/community/contributing Learn how to contribute to LiteClient This page is a contributor overview. The canonical workflow for contributing to the repository lives in the root [`CONTRIBUTING.md`](https://github.com/liteclienthq/liteclient/blob/main/CONTRIBUTING.md). ## Where to make changes * Update the repository code under `src/` for product changes. * Update `README.md` for repository-level onboarding. * Update `docs/` for end-user documentation published on the docs site. ## For documentation changes If you are editing the docs site: 1. Clone the repository. 2. Install the Mintlify CLI with `npm i -g mint`. 3. Run `mint dev` from the `docs/` directory. 4. Preview the site locally at `http://localhost:3000`. ## Writing guidelines * Use active voice. * Write directly to the reader. * Keep headings in sentence case. * Prefer one clear source of truth over duplicated instructions. For setup, checks, pull requests, and code expectations, use the root [`CONTRIBUTING.md`](https://github.com/liteclienthq/liteclient/blob/main/CONTRIBUTING.md). # Authentication Source: https://docs.liteclient.com/features/authentication Comprehensive authentication support for modern APIs including API keys, tokens, Basic Auth, and OAuth 2.0 LiteClient provides built-in authentication support for the most common API authentication methods. Configure authentication in the Auth tab, and LiteClient automatically applies the necessary headers and credentials. ## API Key Authentication API Key authentication lets you send a custom header or query parameter with your API key. Configure API key in a custom header: In the Auth tab, select **API Key** from the type dropdown. Select **Header** as the placement location. * **Key**: `X-API-Key` (or your API's header name) * **Value**: `{{apiKey}}` (use a variable for security) **Example configuration:** ```text theme={null} Placement: Header Key: X-API-Key Value: {{apiKey}} ``` This sends: `X-API-Key: your-api-key-here` Configure API key as a URL query parameter: In the Auth tab, select **API Key** from the type dropdown. Select **Query Param** as the placement location. * **Key**: `api_key` (or your API's parameter name) * **Value**: `{{apiKey}}` (use a variable for security) **Example configuration:** ```text theme={null} Placement: Query Param Key: api_key Value: {{apiKey}} ``` This appends to your URL: `?api_key=your-api-key-here` Store API keys in environment variables and mark them as `secret` type to mask them in the UI. Never hardcode API keys in requests. ## Bearer Token Authentication Bearer Token authentication is commonly used for JWT-based APIs and OAuth 2.0 access tokens. In the Auth tab, select **Bearer Token** from the type dropdown. Enter your token value. Use a variable like `{{accessToken}}` for flexibility. LiteClient automatically adds the `Authorization: Bearer ` header. **Example configuration:** ```text theme={null} Type: Bearer Token Token: {{accessToken}} ``` **Generated header:** ```http theme={null} Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... ``` Bearer tokens support variable substitution. Store tokens in environment variables so you can use different tokens for local, staging, and production. ## Basic Authentication Basic Auth sends username and password credentials encoded in Base64. In the Auth tab, select **Basic Auth** from the type dropdown. * **Username**: Your username or `{{username}}` variable * **Password**: Your password or `{{password}}` variable LiteClient automatically encodes credentials in Base64 and adds the Authorization header. **Example configuration:** ```text theme={null} Type: Basic Auth Username: {{apiUsername}} Password: {{apiPassword}} ``` **Generated header:** ```http theme={null} Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ= ``` Basic Auth sends credentials with every request. Always use HTTPS to prevent credentials from being intercepted. Consider using environment variables for credentials. ## OAuth 2.0 Authentication LiteClient provides comprehensive OAuth 2.0 support with three grant types and automatic token management. ### Authorization Code Flow Traditional OAuth 2.0 flow with browser-based authentication. In the Auth tab, select **OAuth 2.0** from the type dropdown. Select **Authorization Code** as the grant type. * **Authorization URL**: The provider's authorization endpoint * **Token URL**: The provider's token endpoint * **Client ID**: Your application's client ID * **Client Secret**: Your application's client secret (if required) * **Redirect URI**: `vscode://liteclienthq.liteclient/oauth2/callback` * **Scope**: Space-separated scopes (e.g., `read write`) Click **Get Token** to open the authorization page in your browser. Log in and authorize the application. LiteClient receives the callback and exchanges the code for an access token. The token is cached in VS Code's secure storage and automatically added to requests. **Example configuration:** ```text theme={null} Grant Type: Authorization Code Auth URL: https://provider.com/oauth/authorize Token URL: https://provider.com/oauth/token Client ID: {{clientId}} Client Secret: {{clientSecret}} Redirect URI: vscode://liteclienthq.liteclient/oauth2/callback Scope: read write admin ``` ### Authorization Code with PKCE Enhanced security flow for public clients (recommended for most use cases). In the Auth tab, select **Authorization Code with PKCE** as the grant type. Same configuration as Authorization Code, but Client Secret is optional. Click **Get Token**. LiteClient generates a code verifier and challenge automatically. PKCE protects against authorization code interception attacks. PKCE (Proof Key for Code Exchange) is more secure than standard Authorization Code flow and doesn't require a client secret. Use PKCE when available. ### Client Credentials Flow Machine-to-machine authentication without user interaction. In the Auth tab, select **Client Credentials** as the grant type. * **Token URL**: The provider's token endpoint * **Client ID**: Your application's client ID * **Client Secret**: Your application's client secret * **Scope**: Optional scopes * **Audience**: Optional audience parameter Click **Get Token**. LiteClient requests a token directly from the token endpoint. Ideal for backend services, scheduled tasks, and server-to-server communication. **Example configuration:** ```text theme={null} Grant Type: Client Credentials Token URL: https://provider.com/oauth/token Client ID: {{serviceClientId}} Client Secret: {{serviceClientSecret}} Scope: api.read api.write Audience: https://api.example.com ``` Use environment variables for Client ID and Client Secret to support different OAuth apps across local, staging, and production. ### Token Caching and Refresh LiteClient automatically manages OAuth 2.0 tokens: * **Secure Storage**: Tokens are stored in VS Code's SecretStorage (encrypted) * **Automatic Caching**: Tokens are reused across requests until expiration * **Auto Refresh**: When tokens expire, LiteClient automatically requests a new token using the refresh token (if available) * **Per-Configuration**: Each OAuth 2.0 configuration maintains its own token cache Token refresh happens automatically when you send a request with an expired token. You don't need to manually refresh tokens. ## Using Variables in Authentication All authentication types support variable substitution: ```text theme={null} API Key: {{apiKey}} Bearer Token: {{accessToken}} Username: {{username}} Password: {{password}} Client ID: {{oauthClientId}} Client Secret: {{oauthClientSecret}} ``` This lets you: * Use different credentials per environment * Avoid hardcoding secrets in requests * Share collections without exposing credentials ## Best Practices Store all API keys, tokens, usernames, and passwords in environment variables. Mark them as `secret` type to mask them in the UI. When the API supports it, prefer Authorization Code with PKCE over standard Authorization Code for better security. Create separate environments for local, staging, and production with different API keys and OAuth credentials for each. Use current values for local testing instead of initial values. Current values are never committed to Git. For server-to-server API calls, use Client Credentials flow instead of Authorization Code to avoid interactive login. # Collection Runner Source: https://docs.liteclient.com/features/collection-runner Run all requests in a collection or folder sequentially with variable chaining, scripting, and real-time results The Collection Runner executes all requests in a collection or folder sequentially, running scripts between each request and carrying variables and cookies forward. This is the primary way to automate multi-step API workflows like authentication flows, data seeding, and end-to-end testing. ## Starting a Run You can start a collection run in multiple ways: In the sidebar, click the action menu (⋯) on a collection and select **Run Collection**, or on a folder and select **Run Folder**. Only the requests within that scope are executed. Open the Command Palette (`Cmd/Ctrl+Shift+P`) and run **LiteClient: Run Collection**. Select the collection you want to run. The results panel opens automatically and displays real-time progress as each request completes. Requests are executed in the order they appear in the sidebar. Use drag-and-drop reordering to control execution order. ## Variable Chaining The primary use case for the Collection Runner is **variable chaining** — setting variables in one request's scripts and using them in subsequent requests. Variables set via `pm.environment.set()` or `pm.globals.set()` in a script persist for the remainder of the run. **POST** `{{baseUrl}}/auth/login` Post-response script extracts the token from the response and saves it as an environment variable: ```javascript theme={null} pm.test('Login successful', function() { pm.response.to.have.status(200); const jsonData = pm.response.json(); pm.environment.set('token', jsonData.token); console.log('Token saved for subsequent requests'); }); ``` **GET** `{{baseUrl}}/users/me` Uses the token set by Request 1 in its Authorization header: ``` Authorization: Bearer {{token}} ``` The runner automatically resolves `{{token}}` to the value set by the login script. Order your requests so that authentication and setup requests come first. The runner processes them top-to-bottom, so variables set early are available to all later requests. ## How Scripts Work with the Runner Pre-request and post-response scripts run for every request during a collection run, just as they do for individual requests. * **Pre-request scripts** run before each request is sent — use them to generate timestamps, signatures, or dynamic values * **Post-response scripts** run after each response is received — use them to extract data, set variables, and write assertions * **Variables carry forward** — any variable set in one request's script is available to all subsequent requests in the run * **Test results accumulate** — all `pm.test()` assertions across the run are collected and displayed in the results panel Scripts run in the same sandboxed environment as individual requests. The same 2-second timeout and 100KB size limit apply per script. See [Scripting](/features/scripting) for the full pm API reference. ## Cookie Persistence Cookies set during a collection run carry forward between requests automatically. If a server sets a cookie on the first request (e.g., a session cookie), subsequent requests to the same domain include that cookie — just like a browser would. This is especially useful for workflows that depend on session-based authentication or CSRF tokens. ## Results Panel The results panel provides real-time feedback as the runner executes each request. ### What You'll See * **Progress bar** — tracks how many requests have completed out of the total * **Results table** — each request is listed with its pass/fail status based on script assertions * **Expandable rows** — click a row to view the full response body, headers, test results, and console logs for that request Requests where all `pm.test()` assertions pass are marked with a green checkmark. Requests without any tests are also marked as passed. Requests where one or more `pm.test()` assertions fail are marked with a red indicator. Expand the row to see which assertions failed and why. Use `console.log()` in your scripts to trace variable values and debug issues. All console output is captured and visible in the expandable row for each request. ## History Each request executed by the Collection Runner is saved to your [request history](/features/history). This means you can: * Review the exact request and response for any step in the run * Re-send individual requests from the run * Compare responses across different runs History entries from a collection run are identical to manually executed requests — they include the full request configuration, response body, headers, and timing. ## Best Practices Place setup requests (login, create resources) at the top of your collection. The runner executes top-to-bottom, so dependencies should come first. Add `pm.test()` assertions to validate each step. If a login request fails, the test result makes it immediately clear where the run broke down. Use environment variables like `{{baseUrl}}` so the same collection run works against local, staging, and production servers by switching environments. Design your scripts so they produce the same result regardless of prior state. This makes runs repeatable and easier to debug. # Collections Source: https://docs.liteclient.com/features/collections Organize your API requests in a hierarchical structure that grows with your project Collections help you organize and manage related API requests in a scalable, hierarchical structure. You can create unlimited collections, nest requests inside folders, and share your API definitions with your team. ## Creating Collections You can create a new collection in multiple ways: Click the **New Collection** button (folder icon) at the top of the Collections tab in the sidebar. Open the Command Palette (`Cmd/Ctrl+Shift+P`) and run **LiteClient: New Collection**. Enter a descriptive name that reflects the API or service you're working with (e.g., "GitHub API", "Payment Service"). ## Organizing Requests ### Adding Requests to Collections Once you've created a collection, you can add requests to it: 1. Right-click on a collection in the sidebar 2. Select **Add Request to Collection** 3. Configure your request (URL, method, headers, body, auth) 4. Save the request with a descriptive name ### Nested Folders For larger projects, you can nest requests inside folders for logical organization: * Group endpoints by resource type (e.g., "Users", "Orders", "Products") * Organize by feature or workflow * Create hierarchies that mirror your API structure Collections support unlimited nesting depth, so you can organize requests in whatever structure makes sense for your project. ### Drag-and-Drop Reordering Keep your collections organized by dragging requests and folders to reorder them. This helps you: * Prioritize frequently used requests * Group related endpoints together * Maintain a logical workflow order ## Saving Requests When you save a request to a collection, LiteClient stores the complete configuration: * Request URL with variables * HTTP method (GET, POST, PUT, etc.) * Headers (custom and authentication) * Request body and body type * Authentication settings * Pre-request and post-response scripts After configuring a request: 1. Click the **Save** button in the request editor 2. Choose the target collection 3. Enter a request name 4. The request appears in your collection immediately When you modify a saved request: 1. Make your changes in the editor 2. Click **Save** to update the stored version 3. The unsaved changes indicator (dot) disappears when saved ## Postman Collection Import Migrate from Postman effortlessly with full Collection v2.1 import support. In Postman, right-click your collection and select **Export**. Choose **Collection v2.1** format. In LiteClient, run **LiteClient: Import Collection** from the Command Palette and select your exported JSON file. Your collection appears in the sidebar with all folders, requests, variables, and scripts preserved. Pre-request and test scripts are fully supported during import. Collection-level and folder-level scripts will show a warning as they're not yet supported. ## Exporting Collections Share your API collections with your team by exporting to Postman Collection v2.1 format: 1. Right-click on a collection in the sidebar 2. Select **Export Collection** 3. Choose a save location 4. Share the JSON file via email, Slack, or version control Exported collections include all request configurations and scripts. Review the file before sharing if it contains sensitive data like API keys or tokens. ## Collection Management ### Renaming Collections Right-click on a collection and select **Rename Collection** to update its name. ### Deleting Collections Right-click on a collection and select **Delete Collection**. This action is permanent and removes all requests and folders within the collection. Deleted collections cannot be recovered. Consider exporting important collections before deletion. ## Best Practices Name your collections and requests clearly so team members can understand their purpose at a glance. Use names like "Create User" instead of "POST /users". Mirror your API's structure with folders. For a REST API, create folders for each resource (Users, Posts, Comments) and nest related operations inside. Use variables like `{{baseUrl}}` in your request URLs so collections work seamlessly across local, staging, and production environments. Enable workspace storage and commit your `.liteclient/` folder to Git. This lets your team share collections and track API changes over time. # Cookie Management Source: https://docs.liteclient.com/features/cookies Built-in cookie jar for automatic session management with domain-based storage and persistence LiteClient includes a built-in cookie jar that automatically manages cookies for your API requests. Cookies are sent based on domain matching, persisted across VS Code sessions, and can be managed through a dedicated interface. ## Automatic Cookie Management LiteClient automatically handles cookies without manual configuration: When a server sends a `Set-Cookie` header in the response, LiteClient automatically stores it in the cookie jar. On subsequent requests to the same domain, LiteClient automatically includes relevant cookies in the request headers. Cookies are sent only to matching domains and paths based on the cookie's domain and path attributes. Expired cookies are automatically removed from the jar and not sent with requests. Cookie management is fully automatic. You don't need to manually copy cookies or configure cookie headers. ## Viewing Cookies View cookies in two places: After sending a request, view cookies set by the server in the **Cookies** tab of the response panel: Each cookie displays with: * **Name** - Cookie identifier * **Value** - Cookie content * **Domain** - Cookie scope (e.g., `.example.com`) * **Path** - URL path scope (e.g., `/`, `/api`) * **Expires** - Expiration date and time * **HttpOnly** - Whether JavaScript can access the cookie * **Secure** - Whether the cookie requires HTTPS Open the Cookie Manager to view all stored cookies grouped by domain: Run **LiteClient: Manage Cookies** from the Command Palette, or click the cookie icon in the sidebar. Cookies are organized by domain (e.g., `api.example.com`, `localhost`). Expand each domain to see all cookies with their full metadata. ## Cookie Persistence Cookies are automatically saved and loaded across VS Code sessions: * **Automatic Save** - Cookies are saved to disk immediately when received * **Session Persistence** - Cookies persist when you close and reopen VS Code * **Storage Location** - Cookies are stored in `cookies.json` in your storage directory * **Per-Scope Storage** - Global and workspace storage maintain separate cookie jars Session cookies (cookies without an expiration date) are persisted across VS Code sessions, unlike browser behavior where session cookies are cleared when the browser closes. ## Cookie Attributes LiteClient respects standard cookie attributes: ### Domain Attribute Controls which domains receive the cookie: * **Exact domain** - `domain=api.example.com` matches only `api.example.com` * **Subdomain wildcard** - `domain=.example.com` matches `api.example.com`, `www.example.com`, etc. * **No domain** - Cookie is sent only to the exact origin that set it ### Path Attribute Controls which URL paths receive the cookie: * `path=/` - Cookie sent to all paths * `path=/api` - Cookie sent only to `/api` and its subpaths like `/api/users` * `path=/api/v1` - Cookie sent only to `/api/v1` and deeper paths ### Secure Flag When `Secure` is set: * Cookie is sent only over HTTPS connections * HTTP requests do not receive the cookie * Prevents cookie interception over insecure connections Secure cookies are not sent to `http://` URLs. Use HTTPS in your request URLs to receive secure cookies. ### HttpOnly Flag When `HttpOnly` is set: * Cookie cannot be accessed by JavaScript * Protects against XSS attacks * Automatically respected by LiteClient (no JavaScript access in scripts) ### Expires / Max-Age Controls cookie lifetime: * **Expires** - Absolute expiration date (`Expires=Wed, 21 Oct 2026 07:28:00 GMT`) * **Max-Age** - Relative expiration in seconds (`Max-Age=3600` for 1 hour) * **No expiration** - Session cookie (deleted when browser closes, but persisted by LiteClient) LiteClient uses the `tough-cookie` library for RFC 6265-compliant cookie handling. ## Managing Cookies ### Delete Individual Cookies Remove specific cookies from the jar: Run **LiteClient: Manage Cookies** from the Command Palette. Expand the domain group to find the cookie you want to delete. Click the delete icon next to the cookie to remove it from the jar. ### Delete Domain Cookies Remove all cookies for a specific domain: Run **LiteClient: Manage Cookies** from the Command Palette. Find the domain whose cookies you want to delete. Click the delete icon next to the domain to remove all cookies for that domain. Deleting domain cookies is useful when you want to clear session state for a specific API without affecting other domains. ### Clear All Cookies Remove all cookies from the jar: Run **LiteClient: Clear Cookie Jar** from the Command Palette to delete all cookies immediately. Open the Cookie Manager and click the **Clear All** button to remove all cookies. Clearing all cookies is permanent and cannot be undone. You'll need to re-authenticate with any APIs that rely on cookie-based sessions. ## Cookie-Based Authentication Many APIs use cookies for session management: ### Login Flow Example Send a POST request to the login endpoint with credentials: ```json theme={null} { "username": "user@example.com", "password": "secret" } ``` The server responds with a `Set-Cookie` header: ``` Set-Cookie: session=abc123; Path=/; HttpOnly; Secure ``` LiteClient stores the session cookie in the cookie jar. All future requests to the same domain automatically include the session cookie: ``` Cookie: session=abc123 ``` The server recognizes the session and grants access to protected resources. You don't need to manually copy or set cookies. LiteClient handles the entire cookie lifecycle automatically. ## Cookie Storage Scope Cookies are stored according to your active storage scope: When using global storage (default): * Cookies are stored in VS Code's global storage * Available across all workspaces * Private to your machine * Not shared via Git When using workspace storage: * Cookies are stored in `.liteclient/cookies.json` * Workspace-specific * Can be shared via version control (not recommended for sensitive cookies) * Useful for testing with shared session state Be careful when committing workspace storage to Git. The `cookies.json` file may contain sensitive session tokens. Consider adding it to `.gitignore`. ## Debugging Cookie Issues ### Cookie Not Being Sent If a cookie isn't being sent with requests: 1. **Check domain matching** - Verify the request URL matches the cookie's domain 2. **Check path matching** - Ensure the request path matches the cookie's path 3. **Check expiration** - Verify the cookie hasn't expired 4. **Check Secure flag** - Use HTTPS if the cookie has the Secure flag 5. **Review cookie jar** - Open the Cookie Manager to verify the cookie is stored ### Cookie Not Being Stored If a cookie isn't appearing in the jar: 1. **Check response headers** - Verify the server sent a `Set-Cookie` header 2. **Check cookie format** - Ensure the `Set-Cookie` header is valid 3. **Check domain attribute** - Verify the domain matches the request origin 4. **Review response** - Look for cookie-related errors in the response Use the Response Headers tab to view the exact `Set-Cookie` header sent by the server. This helps diagnose why a cookie might not be stored. ## Best Practices Always use HTTPS when working with authentication cookies. This prevents cookie interception and ensures Secure cookies are sent. When testing with multiple user accounts, clear cookies between tests to avoid session conflicts. Open the Cookie Manager regularly to review stored cookies and delete expired or unnecessary entries. Use global storage for personal testing and workspace storage for team-shared test sessions (with caution). If you encounter authentication errors, check if your session cookie has expired. Re-login to obtain a fresh cookie. # Environments Source: https://docs.liteclient.com/features/environments Manage different configurations for local, staging, and production environments with structured variables Environments let you manage different configurations for local development, staging, and production without changing your requests. You can define variables, switch between environments instantly, and maintain separate settings for each context. ## Creating Environments Create named environments to organize your variables: Click the **New Environment** button in the Environments tab of the sidebar, or run **LiteClient: New Environment** from the Command Palette. Choose a descriptive name like "Local", "Staging", or "Production". Define variables specific to this environment (e.g., `baseUrl`, `apiKey`). ## Variable Structure Environment variables use a structured format with multiple properties: * **Name** - The variable identifier used in `{{variableName}}` syntax * **Initial Value** - The default value stored in your environment file * **Current Value** - Optional workspace-local override (never committed to Git) * **Type** - Either `default` or `secret` (secrets are masked in the UI) * **Enabled** - Toggle to enable/disable individual variables Current values are stored in VS Code's workspace state and override initial values during request execution. This lets you test with different values without modifying your saved environment. ## Global Variables Global variables are available across all environments and collections. Use them for values that remain constant regardless of environment: * API version numbers * Common headers * Organization IDs * Default timeouts 1. Open the **Globals** environment in the sidebar 2. Click **Add Variable** 3. Enter name and initial value 4. The variable is immediately available in all requests Reference global variables using the same `{{variableName}}` syntax: ```text theme={null} {{baseUrl}}/api/{{apiVersion}}/users ``` ## Variable Resolution LiteClient resolves variables using a layered precedence system. Variables from narrower scopes override broader scopes: **Resolution Order:** 1. **Environment variables** (highest priority) 2. **Collection variables** 3. **Global variables** (lowest priority) Only enabled variables are resolved. Disabled variables are skipped during resolution. ### Resolution Example If you have: * Global variable: `baseUrl = https://api.example.com` * Environment variable: `baseUrl = http://localhost:3000` When you select that environment, `{{baseUrl}}` resolves to `http://localhost:3000`. ## Using Variables Variables work everywhere in your requests: ### URL ```text theme={null} {{baseUrl}}/api/users/{{userId}} ``` ### Headers ```http theme={null} Authorization: Bearer {{authToken}} X-API-Key: {{apiKey}} ``` ### Request Body ```json theme={null} { "apiKey": "{{apiKey}}", "environment": "{{env}}" } ``` ### Authentication Use variables in API Key, Bearer Token, Basic Auth, and OAuth 2.0 configurations. ## Variable Autocomplete Type `{{` in any input field to trigger autocomplete. You'll see all available variables from globals, collections, and the active environment: Type `{{` in the URL bar, header value, or body editor. Use arrow keys to navigate through available variables. Press Enter to insert the selected variable. Autocomplete shows the current value of each variable, making it easy to verify you're using the right one. ## Switching Environments Quickly switch between environments via the sidebar: 1. Click the environment dropdown in the Environments tab 2. Select your target environment 3. All requests immediately use the new environment's variables The active environment applies to all open request tabs. You don't need to reload or reconfigure anything. ## Environment Manager Open the full Environment Manager panel for advanced editing: Run **LiteClient: Manage Environments** to open the manager in a dedicated panel. Click the **Manage** action on any environment in the sidebar. The Environment Manager provides: * Table view of all variables * Inline editing of name, initial value, current value, type, and enabled state * Bulk operations on multiple variables * Password-style input for secret variables ## Secret Variables Protect sensitive values by marking variables as `secret`: * Secret values display as `••••••••` in the sidebar and autocomplete * Current value inputs use password fields * Secret variables are still stored in plaintext in environment files Secret variables provide UI masking but are not encrypted in storage. Never commit sensitive credentials to version control. Use current values for local testing instead. ## Current Value Overrides Set workspace-local current values that override initial values without modifying your environment file: Right-click a variable in the sidebar and select **Set Current Value**. Enter the override value. Requests automatically use the current value when present. Right-click the variable and select **Clear Current Value** to revert to the initial value. Current values are perfect for testing with temporary API keys or local database URLs without polluting your shared environment files. ## Legacy Format Migration Environments using the legacy key-value format are automatically migrated to the new structured format when loaded. Your existing environments will continue to work seamlessly. ## Best Practices Define variables that change between environments: `baseUrl`, `apiKey`, `databaseUrl`. Keep constants in global variables. Use the same variable names across all environments (e.g., `baseUrl` in Local, Staging, and Production). This ensures requests work in any environment. Mark API keys, tokens, and passwords as secret to prevent accidental exposure in screenshots or screen shares. Test with temporary credentials using current values instead of modifying initial values. This prevents accidental commits of test credentials. # Request History Source: https://docs.liteclient.com/features/history Never lose track of what you've tried with automatic request history tracking and organization LiteClient automatically records every request you send, organizing them by date for easy access. You can replay historical requests, review execution details, and manage your request history. ## Automatic History Recording Every time you send a request, LiteClient automatically saves it to your history with complete details: * Request method and URL * Execution timestamp * Response status code * Execution duration * Full request configuration (headers, body, auth) History is recorded regardless of whether the request succeeds or fails. This helps you debug issues by reviewing failed requests. ## Viewing History Access your request history from the LiteClient sidebar: Click the **History** tab in the LiteClient sidebar. Requests are organized into groups: Today, Yesterday, Last Week, etc. Each history item shows: * HTTP method (GET, POST, etc.) * Request URL * Execution duration in milliseconds * Timestamp ## Day-Grouped Organization History items are automatically organized into date groups for easy navigation: All requests sent today appear in the "Today" group at the top of the history list. Requests from yesterday are grouped separately for quick access to recent work. Older requests are grouped by week, making it easy to find requests from recent days. Requests older than one week are grouped together in an "Older" section. Date grouping helps you quickly locate recent requests without scrolling through a long list. Use the groups to navigate to specific time periods. ## Replaying Requests Replay any historical request to re-execute it with the same configuration: Browse your history and locate the request you want to replay. Click the history item to open it in a new request editor panel. The request opens with the same URL, method, headers, body, and auth settings. Make any changes to the request configuration before resending. Click **Send** to re-execute the request with the current configuration. When you replay a request, variables are resolved using current environment values, not the values from when the request was originally sent. ## Request Details Each history item captures the complete request configuration: ### What's Recorded * **URL** - Full request URL with query parameters * **Method** - HTTP method (GET, POST, PUT, etc.) * **Headers** - All request headers including authentication * **Body** - Request body content and type * **Auth** - Authentication configuration * **Duration** - Execution time in milliseconds * **Timestamp** - When the request was sent * **Status** - Response status code (if received) ### What's Not Recorded * Response body content (only status is saved) * Response headers * Cookies * Test results History items are lightweight to keep storage efficient. To preserve full response details, save important requests to collections. ## Managing History ### Delete Individual Items Remove specific requests from your history: Find the history item you want to delete. Right-click on the history item to open the context menu. Choose **Delete** from the menu to remove the item. ### Bulk Delete by Day Delete all requests from a specific day or date group: 1. Right-click on a date group header (e.g., "Today", "Yesterday") 2. Select **Delete All** to remove all requests from that group 3. Confirm the deletion Bulk delete is permanent and cannot be undone. Consider exporting important requests to collections before bulk deletion. ### Clear All History Remove all history items at once: Navigate to the History tab in the sidebar. Click the **Clear History** button in the tab toolbar (trash icon). Confirm that you want to clear all history. This action is permanent. Clearing history is permanent and cannot be undone. All historical requests will be deleted. ## History Storage History is stored according to your storage scope setting: When using global storage (default), history is saved in VS Code's global storage directory. This keeps history: * Private to your VS Code installation * Available across all workspaces * Not shared via Git When using workspace storage, history is saved in the `.liteclient/` folder in your project root. This: * Stores history in your workspace * Can be shared via version control * Is workspace-specific Switch storage scopes by clicking the **LiteClient: Global/Workspace** indicator in the VS Code status bar. See the Storage documentation for details. ## History Limits To keep storage efficient, LiteClient automatically manages history size: * No hard limit on number of items * Older items are eventually pruned to prevent unbounded growth * Recent requests are always preserved If your history becomes too large, use the Clear All option to reset it. Save important requests to collections before clearing. ## Using History Effectively ### Debugging Failed Requests When a request fails: 1. Open the history item to review the exact configuration 2. Check the URL, headers, and body for errors 3. Modify and resend to test fixes 4. Save the working version to a collection ### Tracking API Changes Use history to track API behavior over time: * Compare request durations to identify performance changes * Review status codes to detect API availability issues * Replay old requests to verify backward compatibility ### Repeating Workflows For multi-step workflows: 1. Execute each request in sequence 2. Review history to verify all steps completed 3. Replay failed steps as needed 4. Save the complete workflow to a collection for future use ## Best Practices History is temporary and may be cleared. Save requests you'll reuse to collections so they're preserved permanently. Periodically review your history to identify patterns, debug issues, and find requests worth saving to collections. When debugging, check history to compare working and failing requests. Look for differences in headers, parameters, or body content. Keep your history manageable by clearing old items. Use bulk delete to remove requests from specific time periods. History is personal and not shared with your team. Use collections and workspace storage for team collaboration. # HTTP Requests Source: https://docs.liteclient.com/features/requests Build precise HTTP requests with a familiar interface, supporting all major methods and content types LiteClient provides a comprehensive interface for building HTTP requests with full control over methods, URLs, parameters, headers, and body content. ## Request Methods LiteClient supports all standard HTTP methods: * **GET** - Retrieve resources * **POST** - Create new resources * **PUT** - Replace existing resources * **PATCH** - Partially update resources * **DELETE** - Remove resources * **HEAD** - Retrieve headers only * **OPTIONS** - Query supported methods Select your method from the dropdown next to the URL bar. ## URL & Query Parameters ### URL Input Enter your full URL in the URL bar. The URL supports variable substitution using the `{{variableName}}` syntax: ```text theme={null} {{baseUrl}}/api/v1/users/{{userId}} ``` Type `{{` to trigger autocomplete and see all available variables from your global, collection, and environment scopes. ### Query Parameters Editor Manage query parameters with a dedicated key-value editor: Click **Add Parameter** to create a new query parameter row. Type the parameter name and value. Both support variable substitution. Use the checkbox to enable or disable individual parameters without deleting them. **Example:** ```text theme={null} Key: page Value: 1 Key: limit Value: {{pageSize}} Key: sort Value: created_at ``` This generates: `?page=1&limit=50&sort=created_at` Dollar-prefixed query keys are kept literal for APIs such as OData, so a key like `$filter` is sent as `$filter` rather than `%24filter`. Query values continue to use standard URL encoding. ## Headers Customize request headers with full control over keys and values. ### Adding Headers 1. Navigate to the **Headers** tab 2. Click **Add Header** 3. Enter the header key and value 4. Both key and value support variable substitution Use the checkbox next to each header to temporarily disable it without deleting. This is useful for: * Testing with and without authentication * Debugging header-related issues * A/B testing different header values ### Common Headers Example ```http theme={null} Content-Type: application/json Accept: application/json X-API-Key: {{apiKey}} User-Agent: LiteClient/1.0 ``` Authentication headers (like `Authorization`) can be set automatically using the Auth tab. See the [Authentication](/features/authentication) page for details. ## Request Body Configure request bodies with multiple content types: ### No Body Select **No Body** for GET and HEAD requests that don't send a request body. ### Raw Body The raw body editor supports multiple content types with syntax highlighting: ```json theme={null} { "name": "{{userName}}", "email": "user@example.com", "role": "admin" } ``` Includes automatic syntax highlighting and validation. ```xml theme={null} {{userName}} user@example.com ``` ```html theme={null}

{{title}}

{{content}}

```
```javascript theme={null} const data = { apiKey: "{{apiKey}}", timestamp: Date.now() }; ``` ```text theme={null} Simple text content with {{variables}} ```
### Form Data Upload files and send multipart form data: Choose **Form Data** from the body type dropdown. Add key-value pairs for text fields and file uploads. Click the file icon next to a field to select a file for upload (25MB limit). **Example use case:** ```text theme={null} Key: title Value: Profile Picture Key: image Value: [Select File: avatar.jpg] Key: category Value: {{imageCategory}} ``` Form-data file uploads have a 25MB size limit. For larger files, consider using a dedicated file upload API. ### URL-Encoded Form Data Send form data as `application/x-www-form-urlencoded`: ```text theme={null} Key: username Value: {{userName}} Key: password Value: {{userPassword}} Key: remember Value: true ``` This sends: `username=john&password=secret&remember=true` ## Variable Substitution Variables work in all body types: * **Raw JSON/XML/HTML** - Use `{{variableName}}` anywhere in the content * **Form Data** - Both keys and values support variables * **URL-Encoded** - Keys and values support variables Variable resolution follows the layered precedence: Environment → Collection → Global. Only enabled variables are resolved. ## Sending Requests Once you've configured your request: Click the **Send** button in the URL bar to execute the request. The response appears in the bottom panel with status, headers, body, and cookies. Click **Cancel** during long-running operations to abort the request. ## Request Execution Flow When you send a request, LiteClient: 1. Runs pre-request scripts (if configured) 2. Resolves all variables (globals → collection → environment) 3. Substitutes variables in URL, headers, body, and auth 4. Sends relevant cookies based on domain 5. Executes the HTTP request 6. Captures the response 7. Runs post-response scripts (if configured) 8. Records the request in history Pre-request and post-response scripts can modify variables and perform assertions. See the [Scripting](/features/scripting) page for details. ## Multi-Tab Editing Work on multiple requests simultaneously: * Open multiple request panels at once * Drag tabs to reorder * Unsaved changes indicator (dot) shows when modifications haven't been saved * Each tab maintains independent state Save frequently used requests to collections so you can quickly open them later from the sidebar. ## Best Practices Replace hardcoded values like API keys, user IDs, and base URLs with variables. This makes requests reusable across environments. Use the enable/disable toggle for headers and parameters instead of deleting them. This preserves your configuration for future testing. When saving requests to collections, use clear names that describe what the request does: "Create User", "Get Order by ID", "Delete Product". Some APIs accept multiple content types. Save separate requests for JSON and XML variants to test both formats. # Response Analysis Source: https://docs.liteclient.com/features/responses View API responses with rich formatting, syntax highlighting, and detailed metadata LiteClient provides comprehensive response analysis with syntax-highlighted body content, detailed headers, cookies, status information, and execution timing. ## Response Body View response bodies with automatic formatting and syntax highlighting. ### Automatic Language Detection LiteClient automatically detects the response content type and applies appropriate syntax highlighting: JSON responses are automatically pretty-printed with syntax highlighting: ```json theme={null} { "id": 123, "name": "John Doe", "email": "john@example.com", "roles": ["admin", "user"] } ``` * Proper indentation for readability * Color-coded keys, strings, numbers, and booleans * Collapsible nested objects and arrays XML and HTML responses are formatted with proper indentation: ```xml theme={null} 123 John Doe john@example.com ``` HTML responses display with syntax highlighting: ```html theme={null} API Response

Success

```
JavaScript responses include syntax highlighting for code: ```javascript theme={null} function callback(data) { console.log(data); return data.results; } ``` Plain text responses display without formatting: ```text theme={null} Simple text response content ```
### Manual Formatting Use the **Format** button in the response toolbar to manually trigger formatting: After sending a request, the response appears in the bottom panel. If the automatic formatting doesn't trigger, click the **Format** button in the toolbar. The response is re-formatted with proper indentation and syntax highlighting. Manual formatting is useful when the automatic detection doesn't recognize the content type correctly, or when you want to re-format minified responses. ## Response Status The response status bar displays key information about the request execution: ### Status Code and Text * **2xx Success** - Green indicator (e.g., `200 OK`, `201 Created`) * **3xx Redirection** - Blue indicator (e.g., `301 Moved Permanently`, `302 Found`) * **4xx Client Error** - Orange indicator (e.g., `400 Bad Request`, `404 Not Found`) * **5xx Server Error** - Red indicator (e.g., `500 Internal Server Error`, `503 Service Unavailable`) ### Execution Timing The status bar shows the total request duration in milliseconds: ```text theme={null} 200 OK • 342ms ``` This includes: * DNS resolution * TCP connection * TLS handshake (for HTTPS) * Request transmission * Server processing * Response download Use execution timing to identify slow endpoints and optimize API performance. Compare times across environments to detect infrastructure issues. ## Response Headers View all response headers in a dedicated tab: After receiving a response, click the **Headers** tab in the response section. All headers are displayed in key-value format with proper formatting. Common headers to review: * `Content-Type` - Response format * `Content-Length` - Response size * `Cache-Control` - Caching directives * `Set-Cookie` - Cookie instructions * `Authorization` - Auth requirements **Example headers:** ```http theme={null} Content-Type: application/json; charset=utf-8 Content-Length: 1247 Cache-Control: no-cache, private X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 Set-Cookie: session=abc123; Path=/; HttpOnly ``` ## Response Cookies View cookies set by the server in the Cookies tab: Each cookie displays with full metadata: * **Name** - Cookie identifier * **Value** - Cookie content * **Domain** - Cookie scope * **Path** - URL path scope * **Expires** - Expiration timestamp * **HttpOnly** - JavaScript access restriction * **Secure** - HTTPS-only flag LiteClient automatically: * Stores cookies in the cookie jar * Sends relevant cookies on subsequent requests * Respects domain and path restrictions * Handles cookie expiration Cookies are automatically sent on matching requests based on domain and path. See the [Cookie Management](/features/cookies) page for details. ## Test Results When you use post-response scripts with tests, results appear in the Tests tab: Send a request that includes post-response test scripts. Click the **Tests** tab to see pass/fail results for each test. Console logs from scripts (`console.log`, `console.warn`, etc.) appear in the test results. Failed tests show the assertion error with line numbers for easy debugging. **Example test results:** ```text theme={null} ✓ Status code is 200 ✓ Response time is less than 500ms ✗ Response has user ID AssertionError: expected undefined to exist at test script:3 Console Output: [INFO] Request completed successfully [WARN] Deprecated field detected: user.legacy_id ``` Test scripts use the Postman-compatible `pm` API. See the [Scripting](/features/scripting) page for details on writing tests. ## Request Cancellation Cancel long-running requests before they complete: Click Send to execute a request. If the request is taking too long, click the **Cancel** button that appears during execution. The request is immediately cancelled, and no response is recorded in history. Cancelling a request doesn't guarantee the server hasn't processed it. For write operations (POST, PUT, DELETE), check the server state to confirm the operation was aborted. ## Error Responses When a request fails, LiteClient provides detailed error information: ### Network Errors ```text theme={null} Error: connect ECONNREFUSED 127.0.0.1:3000 ``` Common network errors: * `ECONNREFUSED` - Server not running or port closed * `ETIMEDOUT` - Request timeout (server took too long) * `ENOTFOUND` - DNS lookup failed (invalid domain) * `ECONNRESET` - Connection reset by server ### HTTP Errors 4xx and 5xx responses display the error status and body: ```json theme={null} 400 Bad Request • 123ms Body: { "error": "Invalid request parameters", "details": { "field": "email", "issue": "Email format is invalid" } } ``` Always check both the status code and response body for error details. Many APIs provide structured error messages with actionable information. ## Best Practices Always review the status code before analyzing the response body. A 200 OK means success, while 4xx and 5xx indicate errors that need investigation. Track execution times to identify slow endpoints. Consistently slow responses (>1000ms) may indicate performance issues or inefficient queries. Headers contain valuable debugging information like rate limits, cache directives, and CORS settings. Check headers when troubleshooting issues. Write post-response scripts to automatically validate status codes, response structure, and data integrity. This catches regressions early. When debugging, save requests that produce errors to collections so you can easily reproduce and share the issue with your team. # Scripting Source: https://docs.liteclient.com/features/scripting Automate your workflow with pre-request and post-response scripts using the Postman-compatible pm API LiteClient supports JavaScript scripting to automate API workflows. Write pre-request scripts to set variables or generate tokens before requests are sent, and post-response scripts to validate responses and extract data. ## Script Types LiteClient provides two types of scripts: Pre-request scripts run **before** the request is sent. Use them to: * Set environment variables dynamically * Generate authentication tokens or signatures * Modify request state * Log pre-request information **Example:** ```javascript theme={null} // Set a timestamp variable pm.environment.set('timestamp', Date.now()); // Generate a random request ID pm.environment.set('requestId', Math.random().toString(36).substring(7)); console.log('Request ID:', pm.variables.get('requestId')); ``` Post-response scripts run **after** the response is received. Use them to: * Write assertions and tests * Extract data from responses * Set variables based on response data * Log response information **Example:** ```javascript theme={null} // Test status code pm.test('Status code is 200', function() { pm.response.to.have.status(200); }); // Extract token from response const jsonData = pm.response.json(); pm.environment.set('authToken', jsonData.token); console.log('Token saved:', jsonData.token); ``` ## The pm API LiteClient provides a Postman-compatible `pm` API for interacting with environments, globals, requests, and responses. ### pm.environment Manage environment variables: ```javascript theme={null} // Get a variable const baseUrl = pm.environment.get('baseUrl'); // Set a variable pm.environment.set('userId', '12345'); // Check if variable exists if (pm.environment.has('apiKey')) { console.log('API key is configured'); } // Unset a variable pm.environment.unset('tempValue'); ``` Variables set via `pm.environment.set()` are automatically persisted to the active environment. New variables are created if they don't exist. ### pm.globals Manage global variables (available across all environments): ```javascript theme={null} // Get a global variable const apiVersion = pm.globals.get('apiVersion'); // Set a global variable pm.globals.set('lastRequestTime', Date.now()); // Check if global exists if (pm.globals.has('orgId')) { console.log('Organization ID is set globally'); } // Unset a global variable pm.globals.unset('tempGlobal'); ``` ### pm.variables Access variables from all scopes with automatic resolution: ```javascript theme={null} // Get variable (resolves Environment → Collection → Global) const baseUrl = pm.variables.get('baseUrl'); // Set variable in current environment pm.variables.set('requestCount', 42); ``` `pm.variables.get()` follows the layered resolution order: Environment → Collection → Global. The narrowest scope wins. ### pm.request Access request metadata (available in both pre-request and post-response scripts): ```javascript theme={null} // Get request URL const url = pm.request.url.toString(); console.log('Request URL:', url); // Get request method const method = pm.request.method; console.log('Method:', method); // Access headers const headers = pm.request.headers; console.log('Content-Type:', headers.get('Content-Type')); ``` ### pm.response Access response data (only available in post-response scripts): ```javascript theme={null} // Get status code const status = pm.response.code; console.log('Status:', status); // Get response time const time = pm.response.responseTime; console.log('Response time:', time, 'ms'); // Parse JSON response const jsonData = pm.response.json(); console.log('User ID:', jsonData.id); // Get response body as text const bodyText = pm.response.text(); // Access response headers const contentType = pm.response.headers.get('Content-Type'); ``` ### pm.test() Write assertions and tests: ```javascript theme={null} // Basic assertion pm.test('Status code is 200', function() { pm.response.to.have.status(200); }); // Multiple assertions pm.test('Response is valid', function() { pm.response.to.be.ok; pm.response.to.be.json; pm.response.to.have.header('Content-Type', /json/); }); // Test response body pm.test('Response has user data', function() { const jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('id'); pm.expect(jsonData.name).to.be.a('string'); pm.expect(jsonData.email).to.include('@'); }); ``` ### pm.expect() ChaiJS-style assertions: ```javascript theme={null} // Number assertions pm.expect(pm.response.code).to.equal(200); pm.expect(pm.response.responseTime).to.be.below(500); // String assertions const jsonData = pm.response.json(); pm.expect(jsonData.name).to.be.a('string'); pm.expect(jsonData.email).to.include('@example.com'); // Object assertions pm.expect(jsonData).to.have.property('id'); pm.expect(jsonData.roles).to.be.an('array'); pm.expect(jsonData.roles).to.include('admin'); // Boolean assertions pm.expect(jsonData.active).to.be.true; ``` ### pm.sendRequest() Make HTTP requests from within scripts. This enables token fetching, dynamic lookups, and multi-step API workflows: ```javascript theme={null} // Simple GET request pm.sendRequest('https://api.example.com/health', function (err, res) { console.log('Health check status:', res.code); }); // POST request with headers and body pm.sendRequest({ url: 'https://api.example.com/auth/token', method: 'POST', header: { 'Content-Type': 'application/json' }, body: { raw: JSON.stringify({ client_id: pm.environment.get('clientId'), grant_type: 'client_credentials' }) } }, function (err, res) { if (!err) { const token = res.json().access_token; pm.environment.set('authToken', token); console.log('Token acquired'); } }); ``` `pm.sendRequest()` is limited to 5 calls per script execution and shares the 10-second script timeout. The callback receives `(error, response)` where `response` has `.code`, `.status`, `.headers`, `.json()`, and `.text()` methods. ## Console Logging Use standard console methods for debugging: ```javascript theme={null} // Info logging console.log('Request started'); console.info('Using environment:', pm.environment.name); // Warning logging console.warn('Deprecated API version detected'); // Error logging console.error('Authentication failed'); // Log objects const user = { id: 123, name: 'John' }; console.log('User data:', user); ``` Console output appears in the Tests tab after request execution. Output is capped at 200 entries per script. ## Script Examples ### Pre-Request Script Examples ```javascript theme={null} // Generate timestamp const timestamp = Date.now(); pm.environment.set('timestamp', timestamp); // Create signature (pseudo-code - use crypto library in real implementation) const message = pm.request.method + pm.request.url + timestamp; const signature = generateHMAC(message, pm.environment.get('secretKey')); pm.environment.set('signature', signature); console.log('Signature generated for timestamp:', timestamp); ``` ```javascript theme={null} // Set request ID header const requestId = Math.random().toString(36).substring(7); pm.environment.set('requestId', requestId); // Set timestamp pm.environment.set('timestamp', new Date().toISOString()); console.log('Request ID:', requestId); ``` ```javascript theme={null} // Set different base URLs based on time const hour = new Date().getHours(); if (hour >= 9 && hour < 17) { pm.environment.set('baseUrl', 'https://api.example.com'); } else { pm.environment.set('baseUrl', 'https://api-night.example.com'); } console.log('Using base URL:', pm.environment.get('baseUrl')); ``` ### Post-Response Script Examples ```javascript theme={null} pm.test('Login successful', function() { pm.response.to.have.status(200); const jsonData = pm.response.json(); pm.expect(jsonData).to.have.property('token'); // Save token for future requests pm.environment.set('authToken', jsonData.token); console.log('Auth token saved'); }); ``` ```javascript theme={null} pm.test('Response structure is valid', function() { const jsonData = pm.response.json(); // Check required fields pm.expect(jsonData).to.have.property('id'); pm.expect(jsonData).to.have.property('name'); pm.expect(jsonData).to.have.property('email'); // Validate types pm.expect(jsonData.id).to.be.a('number'); pm.expect(jsonData.name).to.be.a('string'); pm.expect(jsonData.email).to.match(/^[^@]+@[^@]+\.[^@]+$/); }); ``` ```javascript theme={null} pm.test('Response time is acceptable', function() { pm.expect(pm.response.responseTime).to.be.below(500); }); pm.test('Response size is reasonable', function() { const bodySize = pm.response.text().length; pm.expect(bodySize).to.be.below(100000); // 100KB }); console.log('Response time:', pm.response.responseTime, 'ms'); console.log('Response size:', pm.response.text().length, 'bytes'); ``` ```javascript theme={null} pm.test('User created successfully', function() { pm.response.to.have.status(201); const jsonData = pm.response.json(); // Save user ID for next request pm.environment.set('userId', jsonData.id); console.log('User created with ID:', jsonData.id); console.log('Use {{userId}} in the next request'); }); ``` ```javascript theme={null} // Fetch a token, then verify the user with a follow-up call const userId = pm.response.json().id; pm.sendRequest({ url: 'https://api.example.com/users/' + userId, method: 'GET', header: { 'Authorization': 'Bearer ' + pm.environment.get('authToken') } }, function (err, res) { pm.test('Follow-up GET returns the created user', function () { pm.expect(res.code).to.equal(200); pm.expect(res.json().id).to.equal(userId); }); }); ``` ## Script Execution ### Sandboxed Environment Scripts run in a Node.js VM sandbox with the following constraints: * **10-second timeout** - Scripts that exceed 10 seconds are automatically terminated * **100KB size limit** - Scripts larger than 100KB are rejected * **200 console entries** - Console output is capped at 200 entries * **200 test results** - Test results are capped at 200 tests * **5 `pm.sendRequest()` calls** - HTTP requests from scripts are capped at 5 per execution Scripts have no access to the file system or VS Code APIs. Network access is available only via `pm.sendRequest()`. They run in an isolated environment for security. ### Error Handling When scripts fail, errors are displayed in the Tests tab with line numbers: ```text theme={null} [ERROR] Script execution failed at line 5 ReferenceError: undefinedVariable is not defined at test script:5 ``` Use try-catch blocks in complex scripts to handle errors gracefully and provide meaningful error messages. ## Postman Import/Export Scripts are fully preserved when importing and exporting Postman Collection v2.1 files: * Pre-request scripts are imported as-is * Test scripts are imported as post-response scripts * Collection-level and folder-level scripts show a warning (not yet supported) LiteClient currently supports request-level scripts only. Collection-level and folder-level scripts from Postman collections are not executed. ## Best Practices Write concise scripts that do one thing well. Complex logic is harder to debug and maintain. Break large workflows into multiple requests. Name tests clearly so failures are easy to understand: "Status code is 200", "Response contains user ID", "Email format is valid". Use `console.log()` to track variable changes, token generation, and workflow progress. This helps with debugging. Check if properties exist before accessing them to avoid script errors: ```javascript theme={null} const data = pm.response.json(); if (data && data.token) { pm.environment.set('token', data.token); } ``` Extract tokens, IDs, and other dynamic values into variables so subsequent requests can use them. This enables request chaining. # OAuth 2.0 Setup Source: https://docs.liteclient.com/guides/oauth Configure OAuth 2.0 authentication with LiteClient for Authorization Code, PKCE, and Client Credentials flows ## Overview LiteClient supports OAuth 2.0 authentication with three grant types. Tokens are automatically acquired, cached in VS Code's SecretStorage, and injected into requests. OAuth endpoints, client credentials, scopes, and audience support `{{variableName}}` substitution with the standard precedence: Globals → Collection → selected Environment. ## Supported Grant Types LiteClient supports three OAuth 2.0 flows: Traditional flow requiring user login via browser Enhanced security for public clients without client secret Machine-to-machine authentication with direct token exchange ## Authorization Code Flow Use this flow when your application needs to authenticate on behalf of a user. Open a request panel and click the **Auth** tab Select **OAuth 2.0** from the authentication type dropdown Select **Authorization Code** as the grant type Enter the following URLs: * **Authorization URL**: The endpoint where users log in * **Token URL**: The endpoint that exchanges the code for a token Provide: * **Client ID**: Your application's client identifier * **Client Secret**: Your application's secret key Enter required scopes separated by spaces (e.g., `read:user write:repo`) Click **Get Access Token**. LiteClient will: 1. Open your default browser 2. Navigate to the authorization URL 3. Wait for you to log in and authorize 4. Receive the callback with authorization code 5. Exchange the code for an access token The token is automatically saved and injected in the `Authorization` header for all requests using this auth configuration LiteClient handles the OAuth callback by registering a URI handler in VS Code. ## Authorization Code with PKCE PKCE (Proof Key for Code Exchange) provides enhanced security for public clients that cannot securely store a client secret. Open a request panel and click the **Auth** tab Select **OAuth 2.0** from the authentication type dropdown Select **Authorization Code (PKCE)** as the grant type Enter: * **Authorization URL**: The authorization endpoint * **Token URL**: The token exchange endpoint Provide your **Client ID** (no client secret needed) Enter required scopes if your API requires them Click **Get Access Token**. LiteClient will: 1. Generate a code verifier and challenge 2. Open browser to authorization URL with PKCE parameters 3. Receive authorization code callback 4. Exchange code + verifier for access token PKCE is recommended for single-page applications and mobile apps where client secrets cannot be safely stored. ## Client Credentials Flow Use this flow for server-to-server authentication without user interaction. Open a request panel and click the **Auth** tab Select **OAuth 2.0** from the authentication type dropdown Select **Client Credentials** as the grant type Enter the **Token URL** (authorization URL not needed for this flow) Provide: * **Client ID**: Your application identifier * **Client Secret**: Your application secret Enter required scopes for your API Click **Get Access Token**. The token is acquired directly without browser interaction Client Credentials tokens represent the application itself, not a user. Ensure your API supports this flow. ## Token Management ### Token Storage LiteClient stores OAuth tokens securely: * Tokens are saved in **VS Code's SecretStorage** * Tokens persist across VS Code sessions * Tokens are encrypted and never exposed in plain text ### Token Refresh LiteClient automatically refreshes expired tokens when possible. If refresh fails, re-authenticate via the Auth tab. ### Manual Re-authentication If your token expires or becomes invalid: 1. Open the request's **Auth** tab 2. Verify the OAuth configuration (URLs, Client ID, Secret) 3. Click **Get Access Token** to acquire a new token ## Common OAuth Providers Configuration examples for popular OAuth providers: * **Authorization URL**: `https://github.com/login/oauth/authorize` * **Token URL**: `https://github.com/login/oauth/access_token` * **Grant Type**: Authorization Code or PKCE * **Scopes**: `repo`, `user`, `read:org`, etc. * **Authorization URL**: `https://accounts.google.com/o/oauth2/v2/auth` * **Token URL**: `https://oauth2.googleapis.com/token` * **Grant Type**: Authorization Code or PKCE * **Scopes**: `https://www.googleapis.com/auth/userinfo.email`, etc. * **Authorization URL**: `https://login.microsoftonline.com/common/oauth2/v2.0/authorize` * **Token URL**: `https://login.microsoftonline.com/common/oauth2/v2.0/token` * **Grant Type**: Authorization Code or PKCE * **Scopes**: `User.Read`, `Mail.Read`, etc. ## Troubleshooting * Verify OAuth 2.0 is selected in the Auth tab * Confirm you clicked **Get Access Token** and received a token * Check that the token URL is correct * Ensure your OAuth application's allowed callback URL matches the redirect URI LiteClient sends. Its base form is `vscode://liteclienthq.liteclient/oauth-callback`, but VS Code may append an encoded `windowId` for the active window. * If your provider reports a callback URL mismatch, use the `redirect_uri` shown in its error details, decoded once, as the allowed callback URL. The generated URI may differ between VS Code windows. * Check that VS Code is set as the default handler for `vscode://` URIs * LiteClient automatically refreshes tokens when possible * If refresh fails, manually re-authenticate via the Auth tab * Verify the token URL is correct # Postman Migration Source: https://docs.liteclient.com/guides/postman-migration Import your existing Postman collections into LiteClient ## Overview LiteClient supports importing Postman Collection v2.1 files, including nested folders, requests, and metadata. This allows you to seamlessly migrate your existing API workflows to LiteClient. ## Supported Format LiteClient imports: * **Postman Collection v2.1** JSON files * Nested folders and request organization * Request metadata (name, description, method, URL) * Headers, body, and authentication configurations LiteClient currently supports **Postman Collection v2.1** format. Ensure your collection is in this version before importing. ## Importing a Postman Collection In the LiteClient sidebar, switch to the **Collections** tab Click the **Add Collection** button Choose **Import from Postman** from the options Select your Postman Collection v2.1 JSON file from your file system LiteClient automatically imports: * All requests with their configurations * Folder structure and organization * Request metadata and descriptions ## Exporting from Postman If you need to export your collection from Postman first: Launch the Postman application Find the collection you want to export in the sidebar 1. Click the three dots (...) next to the collection name 2. Select **Export** 3. Choose **Collection v2.1** as the format 4. Save the JSON file Use the JSON file with LiteClient's import feature Make sure to select **Collection v2.1** when exporting from Postman. Other versions may not be fully compatible. ## What Gets Imported LiteClient imports the following from Postman collections: * HTTP method (GET, POST, etc.) * URL and path parameters * Headers and values * Request body (all types) * Collection name and description * Nested folders * Request order and hierarchy * Request names * Request descriptions * Collection metadata * API Key configurations * Bearer tokens * Basic auth settings ## Exporting from LiteClient You can also export your LiteClient collections back to Postman format: Navigate to the **Collections** tab in the sidebar Find the collection you want to export 1. Click the collection menu (three dots) 2. Select **Export** 3. Choose a location to save the JSON file The exported file can be imported back into Postman if needed ## Migration Checklist When migrating from Postman to LiteClient: * [ ] Export your Postman collection as v2.1 JSON * [ ] Import the JSON file into LiteClient * [ ] Verify all requests are present * [ ] Check folder structure is maintained * [ ] Recreate any environment variables in LiteClient * [ ] Test critical requests to ensure they work as expected * [ ] Configure OAuth flows if using OAuth 2.0 authentication LiteClient's variable system works similarly to Postman's. You can recreate your Postman environments in LiteClient's **Env** tab. ## Differences from Postman While LiteClient maintains compatibility with Postman collections, there are some differences: Postman environments need to be recreated manually in LiteClient. Export your Postman environment as JSON, then manually create variables in LiteClient's **Env** tab. LiteClient does not currently support Postman's pre-request scripts. Use LiteClient's variable system for dynamic values. Postman test scripts are not imported. LiteClient focuses on request/response inspection via the native VS Code interface. LiteClient does not have a collection runner feature. Requests are executed individually. ## Troubleshooting * Verify the file is Postman Collection v2.1 format * Check that the JSON file is not corrupted * Ensure the file is properly formatted JSON * Try re-exporting from Postman if issues persist * Check if the requests are nested in folders * Expand all folders in the Collections tab * Verify the original Postman collection included all requests * Re-configure OAuth 2.0 flows in the Auth tab * Verify API keys and bearer tokens are set correctly * Check that variables used in auth are defined in environments # Storage Scopes Source: https://docs.liteclient.com/guides/storage-scopes Choose between global and workspace storage for collections, environments, and history ## Overview LiteClient offers two storage scopes for your API data: **Global** and **Workspace**. Choose the scope that best fits your workflow and team collaboration needs. ## Storage Scope Types Data stored in VS Code's global storage directory. Private to your machine, persists across all workspaces. Data stored in `.liteclient/` folder at workspace root. Can be shared via Git with your team. ## Global Storage By default, LiteClient stores all data in VS Code's global storage directory. ### Characteristics * **Location**: VS Code's `globalStorageUri` (machine-specific path) * **Scope**: Private to your user account on this machine * **Persistence**: Available across all VS Code workspaces * **Version Control**: Not tracked in Git ### When to Use Global Storage Working on solo projects where sharing isn't needed Storing sensitive API keys you don't want in repositories Testing the same APIs across multiple projects Personal testing and development workflows ## Workspace Storage Introduced in version 0.13.0, workspace storage enables team collaboration by storing data in your project directory. ### Characteristics * **Location**: `.liteclient/` folder at workspace root * **Scope**: Specific to the current workspace * **Persistence**: Only available when this workspace is open * **Version Control**: Can be committed to Git for team sharing ### Storage Files When using workspace storage, LiteClient creates: ```text theme={null} workspace-root/ └── .liteclient/ ├── collections.json # Collections, folders, requests ├── environments.json # Environments and variables ├── history.json # Request execution history ├── cookies.json # Cookie jar per domain └── settings.json # User preferences ``` ### When to Use Workspace Storage Share collections and environments with your team via Git API configurations that belong to a specific project New team members get API configs automatically when cloning API examples and test cases as part of project documentation Avoid committing sensitive data to workspace storage. Use environment variables or VS Code's SecretStorage for API keys and tokens. ## Switching Storage Scopes You can switch between global and workspace storage at any time. ### Using the Status Bar Look for the storage scope indicator in the VS Code status bar (bottom) Click the indicator showing **Global** or **Workspace** Choose your desired storage scope from the dropdown LiteClient will reload and use the selected storage scope ### Using Settings Alternatively, configure via VS Code settings: 1. Open Settings (`Ctrl+,` or `Cmd+,`) 2. Search for `liteclient.storageScope` 3. Select either `global` or `workspace` ## Migrating Data to Workspace If you've been using global storage and want to switch to workspace storage: Press `Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (macOS) Type and select: **LiteClient: Migrate Data to Workspace** LiteClient copies your global data into `.liteclient/` folder Add `.liteclient/` to your repository: ```bash theme={null} git add .liteclient/ git commit -m "Add LiteClient API configurations" ``` Migration **copies** data from global storage. Your original global data remains unchanged. ## File System Watcher When using workspace storage, LiteClient automatically watches for external changes: * Detects changes to `.liteclient/*.json` files * Refreshes sidebar when files change externally * Useful after `git pull` or external edits The file system watcher ensures your sidebar stays in sync when team members push collection updates. ## Version Control Best Practices When committing workspace storage to Git: ### Recommended `.gitignore` Patterns ```gitignore theme={null} # Ignore sensitive or user-specific files .liteclient/settings.json .liteclient/history.json # Commit shared configurations # .liteclient/collections.json # .liteclient/environments.json ``` **Recommended to commit**: Contains API requests and folder structure. Useful for team sharing. **Conditional**: Commit non-sensitive environment variables. Use template values (e.g., `{{YOUR_API_KEY}}`) for secrets. **Recommended to ignore**: Personal request history varies by developer. **Recommended to ignore**: Session cookies are user-specific and may contain sensitive data. **Recommended to ignore**: User preferences are personal. ## Comparison Table | Feature | Global Storage | Workspace Storage | | - | - | - | | **Location** | VS Code global directory | `.liteclient/` in workspace | | **Sharing** | Not shareable | Git-based team sharing | | **Scope** | All workspaces | Current workspace only | | **Version Control** | No | Yes | | **File System Watcher** | No | Yes | | **Use Case** | Personal workflows | Team collaboration | ## Troubleshooting * Verify the storage scope indicator shows the correct scope * Check that `.liteclient/` folder exists in workspace root * Try reloading VS Code window * Run the migration command if switching from global to workspace * Ensure you're using workspace storage scope * Check `.gitignore` isn't excluding `.liteclient/` * Verify files exist: `ls -la .liteclient/` * Confirm workspace storage is active * Verify `.liteclient/*.json` files are committed * Ask team members to pull latest changes and reload VS Code * Check file system watcher is functioning # Troubleshooting Source: https://docs.liteclient.com/guides/troubleshooting Common issues and solutions for LiteClient ## Common Issues This guide covers common issues you may encounter while using LiteClient and how to resolve them. If variables appear unchanged in your requests (e.g., `{{baseUrl}}` sent literally): **Possible Causes:** 1. No environment is selected in the sidebar 2. The variable doesn't exist in the active environment, collection, or globals 3. Typo in the variable name (e.g., `{{nam}}` instead of `{{name}}`) 4. The variable is disabled **Solutions:** * Ensure an environment is selected from the dropdown in the sidebar * Verify the variable exists in the **Env** tab (check Globals, Collection, and Environment sections) * Check the variable name spelling matches exactly (case-sensitive) * Confirm the variable is **enabled** (check the enabled checkbox) * Remember: Global variables are always available regardless of selected environment If your request fails before sending with an invalid URL error: **Possible Causes:** 1. URL missing `http://` or `https://` protocol 2. Unresolved variables in the URL 3. Malformed URL structure **Solutions:** * Verify the URL starts with `http://` or `https://` * Check for unresolved variables (e.g., `{{port}}` without defining the `port` variable) * Test the URL in a browser to confirm the endpoint exists * Use the variable autocomplete to ensure correct variable names If cookies aren't being included in your requests: **Possible Causes:** 1. Cookie Jar is disabled 2. Cookies don't match the request domain 3. Cookie has expired 4. Cookie security settings prevent sending **Solutions:** * Ensure the Cookie Jar is enabled (it's enabled by default) * Check that cookies match the request domain (e.g., cookies for `example.com` won't send to `api.other.com`) * Verify cookie hasn't expired using the Cookie Manager * Use the Cookie Manager to inspect stored cookies and their attributes * Check if the cookie has `Secure` flag and you're using `https://` If requests fail with authentication errors: **Possible Causes:** 1. Access token has expired 2. Refresh token failed or is invalid 3. OAuth configuration is incorrect **Solutions:** * LiteClient automatically refreshes tokens when possible * If automatic refresh fails, manually re-authenticate: 1. Open the request's **Auth** tab 2. Verify OAuth configuration (Authorization URL, Token URL, Client ID, Secret) 3. Click **Get Access Token** to acquire a new token * Check that the token URL is correct in your OAuth configuration * Verify your OAuth application credentials haven't been revoked If response appears as unformatted text: **Possible Causes:** 1. Missing or incorrect `Content-Type` header in response 2. Server returning non-JSON content 3. Response body is actually plain text **Solutions:** * Response formatting requires proper `Content-Type` header from the server * JSON responses with `Content-Type: application/json` are auto-formatted * Other content types (XML, HTML, plain text) display as-is * Check the response headers in the **Headers** tab to verify `Content-Type` * If the server is returning JSON without proper headers, contact the API maintainer If requests hang or timeout: **Possible Causes:** 1. Server is slow or unresponsive 2. Network connectivity issues 3. Request timeout setting too short **Solutions:** * Verify your internet connection is working * Test the endpoint in a browser or with `curl` to confirm it responds * Check if the server is experiencing downtime * Review any timeout settings in your request configuration * For slow endpoints, consider the expected response time If Postman import fails: **Possible Causes:** 1. Wrong Postman collection version 2. Corrupted JSON file 3. Invalid file format **Solutions:** * Verify the file is **Postman Collection v2.1** format * When exporting from Postman, explicitly select **Collection v2.1** * Check that the JSON file is not corrupted (open in a text editor) * Ensure the file is properly formatted JSON (use a JSON validator) * Try re-exporting from Postman if issues persist If switching to workspace storage shows empty collections: **Possible Causes:** 1. `.liteclient/` folder doesn't exist 2. Storage scope not properly switched 3. Data not migrated from global storage **Solutions:** * Verify the storage scope indicator in the status bar shows **Workspace** * Check that `.liteclient/` folder exists in your workspace root * Run **LiteClient: Migrate Data to Workspace** command to copy global data * Reload VS Code window after switching storage scopes * Check file permissions on `.liteclient/` directory If autocomplete doesn't show your variables: **Possible Causes:** 1. Variables not saved properly 2. Environment not selected 3. Autocomplete not triggered correctly **Solutions:** * Ensure you saved the environment after adding variables * Select an environment from the dropdown in the sidebar * Type `{{` to trigger autocomplete (not just `{`) * Check the **Env** tab to confirm variables exist * Global variables should always appear in autocomplete If headers aren't appearing in the actual request: **Possible Causes:** 1. Headers disabled in the headers table 2. Variables in headers not resolved 3. Header name/value contains invalid characters **Solutions:** * Check the checkbox next to each header in the Headers tab * Verify any variables in header values are defined and enabled * Ensure header names don't contain spaces or special characters * Test with a simple static header first * Use browser DevTools or a proxy to inspect the actual HTTP request If the OAuth flow opens browser but doesn't complete: **Possible Causes:** 1. Redirect URI not configured in OAuth app 2. VS Code not handling `vscode://` URIs 3. Browser blocking the callback **Solutions:** * Ensure your OAuth application's allowed callback URL matches the redirect URI LiteClient sends. Its base form is `vscode://liteclienthq.liteclient/oauth-callback`, but VS Code may append an encoded `windowId` for the active window. * If your provider reports a callback URL mismatch, use the `redirect_uri` shown in its error details, decoded once, as the allowed callback URL. The generated URI may differ between VS Code windows. * Check that VS Code is the default handler for `vscode://` URIs on your system * Try a different browser if your current browser blocks custom protocols * Verify the Authorization URL and Token URL are correct * Check OAuth application settings in the provider's console If LiteClient doesn't appear in VS Code: **Possible Causes:** 1. Extension not installed properly 2. VS Code needs restart 3. Extension disabled **Solutions:** * Verify LiteClient is installed: Extensions panel → Search "LiteClient" * Restart VS Code completely * Check if the extension is enabled (not disabled) * Look for the LiteClient icon in the Activity Bar (left sidebar) * Try reinstalling the extension from the marketplace * Check the Output panel (`View → Output → LiteClient`) for errors ## Getting Help If you encounter issues not covered here: Review the full documentation for detailed feature guides Report bugs or request features on the GitHub repository Check Output panel: `View → Output → LiteClient` Ask questions and share solutions with other users When reporting issues, include: * LiteClient version (from Extensions panel) * VS Code version (`Help → About`) * Operating system * Steps to reproduce the issue * Any error messages from the Output panel # Variables Source: https://docs.liteclient.com/guides/variables Use dynamic variables throughout your requests with LiteClient's variable system ## Overview LiteClient supports dynamic variable substitution using the `{{variableName}}` syntax. Variables can be used throughout your requests to create reusable, environment-specific configurations. ## Variable Syntax Variables are enclosed in double curly braces: ```text theme={null} {{baseUrl}}/api/users {{apiKey}} {{environmentVariable}} ``` ### Where Variables Work Variables can be used in: * **URLs**: `{{baseUrl}}/api/users/{{userId}}` * **Headers**: Both keys and values * **Request body**: All body modes (JSON, form-data, etc.) * **Authentication credentials**: API keys, OAuth parameters ## Variable Types LiteClient uses `EnvironmentVariable` objects with the following properties: * `id` - Unique identifier * `name` - Variable name (used in `{{name}}` syntax) * `initialValue` - The variable's value * `type` - Either `default` or `secret` * `enabled` - Boolean flag to enable/disable the variable Only **enabled** variables are resolved during request execution. ## Variable Resolution Order When a request is executed, LiteClient resolves variables using a layered precedence system. The **narrowest scope wins**: Global variables are always available regardless of the selected environment. They provide base values accessible across all requests. Collection-scoped variables override global variables. These are specific to requests within a collection. Environment variables have the highest precedence and override both global and collection variables. Use these for environment-specific configurations (development, staging, production). ### Resolution Example If you have: * Global variable: `baseUrl = https://api.example.com` * Collection variable: `baseUrl = https://api.dev.example.com` * Environment variable: `baseUrl = https://api.staging.example.com` The request will use `https://api.staging.example.com` (environment scope wins). ## Autocomplete LiteClient provides an autocomplete dropdown when typing variables: 1. Type `{{` to trigger autocomplete 2. Start typing the variable name 3. Use arrow keys to navigate available variables 4. Press Enter to select The autocomplete shows all available variables from global, collection, and environment scopes. ## Creating Variables ### Global Variables Global variables are always available: Switch to the **Env** tab in the LiteClient sidebar Select the **Globals** section Click **Add Variable** and enter name and value ### Environment Variables Create environment-specific variables: In the **Env** tab, click **New Environment** Enter a name (e.g., "Development", "Production") Click **Add Variable** and configure your environment-specific values Choose the environment from the dropdown in any request panel ## Best Practices Name variables clearly: `apiBaseUrl` instead of `url`, `authToken` instead of `token` Mark sensitive data (API keys, tokens) as `secret` type Use global variables for values shared across all environments Use environments to manage different configurations (dev, staging, prod) ## Troubleshooting If variables are not being substituted, check: 1. An environment is selected in the sidebar 2. The variable exists in the active environment, collection, or globals 3. The variable name matches exactly (case-sensitive) 4. The variable is **enabled** # Installation Source: https://docs.liteclient.com/installation Install LiteClient from the VS Code Marketplace, Open VSX, or from source LiteClient is available through multiple installation methods. The VS Code Marketplace is recommended for most users. ## VS Code Marketplace The easiest way to install LiteClient is through the VS Code Marketplace. Press `Ctrl+Shift+X` (Windows/Linux) or `Cmd+Shift+X` (macOS) to open the Extensions view in VS Code. Type "LiteClient" in the search box at the top of the Extensions view. Click the **Install** button on the LiteClient extension by liteclienthq. Click the LiteClient icon in the Activity Bar to open the sidebar and start making requests. You can also install LiteClient by opening the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`) and running **Extensions: Install Extensions**, then searching for "LiteClient". ## Open VSX Registry If you're using VS Codium or another VS Code compatible editor that uses Open VSX, you can install LiteClient from the Open VSX Registry. Go to [open-vsx.org/extension/liteclienthq/liteclient](https://open-vsx.org/extension/liteclienthq/liteclient) in your browser. Click the download button to get the latest `.vsix` file for your platform. Run the following command in your terminal, replacing `{version}` with the downloaded version: ```bash theme={null} code --install-extension liteclienthq.liteclient-{version}.vsix ``` ## Install from source Developers who want to contribute or customize LiteClient can install from source. ```bash theme={null} git clone https://github.com/liteclienthq/liteclient.git cd liteclient ``` ```bash theme={null} npm install ``` ```bash theme={null} npm run build ``` After building, you'll find a `.vsix` file in the `dist/` directory. Install it using: ```bash theme={null} code --install-extension dist/liteclient-{version}.vsix ``` Building from source requires Node.js 22.x or later and VS Code 1.90.0 or later. ## Verify installation After installing LiteClient through any method, verify the installation: 1. Look for the LiteClient icon in the Activity Bar (left sidebar) 2. Click the icon to open the LiteClient sidebar 3. You should see tabs for Collections, Environments, and History ## Next steps Make your first API request in under 60 seconds Learn how to organize your requests with collections # Introduction Source: https://docs.liteclient.com/introduction The fastest, most focused REST API client for your code editor LiteClient is a native VS Code extension that brings a powerful REST API client directly into your editor. No more context switching between your IDE and external tools. Make HTTP requests, manage environments, and organize your API collections without leaving VS Code. ## Why LiteClient? Modern API clients have become bloated with cloud accounts, telemetry, and features you never use. LiteClient returns to the fundamentals: Opens instantly with your workspace All data stays local. No accounts, no telemetry, no cloud sync Uses VS Code's native buttons, trees, and themes Everything you need, nothing you don't ## Get started Install LiteClient from the VS Code Marketplace or Open VSX Make your first request in under 60 seconds Organize API requests in hierarchical collections with drag-and-drop Manage different configurations for local, staging, and production API Key, Bearer Token, Basic Auth, and OAuth 2.0 support Automate workflows with pre-request and post-response scripts ## Core features ### Collections and organization Organize your API requests in a hierarchical structure that grows with your project. Create unlimited collections to group related APIs, nest requests inside folders for logical organization, and use drag-and-drop reordering to keep things organized. ### Environment management Manage different configurations for local, staging, and production environments. Create named environments with structured variables, use global variables available across all environments, and enjoy layered variable resolution that follows a clear precedence: Globals → Collection → Environment. ### Complete authentication support LiteClient supports the authentication methods you need: * **API Key** - Custom header or query parameter placement * **Bearer Token** - Simple token-based authentication * **Basic Auth** - Username/password with automatic Base64 encoding * **OAuth 2.0** - Authorization Code, Authorization Code with PKCE, and Client Credentials flows with automatic token caching and refresh ### Privacy first LiteClient is designed with privacy as a core principle. All data is stored locally in VS Code's global storage or optionally in your workspace's `.liteclient/` folder. No telemetry, no analytics, no tracking, and no cloud sync. Your API keys and credentials are stored locally—only you can access them. ## What's next? Get started by installing the extension Follow the quickstart guide to send your first API request # Quickstart Source: https://docs.liteclient.com/quickstart Make your first API request, create an environment, and organize with collections in under 5 minutes This guide walks you through the essential features of LiteClient. You'll make your first API request, set up an environment with variables, and organize your work with collections. ## Make your first request Let's start by making a simple GET request to a public API. Click the LiteClient icon in the Activity Bar to open the sidebar. Click **New Request** in the sidebar, or press `Ctrl+Shift+P` (Windows/Linux) or `Cmd+Shift+P` (macOS) and run **LiteClient: New Request**. In the URL bar at the top of the request panel, enter: ``` https://jsonplaceholder.typicode.com/users ``` Click the **Send** button or press `Ctrl+Enter` (Windows/Linux) or `Cmd+Enter` (macOS). The response appears in the panel below with syntax highlighting, status code, headers, and execution time. You can press `Ctrl+L` (Windows/Linux) or `Cmd+L` (macOS) to quickly focus the URL bar from anywhere in the request panel. ## Create an environment Environments let you manage different configurations for local, staging, and production. Let's create your first environment with variables. Click the **Env** tab in the LiteClient sidebar. Click **New Environment** and enter a name like "Development". Click **Add Variable** and create your first variable: * **Name**: `baseUrl` * **Value**: `http://localhost:3000` * **Type**: Default * **Enabled**: Yes Add an API key variable: * **Name**: `apiKey` * **Value**: `your-api-key-here` * **Type**: Secret (this masks the value in the UI) * **Enabled**: Yes Go back to your request panel and update the URL to use your variable: ``` {{baseUrl}}/api/users ``` Type `{{` to see an autocomplete dropdown with available variables. Variables follow a layered resolution order: **Globals** → **Collection** → **Environment**. Variables defined in narrower scopes override those in broader scopes. ## Organize with collections Collections help you organize related API requests in a hierarchical structure. Click the **Collections** tab in the LiteClient sidebar. Click **New Collection** and name it something descriptive like "My API". Right-click the collection and select **Add Request**. Give it a name like "Get Users". The request opens in a new panel. Add your URL, headers, and any authentication: ``` {{baseUrl}}/api/users ``` Your request is automatically saved to the collection. Any changes you make are persisted. Right-click the collection and select **New Folder** to create logical groupings. You can drag and drop requests between folders. You can import existing Postman Collections (v2.1) by clicking **Add Collection** → **Import from Postman** in the Collections tab. ## Add authentication LiteClient supports multiple authentication methods. Let's add a Bearer token to a request. In your request panel, click the **Auth** tab. Choose **Bearer Token** from the dropdown. You can enter a token directly or use a variable: ``` {{apiKey}} ``` Click **Send**. The `Authorization` header is automatically added with your Bearer token. ### Other authentication methods Add an API key as a custom header or query parameter Username and password with automatic Base64 encoding Authorization Code, PKCE, and Client Credentials flows with automatic token refresh ## Use the request history Every request you send is automatically recorded in the History tab. Click the **History** tab in the LiteClient sidebar. History is organized by day (Today, Yesterday, Last Week). Each entry shows the method, URL, and execution time. Click any history entry to open it in a new request panel and send it again. Right-click any day group to delete all requests from that day, or click **Clear History** to remove everything. ## Storage scopes LiteClient gives you control over where your data is stored. * **Global storage** (default) - Collections, environments, and history are stored in VS Code's global storage, available across all workspaces * **Workspace storage** - Data is stored in a `.liteclient/` folder in your project root, perfect for sharing API collections via Git Click the **LiteClient: Global/Workspace** indicator in the status bar to switch between scopes. Workspace storage requires an open folder. Each scope maintains independent collections, environments, and history. ## Next steps You've learned the basics of LiteClient. Here's what to explore next: Write pre-request and post-response scripts to automate workflows View and manage cookies with the built-in Cookie Manager Migrate from Postman by importing Collection v2.1 files Set up OAuth 2.0 flows with automatic token caching and refresh # Architecture Source: https://docs.liteclient.com/reference/architecture Technical architecture and design patterns of the LiteClient VS Code extension LiteClient is built as a native VS Code extension using a three-tier architecture that separates business logic, communication protocols, and user interface. This design prioritizes performance, privacy, and native IDE integration. ## Overview LiteClient is a lightweight REST API client that runs entirely within VS Code. All data persists locally with no external services or telemetry. The extension follows VS Code's extension architecture patterns and leverages native platform capabilities. ## Three-Tier Architecture The extension is organized into three distinct layers: ### 1. Extension Module Runs in the VS Code extension host process (Node.js environment). **Responsibilities**: * Business logic for collections, environments, history * HTTP request execution with Node.js capabilities * File I/O and data persistence * Cookie management and OAuth2 flows * Command registration and handling **Key Components**: * Services (business logic) * Commands (user-invokable actions) * Providers (webview lifecycle management) * Storage (JSON file persistence) ### 2. Message Protocol Typed communication layer between extension and webview. **Features**: * Type-safe message definitions * Bidirectional communication * Request/response patterns * State synchronization **Message Types**: * Request execution (`send-request`) * Response delivery (`response`) * State updates (`collections-list`, `environments-list`, `history-list`) * User actions (create, update, delete operations) ### 3. Webview Module Runs in a webview context (browser-like environment). **Responsibilities**: * User interface rendering * Form input and validation * Response visualization * Request/response editing **Technology Stack**: * Lit web components * CodeMirror 6 for code editing * Native HTML/CSS for performance ## Extension Module Architecture ### Services Layer The services layer encapsulates all business logic: **File**: `collectionService.ts` **Responsibilities**: * CRUD operations for collections, folders, and requests * Postman Collection v2.1 import/export * Nested folder hierarchy management * Request metadata persistence **Storage**: `collections.json` **File**: `environmentService.ts` **Responsibilities**: * Environment and variable management * Global variables (shared across all requests) * Variable enable/disable toggling * Secret variable handling **Storage**: `environments.json` **File**: `historyService.ts` **Responsibilities**: * Request execution tracking * Day-grouped organization * History search and filtering * History item deletion **Storage**: `history.json` **File**: `httpRequestService.ts` **Responsibilities**: * HTTP client with Node.js Fetch API * Variable substitution in URL, headers, body * Request timeout handling * Redirect following * Response capture and formatting **Storage**: None (stateless) **File**: `cookieJarService.ts` **Responsibilities**: * Cookie persistence per domain * Automatic cookie sending with requests * Set-Cookie header capture * Cookie expiration management **Technology**: tough-cookie library\ **Storage**: `cookies.json` **File**: `oauth2TokenService.ts` **Responsibilities**: * OAuth2 token acquisition * Token caching and refresh * PKCE support * Authorization Code and Client Credentials flows **Storage**: VS Code SecretStorage (encrypted) **File**: `settingsService.ts` **Responsibilities**: * User preferences * UI state persistence * Workspace-specific settings **Storage**: `settings.json` ### Service Patterns All services follow consistent design patterns: * **Constructor injection**: StorageService injected via constructor * **Async/await**: All I/O operations are asynchronous * **Error handling**: Descriptive errors thrown for invalid operations * **Single responsibility**: Each service owns a specific domain ```typescript theme={null} // Example service pattern class EnvironmentService { constructor(private storage: StorageService) {} async getEnvironments(): Promise { return await this.storage.read('environments.json'); } async createEnvironment(name: string): Promise { // Implementation } } ``` ### Providers Layer Providers manage webview lifecycle and message routing: Manages the sidebar webview with Collections, Environments, and History tabs. **Lifecycle**: * Creates webview on sidebar activation * Loads HTML/CSS/JS for sidebar UI * Routes messages between webview and services * Handles state synchronization Creates and manages request editor panels (custom editor for `.lcreq` files). **Lifecycle**: * Opens panel when `.lcreq` file is opened * Loads request data from file * Handles OAuth2 flows via URI handler * Saves request changes back to file Manages the cookie manager webview panel. **Lifecycle**: * Opens on command invocation * Displays all cookies grouped by domain * Handles cookie editing and deletion ### Commands Layer Commands are user-invokable actions registered in `package.json`: | File | Commands | | - | - | | `collectionCommands.ts` | Collection CRUD, import/export | | `environmentCommands.ts` | Environment and variable operations | | `historyCommands.ts` | History access and management | | `requestCommands.ts` | New request creation | | `cookieCommands.ts` | Cookie management commands | **Command Pattern**: ```typescript theme={null} export function registerNewRequest(deps: CommandDependencies) { return vscode.commands.registerCommand('liteclient.newRequest', async () => { // Command implementation }); } ``` ## Webview Architecture ### Request Editor Components The request editor is built with Lit web components: * **lc-url-bar**: URL input with HTTP method selector * **lc-tabs**: Tab navigation for request sections * **lc-headers-table**: Key-value editor for headers * **lc-body-panel**: Request body editor with format support * **lc-auth-panel**: Authentication configuration (OAuth2, Bearer, Basic) * **lc-form-data-editor**: Multipart form-data with file uploads * **lc-variable-autocomplete**: Environment variable autocomplete (`{{var}}`) * **lc-response-view**: Response display with syntax highlighting * **lc-cookies-table**: Response cookies viewer * **lc-status-bar**: Response status, timing, size * **lc-request-meta**: Request metadata (name, description) ### Sidebar Components * **lc-sidebar-panel**: Main container with tabs * **lc-collection-tree**: Hierarchical collection browser * **lc-env-switcher**: Environment selector dropdown * **lc-environment-list**: Environment and variable management * **lc-history-list**: Day-grouped request history * **lc-cookie-manager**: Cookie management interface ### Shared Components Shared across request editor and sidebar: * **models.ts**: TypeScript data models (Environment, Collection, Request, etc.) * **messages.ts**: Typed message definitions for extension communication * **variableSubstitution.ts**: `{{variableName}}` substitution logic * **variableResolver.ts**: Centralized variable resolution with layered precedence ## Data Storage ### Storage Architecture LiteClient uses a JSON file-based storage system: ```text theme={null} [Storage Directory] ├── collections.json # Collections, folders, requests ├── environments.json # Environments and variables ├── history.json # Request execution history ├── cookies.json # Serialized cookie jar └── settings.json # User preferences ``` ### Storage Scopes **Location**: VS Code's `globalStorageUri` **Characteristics**: * Private to the user * Not stored in project repository * Available across all workspaces * Platform-specific location **Use Case**: Personal API testing, sensitive credentials **Location**: `.liteclient/` in workspace root **Characteristics**: * Shareable via Git * Project-specific * Team collaboration * Version controlled **Use Case**: Shared API collections, team environments ### StorageService Provides atomic file operations with corruption recovery: ```typescript theme={null} class StorageService { async read(filename: string): Promise async write(filename: string, data: T): Promise async delete(filename: string): Promise async exists(filename: string): Promise } ``` **Features**: * Atomic writes (write to temp file, then rename) * Backup on corruption detection * JSON schema validation * Error recovery ## Request Execution Flow The complete flow from user action to response display: ```mermaid theme={null} sequenceDiagram User->>lc-url-bar: Clicks Send lc-url-bar->>RequestPanelManager: send-request message RequestPanelManager->>variableResolver: Resolve variables variableResolver->>EnvironmentService: Get environment variableResolver->>CollectionService: Get collection variableResolver-->>RequestPanelManager: Resolved values RequestPanelManager->>HttpRequestService: Execute request HttpRequestService->>CookieJarService: Get cookies for domain HttpRequestService->>Fetch API: HTTP request Fetch API-->>HttpRequestService: HTTP response HttpRequestService->>CookieJarService: Store Set-Cookie headers HttpRequestService-->>RequestPanelManager: Response data RequestPanelManager->>HistoryService: Record request RequestPanelManager->>lc-response-view: response message lc-response-view->>User: Display response RequestPanelManager->>SidebarProvider: Update history SidebarProvider->>lc-history-list: history-list message ``` ### Variable Resolution Order Variables follow a layered precedence (narrowest scope wins): 1. **Globals** - Shared across all requests 2. **Collection** - Available to all requests in a collection 3. **Environment** - Scoped to selected environment Only **enabled** variables are resolved. Disabled variables are ignored during substitution. ## Extension Initialization Startup sequence when VS Code activates the extension: 1. `extension.activate()` called 2. Create `StorageService` (determines scope from settings) 3. Instantiate all services with `StorageService` injection 4. Register `SidebarProvider` for sidebar webview 5. Register `RequestPanelManager` for `.lcreq` custom editor 6. Register `CookieManagerProvider` for cookie manager panel 7. Register URI handler for OAuth2 callbacks 8. Register all commands with `CommandDependencies` 9. Extension ready for user interaction ## Performance Considerations * **Lazy loading**: Webviews created only when needed * **Efficient messaging**: Only changed state synchronized * **JSON streaming**: Large responses streamed to webview * **CodeMirror**: Virtual scrolling for large documents * **Indexed lookups**: Fast collection/environment retrieval ## Security Model * **Local-only**: No external network calls except user requests * **No telemetry**: Zero tracking or analytics * **SecretStorage**: OAuth tokens stored in VS Code's encrypted storage * **Sandboxed webviews**: Isolated execution context * **Script sandboxing**: Pre-request/test scripts run in Node.js `vm` sandbox # Commands Source: https://docs.liteclient.com/reference/commands Complete reference of all VS Code commands available in LiteClient LiteClient provides a comprehensive set of commands for managing requests, collections, environments, history, and cookies. All commands can be accessed via the Command Palette (`Ctrl+Shift+P` or `Cmd+Shift+P`). ## Request Commands Create a new HTTP request file. Opens a new `.lcreq` file in the request editor. **Category**: LiteClient\ **Icon**: New File Open a previously executed request from history. Loads the request details into a new request editor. **Category**: LiteClient ## Collection Commands Create a new collection to organize related requests. Prompts for a collection name. **Category**: LiteClient\ **Icon**: New Folder Add an existing collection. Alternative method for creating collections. **Category**: LiteClient Rename an existing collection. Prompts for a new name. **Category**: LiteClient\ **Icon**: Edit Delete a collection and all its requests. Prompts for confirmation. **Category**: LiteClient\ **Icon**: Trash Add the current request to a collection. Prompts to select the target collection. **Category**: LiteClient Rename a request within a collection. Prompts for a new name. **Category**: LiteClient Remove a request from a collection. The request file itself is not deleted. **Category**: LiteClient\ **Icon**: Trash ## Runner Commands Run all requests in a collection or folder sequentially. If no collection is specified, prompts to select one. Opens the Collection Runner panel with real-time progress and results. **Category**: LiteClient Also available from the action menu (⋯) on collections ("Run Collection") and folders ("Run Folder") in the sidebar. ## Environment Commands Create a new environment for managing variables. Prompts for an environment name. **Category**: LiteClient\ **Icon**: New Folder Add a new environment. Alternative method for creating environments. **Category**: LiteClient Rename an existing environment. Prompts for a new name. **Category**: LiteClient\ **Icon**: Edit Delete an environment and all its variables. Prompts for confirmation. **Category**: LiteClient\ **Icon**: Trash Open the environment manager interface to manage all environments and variables. **Category**: LiteClient ## Variable Commands Add a new variable to the selected environment. Prompts for name and value. **Category**: LiteClient\ **Icon**: Add Edit an existing environment variable. Prompts for new name and value. **Category**: LiteClient\ **Icon**: Edit Delete a variable from the environment. Prompts for confirmation. **Category**: LiteClient\ **Icon**: Trash ## History Commands Delete a single request from the history. Available in the history list context menu. **Category**: LiteClient\ **Icon**: Trash Clear all request execution history. Prompts for confirmation. **Category**: LiteClient\ **Icon**: Trash ## Cookie Commands Open the cookie manager interface to view and manage all stored cookies. **Category**: LiteClient Clear the entire cookie jar. Removes all cookies for all domains. **Category**: LiteClient ## Storage Commands Migrate all data (collections, environments, history, cookies) from global storage to workspace storage. **Category**: LiteClient This command creates a `.liteclient/` folder in your workspace root and copies all data there. Use this when you want to share collections and environments via Git. Switch between global and workspace storage scopes. Updates the `liteclient.storageScope` setting. **Category**: LiteClient Switching storage scope does not automatically migrate data. Use `liteclient.migrateToWorkspace` to copy data from global to workspace storage. ## Using Commands ### Command Palette Access any command by opening the Command Palette: Press `Ctrl+Shift+P` and type "LiteClient" to filter available commands. Press `Cmd+Shift+P` and type "LiteClient" to filter available commands. ### Context Menus Many commands are also available via right-click context menus in the LiteClient sidebar: * **Collections**: Right-click a collection for rename/delete options * **Requests**: Right-click a request for rename/delete options * **Environments**: Right-click for rename/delete/add variable options * **Variables**: Right-click for edit/delete options * **History**: Right-click for delete options ### Keyboard Shortcuts You can assign custom keyboard shortcuts to any LiteClient command: 1. Open **Preferences: Open Keyboard Shortcuts** from the Command Palette 2. Search for the command (e.g., "liteclient.newRequest") 3. Click the + icon to add a custom keybinding Example keybinding: ```json theme={null} { "key": "ctrl+alt+n", "command": "liteclient.newRequest" } ``` # Configuration Source: https://docs.liteclient.com/reference/configuration Configuration options for customizing LiteClient behavior LiteClient provides configuration options to customize storage behavior and data persistence. All settings can be configured through VS Code's settings interface or directly in `settings.json`. ## Settings ### Storage Scope Controls where LiteClient stores collections, environments, history, and cookies. **Type**: `string`\ **Options**: `"global"` | `"workspace"`\ **Default**: `"global"` #### Options Stores all data in VS Code's global storage directory. Data is: * **Private**: Not stored in your project repository * **Persistent**: Available across all workspaces * **User-specific**: Each user has their own collections and environments **Storage location**: Platform-specific VS Code global storage directory Recommended for personal API testing and when you don't want to commit sensitive data to version control. Stores all data in a `.liteclient/` folder in your workspace root. Data is: * **Shareable**: Can be committed to Git and shared with team * **Project-specific**: Isolated per workspace * **Team-accessible**: All team members can access the same collections **Storage location**: `/.liteclient/` Recommended for team collaboration and when you want to version control your API collections. #### Storage Files Regardless of scope, LiteClient stores data in these JSON files: | File | Contents | | - | - | | `collections.json` | Collections, folders, and saved requests | | `environments.json` | Environments and variables (including globals) | | `history.json` | Request execution history with timestamps | | `cookies.json` | Serialized cookie jar (per domain) | | `settings.json` | User preferences and UI state | ## Configuring Settings ### Using VS Code Settings UI 1. Open **Settings** (`Ctrl+,` or `Cmd+,`) 2. Search for "liteclient" 3. Select your preferred storage scope from the dropdown ### Using settings.json Add the configuration directly to your VS Code settings: Configure for all workspaces: ```json theme={null} { "liteclient.storageScope": "global" } ``` Access via: **Preferences: Open User Settings (JSON)** Configure for current workspace only: ```json theme={null} { "liteclient.storageScope": "workspace" } ``` Access via: **Preferences: Open Workspace Settings (JSON)** ## Migrating Data ### From Global to Workspace To migrate existing data from global to workspace storage: 1. Set `liteclient.storageScope` to `"workspace"` 2. Run the **LiteClient: Migrate Data to Workspace** command 3. All collections, environments, history, and cookies will be copied to `.liteclient/` The migration creates this structure: ```text theme={null} workspace-root/ └── .liteclient/ ├── collections.json ├── environments.json ├── history.json ├── cookies.json └── settings.json ``` The migration **copies** data rather than moving it. Your global storage data remains intact after migration. ### From Workspace to Global To switch from workspace to global storage: 1. Set `liteclient.storageScope` to `"global"` 2. LiteClient will read from global storage on next launch 3. The `.liteclient/` folder remains in your workspace but is not used There is no automatic migration from workspace to global. You'll need to manually copy data if needed. ## Version Control ### Workspace Storage When using workspace storage, you can commit the `.liteclient/` folder to Git: ```gitignore theme={null} # Include collections and environments !.liteclient/collections.json !.liteclient/environments.json # Exclude sensitive data .liteclient/history.json .liteclient/cookies.json .liteclient/settings.json ``` **Security Warning**: Be careful not to commit sensitive data like API keys, tokens, or cookies. Consider using environment variables for sensitive values and marking them as "secret" type in LiteClient. ### Global Storage Global storage is never committed to version control. It resides in VS Code's application data directory: * **Windows**: `%APPDATA%/Code/User/globalStorage/liteclienthq.liteclient/` * **macOS**: `~/Library/Application Support/Code/User/globalStorage/liteclienthq.liteclient/` * **Linux**: `~/.config/Code/User/globalStorage/liteclienthq.liteclient/` ## Best Practices ### For Individual Developers * Use **global** storage for personal projects and experimentation * Keep sensitive credentials in global storage to avoid accidental commits * Use environment variables with "secret" type for API keys ### For Teams * Use **workspace** storage for shared API collections * Commit `collections.json` and `environments.json` to Git * Use `.gitignore` to exclude `history.json` and `cookies.json` * Document required environment variables in your README * Use placeholder values for sensitive variables (e.g., `{{API_KEY}}`) ### For Open Source Projects * Use **workspace** storage with example collections * Provide template environments with placeholder values * Document all required variables and how to obtain credentials * Never commit actual API keys or tokens # Scripting API Source: https://docs.liteclient.com/reference/scripting-api JavaScript API for pre-request and post-response scripts in LiteClient LiteClient supports pre-request and post-response scripts using a Postman-compatible `pm` API. Write JavaScript code that runs before sending a request or after receiving a response to automate workflows, set variables dynamically, and validate responses. ## Overview Scripts enable advanced automation and testing workflows: * **Pre-request scripts**: Run before a request is sent (set dynamic headers, compute signatures, etc.) * **Post-response scripts**: Run after receiving a response (validate data, extract values, run tests) Scripts run in a sandboxed Node.js `vm` environment with a 10-second timeout and 100KB size limit. ## The pm Object The `pm` object provides the scripting API. It's available globally in all scripts. ### pm.environment Access and modify environment variables. Get the value of an environment variable. **Signature**: `pm.environment.get(name: string): string | undefined` ```javascript theme={null} const apiKey = pm.environment.get('API_KEY'); console.log('Using API key:', apiKey); ``` Set or create an environment variable. Changes are persisted to storage. **Signature**: `pm.environment.set(name: string, value: string): void` ```javascript theme={null} // Extract token from response and save to environment const token = pm.response.json().access_token; pm.environment.set('AUTH_TOKEN', token); ``` If the variable doesn't exist, it will be created automatically in the current environment. Remove an environment variable. **Signature**: `pm.environment.unset(name: string): void` ```javascript theme={null} pm.environment.unset('TEMP_TOKEN'); ``` ### pm.globals Access and modify global variables (shared across all environments). Get the value of a global variable. **Signature**: `pm.globals.get(name: string): string | undefined` ```javascript theme={null} const baseUrl = pm.globals.get('BASE_URL'); ``` Set or create a global variable. Changes are persisted to storage. **Signature**: `pm.globals.set(name: string, value: string): void` ```javascript theme={null} pm.globals.set('REQUEST_COUNT', '42'); ``` Remove a global variable. **Signature**: `pm.globals.unset(name: string): void` ```javascript theme={null} pm.globals.unset('TEMP_VALUE'); ``` ### pm.variables Read-only access to resolved variables (combines globals, collection, and environment). Get the resolved value of a variable following precedence order. **Signature**: `pm.variables.get(name: string): string | undefined` **Resolution order**: Globals → Collection → Environment (narrowest wins) ```javascript theme={null} // Gets the most specific value const apiUrl = pm.variables.get('API_URL'); ``` Use `pm.variables.get()` when you don't care which scope the variable comes from. Use `pm.environment.get()` or `pm.globals.get()` when you need a specific scope. ### pm.request Access request data (available in both pre-request and post-response scripts). The request URL (after variable substitution). ```javascript theme={null} console.log('Sending request to:', pm.request.url); ``` The HTTP method (GET, POST, PUT, DELETE, etc.). ```javascript theme={null} if (pm.request.method === 'POST') { // Add special header for POST requests pm.request.headers.add('X-Request-Type', 'mutation'); } ``` Request headers collection. **Methods**: * `get(name: string): string | undefined` - Get header value * `add(name: string, value: string): void` - Add header * `remove(name: string): void` - Remove header ```javascript theme={null} // Add authentication header const token = pm.environment.get('TOKEN'); pm.request.headers.add('Authorization', `Bearer ${token}`); // Check existing header const contentType = pm.request.headers.get('Content-Type'); ``` Request body content. **Methods**: * `raw()` - Get body as string * `json()` - Parse body as JSON (throws if invalid) ```javascript theme={null} // Modify request body const body = pm.request.body.json(); body.timestamp = new Date().toISOString(); pm.request.body = JSON.stringify(body); ``` ### pm.response Access response data (only available in post-response scripts). HTTP status code. ```javascript theme={null} pm.test('Status is 200', () => { pm.expect(pm.response.code).to.equal(200); }); ``` HTTP status text (e.g., "OK", "Not Found"). ```javascript theme={null} console.log('Response status:', pm.response.status); ``` Response headers collection. **Methods**: * `get(name: string): string | undefined` - Get header value * `has(name: string): boolean` - Check if header exists ```javascript theme={null} const contentType = pm.response.headers.get('Content-Type'); pm.test('Response is JSON', () => { pm.expect(contentType).to.include('application/json'); }); ``` Raw response body as string. ```javascript theme={null} console.log('Response length:', pm.response.body.length); ``` Parse response body as JSON. **Signature**: `pm.response.json(): any` ```javascript theme={null} const data = pm.response.json(); pm.test('Has user ID', () => { pm.expect(data.user.id).to.be.a('number'); }); ``` Throws an error if the response body is not valid JSON. Response time in milliseconds. ```javascript theme={null} pm.test('Response time is acceptable', () => { pm.expect(pm.response.time).to.be.below(500); }); ``` ### pm.test() Define a test assertion (post-response scripts only). Create a named test with an assertion function. **Signature**: `pm.test(name: string, fn: () => void): void` ```javascript theme={null} pm.test('User has valid email', () => { const user = pm.response.json(); pm.expect(user.email).to.match(/@/); }); ``` **Test results** are displayed in the "Tests" tab of the response panel. ### pm.expect() ChaiJS-style assertions for testing. Create an assertion using Chai's expect syntax. **Signature**: `pm.expect(actual): Assertion` **Common assertions**: ```javascript theme={null} pm.expect(actual).to.equal(expected); pm.expect(actual).to.eql(expected); // deep equality pm.expect(actual).to.not.equal(value); ``` ```javascript theme={null} pm.expect(value).to.be.a('string'); pm.expect(value).to.be.an('array'); pm.expect(value).to.be.a('number'); pm.expect(value).to.be.true; pm.expect(value).to.be.null; pm.expect(value).to.be.undefined; ``` ```javascript theme={null} pm.expect(value).to.be.above(10); pm.expect(value).to.be.below(100); pm.expect(value).to.be.at.least(5); pm.expect(value).to.be.at.most(50); ``` ```javascript theme={null} pm.expect(str).to.include('substring'); pm.expect(str).to.match(/regex/); pm.expect(str).to.have.lengthOf(10); ``` ```javascript theme={null} pm.expect(array).to.be.an('array').that.is.not.empty; pm.expect(array).to.have.lengthOf(3); pm.expect(array).to.include('item'); pm.expect(obj).to.have.property('key'); pm.expect(obj).to.have.all.keys('a', 'b', 'c'); ``` ### pm.sendRequest() Make HTTP requests from within scripts. Send an HTTP request from a script. Accepts a URL string or a request options object. **Signatures**: * `pm.sendRequest(url: string, callback?: (err, response) => void): void` * `pm.sendRequest(request: object, callback?: (err, response) => void): void` **Request object properties**: * `url` (string, required) — The request URL * `method` (string, optional) — HTTP method, defaults to `GET` * `header` or `headers` (object, optional) — Request headers * `body` (string or `{ raw: string }`, optional) — Request body **Callback response object**: * `code` (number) — HTTP status code * `status` (string) — Status text (e.g. `"200 OK"`) * `headers` (object) — Response headers * `json()` — Parse response body as JSON * `text()` — Get response body as string ```javascript theme={null} // Simple GET pm.sendRequest('https://api.example.com/health', function (err, res) { console.log('Status:', res.code); }); // POST with body pm.sendRequest({ url: 'https://api.example.com/auth/token', method: 'POST', header: { 'Content-Type': 'application/json' }, body: { raw: JSON.stringify({ grant_type: 'client_credentials' }) } }, function (err, res) { if (!err) { pm.environment.set('token', res.json().access_token); } }); ``` Limited to 5 calls per script execution. Shares the 10-second script timeout. If the callback is omitted, errors are silently ignored. ### console Log messages and debugging output. Log informational messages. **Signature**: `console.log(...args: any[]): void` ```javascript theme={null} console.log('Token extracted:', token); console.log('User data:', user.name, user.email); ``` Log error messages. **Signature**: `console.error(...args: any[]): void` ```javascript theme={null} console.error('Failed to parse response:', error.message); ``` Log warning messages. **Signature**: `console.warn(...args: any[]): void` ```javascript theme={null} console.warn('Deprecated API endpoint used'); ``` Console output is displayed in the "Tests" tab with a 200-entry limit. Logs are cleared between requests. ## Script Examples ### Pre-Request Script Examples Add computed headers before sending the request: ```javascript theme={null} // Add timestamp header pm.request.headers.add('X-Request-Time', new Date().toISOString()); // Add HMAC signature const secret = pm.environment.get('API_SECRET'); const payload = pm.request.body.raw(); const signature = computeHMAC(secret, payload); pm.request.headers.add('X-Signature', signature); ``` Check token expiration and refresh if needed: ```javascript theme={null} const expiresAt = pm.globals.get('TOKEN_EXPIRES_AT'); const now = Date.now(); if (!expiresAt || now >= parseInt(expiresAt)) { console.log('Token expired, refreshing...'); pm.sendRequest({ url: pm.environment.get('TOKEN_URL'), method: 'POST', header: { 'Content-Type': 'application/json' }, body: { raw: JSON.stringify({ grant_type: 'client_credentials', client_id: pm.environment.get('CLIENT_ID') }) } }, function (err, res) { if (!err) { const data = res.json(); pm.environment.set('AUTH_TOKEN', data.access_token); pm.globals.set('TOKEN_EXPIRES_AT', (now + data.expires_in * 1000).toString()); console.log('Token refreshed'); } }); } ``` Track request count: ```javascript theme={null} const count = parseInt(pm.globals.get('REQUEST_COUNT') || '0'); pm.globals.set('REQUEST_COUNT', (count + 1).toString()); console.log('Request number:', count + 1); ``` ### Post-Response Script Examples Extract authentication token from response: ```javascript theme={null} const response = pm.response.json(); if (response.access_token) { pm.environment.set('AUTH_TOKEN', response.access_token); console.log('Token saved to environment'); // Calculate expiration time const expiresIn = response.expires_in || 3600; const expiresAt = Date.now() + (expiresIn * 1000); pm.globals.set('TOKEN_EXPIRES_AT', expiresAt.toString()); } ``` Validate response structure and data: ```javascript theme={null} pm.test('Status is 200 OK', () => { pm.expect(pm.response.code).to.equal(200); }); pm.test('Response is JSON', () => { const contentType = pm.response.headers.get('Content-Type'); pm.expect(contentType).to.include('application/json'); }); pm.test('Response has required fields', () => { const data = pm.response.json(); pm.expect(data).to.have.property('id'); pm.expect(data).to.have.property('email'); pm.expect(data.email).to.be.a('string'); }); pm.test('Response time is acceptable', () => { pm.expect(pm.response.time).to.be.below(1000); }); ``` Extract data for use in subsequent requests: ```javascript theme={null} const user = pm.response.json(); // Save user ID for next request pm.environment.set('USER_ID', user.id.toString()); pm.environment.set('USER_EMAIL', user.email); console.log('User created:', user.id, user.email); pm.test('User ID is valid', () => { pm.expect(user.id).to.be.a('number'); pm.expect(user.id).to.be.above(0); }); ``` Handle errors gracefully: ```javascript theme={null} if (pm.response.code >= 400) { console.error('Request failed:', pm.response.status); try { const error = pm.response.json(); console.error('Error details:', error.message); } catch (e) { console.error('Non-JSON error response'); } } else { pm.test('Request successful', () => { pm.expect(pm.response.code).to.be.below(400); }); } ``` ## Script Limits Scripts run in a sandboxed environment with the following limits: * **Timeout**: 10 seconds maximum execution time * **Size**: 100KB maximum script size * **Console output**: 200 entries maximum * **Test results**: 200 tests maximum * **`pm.sendRequest()` calls**: 5 per script execution * **No external modules**: Cannot use `require()` or `import` * **No file system access**: Cannot read/write files Scripts that exceed the timeout or size limit will be terminated and an error will be displayed in the Tests tab. ## Postman Compatibility LiteClient's scripting API is compatible with Postman Collection v2.1: * **Import**: Pre-request and test scripts are preserved when importing Postman collections * **Export**: Scripts are included when exporting to Postman format * **Limitations**: Collection-level and folder-level scripts are not supported (request-level only) When importing a collection with collection-level or folder-level scripts, a warning will be displayed. You'll need to manually copy those scripts to individual requests. ## Best Practices ### Script Organization * Keep scripts focused on a single responsibility * Use comments to explain complex logic * Extract common logic to environment variables (as JSON strings) * Use meaningful test names that describe what's being validated ### Performance * Avoid expensive operations in pre-request scripts (they delay request sending) * Cache computed values in variables instead of recalculating * Use `console.log()` sparingly in production scripts ### Error Handling * Always wrap JSON parsing in try-catch blocks * Check for variable existence before using them * Provide descriptive error messages in console output * Use tests to validate assumptions about response structure ### Variable Management * Use globals for values shared across all requests (base URLs, API keys) * Use environment variables for values specific to an environment (dev/prod tokens) * Use descriptive variable names (avoid single letters) * Clean up temporary variables with `unset()` when done