Resterm Documentation

repository·main·Indexed 23 days ago

https://github.com/unkn0wn-root/resterm

A terminal-based, keyboard-driven API client for REST, GraphQL, gRPC, WebSocket, and SSE. Resterm treats requests as versionable .http files and features a Vim-style TUI, built-in mock server capabilities via @mock directives, and RestermScript (RTS) for request scripting. It supports OpenAPI 3 imports, OAuth 2.0 flows, request tracing, and routing via SSH tunnels or Kubernetes port-forwards. The CLI provides tools for scripted runs, collection management (export/import/pack), and request history maintenance.

Tokens
39.5K
Snippets
97
Records
198
Agent score
83%

What's inside Resterm

  1. Overview of Resterm CLI entry points

    main

    Resterm provides three primary command-line entry points depending on your workflow:

    1. resterm: Opens the interactive Terminal User Interface (TUI). It also provides tools for importing, updating, history management, and collections.
    2. resterm run: Executes .http or .rest files headlessly (without the TUI). This is used for running workflows, comparing runs, or profiling runs.
    3. resterm mock: Starts a mock server that serves responses declared via # @mock directives within your request files.
  2. Navigate the Resterm UI

    main

    Resterm uses a multi-pane layout designed for high-speed interaction via keyboard shortcuts:

    • Sidebar: A unified navigator for files, requests, and workflows. Use /Space to expand files, g+k/g+j to collapse/expand branches, and g+Shift+K/g+Shift+J for all branches. Use g+h to shrink and g+l to expand.
    • Editor: The middle pane for writing requests. It uses modal editing (default is view mode; press i to enter insert mode, Esc to return to view). Supports Vim motions.
    • Response Panes: The right-hand side displaying the latest response. Supports multiple views: Pretty (formatted JSON), Raw (exact text), Stream (WebSocket/SSE), Headers, Profile/Workflow, Timeline, Diff, and History.
    • Header Bar: Displays workspace, active environment, current request, and test summaries.
    • Command Bar & Status: Provides contextual hints, progress animations, and notifications.
  3. What is RestermScript (RTS)?

    main

    RestermScript (RTS) is Resterm's built-in, bounded expression language used for templates, directives, and reusable modules. It is designed to be a safer, more predictable alternative to JavaScript for request evaluation and control flow.

    Key Characteristics:

    • Bounded & Predictable: Runs with strict step limits; cannot perform network operations or file writes (except via json.file if enabled).
    • Safe: Avoids arbitrary evaluation and does not expose system APIs.
    • Debuggable: Errors provide file, line, and column information with a call stack.

    When to use RTS vs JavaScript:

    • Use RTS for template values ({{= expr }}), request/workflow control directives (@when, @skip-if, @if, @switch, @for-each), assertions (@assert), and reusable .rts modules.
    • Use JavaScript only when you require full language features or are porting complex existing logic.
  4. Route traffic via SSH tunnels or Kubernetes port-forwards

    main

    Resterm allows routing HTTP, gRPC, WebSocket, and SSE traffic through remote infrastructure using profiles:

    • SSH Tunnels: Use @ssh profiles to route traffic through bastions.
    • Kubernetes: Use @k8s profiles to target pods, services, deployments, or statefulsets via port-forwarding.
  5. Configure request body content

    main

    Resterm supports several methods for defining the body of a request:

    • Inline: Standard body content following the blank line after headers.
    • External file: Use < ./path/to/file.json to load a file relative to the request file. To search the workspace root, set the environment variable RESTERM_ENABLE_FALLBACK=1.
    • Inline includes: Use @ path/to/file inside the body to replace that line with the file's contents (useful for multi-part templates).
    • Forced inline: If a literal body line looks like a file reference (e.g., < this is a string), use # @body inline or # @body raw to prevent Resterm from attempting to load it as a file.
  6. Use metadata comments for request configuration

    main

    You can attach metadata to requests using comments (#, //, or --) placed immediately above the HTTP method. Common metadata keys include:

    • @name <name>: Assigns a specific name to the request.
    • @tag <tag>: Assigns tags to the request (e.g., for filtering or grouping in smoke tests).

    Example:

    ### Users
    # @name listUsers
    # @tag users smoke
    GET {{apiUrl}}/users
    Accept: application/json
  7. Understand variable resolution order

    main

    When expanding {{variable}} templates, Resterm resolves variables in the following priority (from highest to lowest):

    1. File constants (@const)
    2. Script-set values (vars.set in pre-request or test scripts)
    3. Request-scope variables (@var request, @capture request)
    4. Runtime globals (stored via captures or scripts, per environment)
    5. Document globals (@global, @var global)
    6. File scope declarations and @capture file values
    7. Selected environment JSON
    8. OS environment variables (case-sensitive, with an uppercase fallback)

    Dynamic Helpers

    Resterm provides built-in helpers for common dynamic values:

    • {{$uuid}} or {{$guid}}: A unique identifier.
    • {{$timestamp}}: Unix seconds.
    • {{$timestampMs}}: Unix milliseconds.
    • {{$timestampISO8601}}: ISO 8601 formatted timestamp.
    • {{$randomInt}}: A random integer.

    Timestamp Offsets

    Timestamp helpers support offsets using standard Go duration units plus d (days) and w (weeks):

    • {{$timestamp + 6d}}
    • {{$timestampISO8601 - 90m}}
    • {{$timestampMs + 2h}}
  8. Understand Resterm response history and diffing

    main

    Resterm automatically records successful requests into a history database.

    Key History Features:

    • Automatic Masking: Sensitive headers (e.g., Authorization, X-API-Key, X-Access-Token) and values captured via -secret are masked in logs unless you explicitly use the @log-sensitive-headers directive.
    • Environment Awareness: History entries are tied to specific environments. Switching environments filters the history list. If a selected group or profile no longer exists, Resterm shows a warning and prevents immediate resending to avoid accidental execution with incorrect credentials.
    • Navigation: In the history list, press Enter to load a request into the editor without sending it. Use r or Ctrl+R (or your configured send shortcut) to replay a loaded entry.
    • Regression Analysis: The Diff tab allows you to compare a focused pane against a pinned pane. For COMPARE method runs, Resterm stores the specific group, target profile, and selection used, allowing you to audit deltas offline.
  9. Configure Mock Servers in request files

    main

    Resterm allows you to declare mock servers directly within your .http files using @mock directives. This enables you to mimic API behavior alongside your actual requests.

    Key Features

    • Matching: Match requests by method, path, query, headers, or JSON body.
    • Sequences: Model polling or retry flows with response sequences.
    • Dynamic Data: Build responses using generators for path, query, header, and body values.
    • Verification: Use @expect to verify call counts.

    Example: Multiple scenarios on one route

    In the example below, the first mock is the default response, while the second is triggered only when specific query, header, and JSON body conditions are met.

    ### Payment accepted
    # @mock method=POST path=/payments name=accepted default=true latency=150ms
    HTTP/1.1 202 Accepted
    Content-Type: application/json
    
    {"id":"pay_123","status":"pending"}
    
    ### Payment declined
    # @mock method=POST path=/payments name=declined
    # @match query={"mode":"decline"} headers={"X-Tenant":"demo"} json={"amount":0}
    HTTP/1.1 422 Unprocessable Entity
    Content-Type: application/json
    
    {"error":"amount must be positive"}

    Running the Mock Server

    You can serve a single file or a directory recursively:

    # Serve a single file
    resterm mock ./requests.http
    
    # Serve a directory recursively on a specific address
    resterm mock --recursive --addr 127.0.0.1:9090 ./requests
    ### Payment accepted
    # @mock method=POST path=/payments name=accepted default=true latency=150ms
    HTTP/1.1 202 Accepted
    Content-Type: application/json
    
    {"id":"pay_123","status":"pending"}
    
    ### Payment declined
    # @mock method=POST path=/payments name=declined
    # @match query={"mode":"decline"} headers={"X-Tenant":"demo"} json={"amount":0}
    HTTP/1.1 422 Unprocessable Entity
    Content-Type: application/json
    
    {"error":"amount must be positive"}
  10. Use the RestermScript (RTS) Standard Library

    main

    RestermScript (RTS) provides a standard library for common request needs like string manipulation, math, and data transformation. The library is primarily accessed via the rts namespace. Core namespaces like crypto, base64, url, time, json, headers, and query are also available at the top level for convenience.

    Note: stdlib is a deprecated alias for rts. While core helpers are top-level, specific utility namespaces like text, list, dict, and math must be accessed through rts (e.g., rts.text.lower()).

  11. Implement Response Sequences with sequence-key

    main

    A response sequence allows a single route to return multiple different responses in order. Responses in a sequence are separated by a line containing exactly ---.

    Syntax:

    ### Poll payment
    # @mock method=GET path=/payments/{id} sequence=polling sequence-key=path.id
    HTTP/1.1 503 Service Unavailable
    
    {"status":"pending"}
    ---
    HTTP/1.1 503 Service Unavailable
    
    {"status":"pending"}
    ---
    HTTP/1.1 200 OK
    
    {"status":"completed"}

    Key Concepts:

    • Cursors: Without sequence-key, the cursor is global to the scenario. With sequence-key, callers advance independently based on a specific value (e.g., path.id, query.job, header.X-Correlation-ID, or cookie.session).
    • Looping: Once the final response is reached, the sequence repeats forever.
    • Resetting: You can reset cursors via CLI or TUI:
      • resterm mock reset (resets all cursors)
      • resterm mock reset polling (resets cursors for a specific sequence name)

    Note: Use file-backed bodies if your payload must contain the --- delimiter.

    ### Poll payment
    # @mock method=GET path=/payments/{id} sequence=polling sequence-key=path.id
    HTTP/1.1 503 Service Unavailable
    Retry-After: 1
    
    {"status":"pending"}
    ---
    HTTP/1.1 503 Service Unavailable
    Retry-After: 1
    
    {"status":"pending"}
    ---
    HTTP/1.1 200 OK
    
    {"status":"completed"}