### Install httpyac CLI Source: https://github.com/anweber/httpyac/blob/main/README.md Install the httpyac CLI globally using npm or run it via Docker. Verify the installation by checking the version. ```shell npm install -g httpyac httpyac --version ``` ```shell docker run -it -v ${PWD}:/data ghcr.io/anweber/httpyac:latest --version ``` -------------------------------- ### Basic HTTP GET Request with Authentication Source: https://github.com/anweber/httpyac/blob/main/README.md Example of a basic GET request using httpyac syntax. It demonstrates variable definition and basic authentication using environment variables. ```http @user = doe @password = 12345678 GET https://httpbin.org/basic-auth/{{user}}/{{password}} Authorization: Basic {{user}} {{password}} ``` -------------------------------- ### Install and Use httpyac CLI Source: https://context7.com/anweber/httpyac/llms.txt Install httpYac globally and use the `httpyac send` command to execute HTTP requests from files. Supports various options for environment selection, variable injection, output formatting, and filtering. ```bash # Install globally npm install -g httpyac # Send all requests in a file httpyac send requests.http --all # Send with a named environment and inline variables httpyac send requests.http --env production --var baseUrl=https://api.example.com # Send by request name httpyac send requests.http --name "Get User" # Send by line number httpyac send requests.http --line 12 # Send with tag filter httpyac send requests.http --tag smoke # Output full request/response exchange httpyac send requests.http --all --output exchange # Output only response body, suppress logs httpyac send requests.http --all --output body --silent # Output JSON results (CI-friendly) httpyac send requests.http --all --json # Output JUnit XML results httpyac send requests.http --all --junit # Repeat requests in parallel 5 times httpyac send requests.http --name "Load Test" --repeat 5 --repeat-mode parallel # Send requests in parallel from multiple files httpyac send "tests/**/*.http" --all --parallel 4 # Allow self-signed SSL certificates httpyac send requests.http --insecure # Stop on first test failure httpyac send tests.http --all --bail # Interactive mode: select region from menu, loop back after each run httpyac send requests.http --interactive # Filter output to only failed requests httpyac send tests.http --all --filter only-failed --output-failed exchange # Verbose mode httpyac send requests.http --verbose ``` -------------------------------- ### Display httpyac send Command Help Source: https://github.com/anweber/httpyac/blob/main/README.md Get detailed help for the 'send' command, which is used to execute http files. This includes information on arguments and available options for sending requests. ```shell > httpyac help send Usage: httpyac send [options] send/ execute http files Arguments: fileName path to file or glob pattern Options: -a, --all execute all http requests in a http file --bail stops when a test case fails -e, --env list of environments --filter filter requests output (only-failed) --insecure allow insecure server connections when using ssl -i --interactive do not exit the program after request, go back to selection --json use json output --junit use junit xml output -l, --line line of the http requests -n, --name name of the http requests --no-color disable color support -o, --output output format of response (short, body, headers, response, exchange, none) --output-failed output format of failed response (short, body, headers, response, exchange, none) --raw prevent formatting of response body --quiet --repeat repeat count for requests --repeat-mode repeat mode: sequential, parallel (default) --parallel send parallel requests -s, --silent log only request -t, --tag list of tags to execute --timeout maximum time allowed for connections --var list of variables -v, --verbose make the operation more talkative -h, --help display help for command ``` -------------------------------- ### Programmatic API: `createEmptyProcessorContext()` and `getVariables()` Source: https://context7.com/anweber/httpyac/llms.txt Build a full processor context for advanced use cases such as custom variable resolution or programmatic token generation. `getVariables()` can resolve variables for a given environment. ```APIDOC ## Programmatic API: `createEmptyProcessorContext()` and `getVariables()` Build a full processor context for advanced use cases such as custom variable resolution or programmatic token generation. ```typescript import { createEmptyProcessorContext, getVariables, getEnvironments } from 'httpyac'; import { HttpFileStore } from 'httpyac/store'; async function resolveVariablesExample() { const store = new HttpFileStore(); const httpFile = await store.initHttpFile('script.http', { workingDir: process.cwd(), config: { environments: { $shared: { apiHost: 'https://api.example.com' }, dev: { token: 'dev-token-123' }, prod: { token: 'prod-token-xyz' }, }, }, }); // Full variable resolution for 'dev' environment const variables = await getVariables({ httpFile, activeEnvironment: ['dev'], variables: { runtimeVar: 'injected' }, }); // variables => { apiHost: 'https://api.example.com', token: 'dev-token-123', runtimeVar: 'injected', ... } // Build a full processor context (used internally by send()) const context = await createEmptyProcessorContext({ httpFile, activeEnvironment: ['dev'], variables: { overrideToken: 'my-token' }, }); console.log('Full context variables:', context.variables); } resolveVariablesExample(); ``` ``` -------------------------------- ### Using Environments and Overriding Variables Source: https://context7.com/anweber/httpyac/llms.txt Send requests using a specified environment configuration or override variables at runtime. ```bash # Use the staging environment httpyac send requests.http --all --env staging ``` ```bash # Override a variable at runtime httpyac send requests.http --all --env production --var token=override-token ``` -------------------------------- ### Display httpyac CLI Help Source: https://github.com/anweber/httpyac/blob/main/README.md View the main help information for the httpyac CLI, including available options and commands. ```shell > httpyac --help Usage: httpyac [options] [command] httpYac - Quickly and easily send REST, SOAP, GraphQL and gRPC requests Options: -V, --version output the version number -h, --help display help for command Commands: oauth2 [options] generate oauth2 token send [options] send/ execute http files help [command] display help for command ``` -------------------------------- ### Programmatic API: `HttpFileStore` Source: https://context7.com/anweber/httpyac/llms.txt `HttpFileStore` manages parsing, caching, and lifecycle of `HttpFile` instances. It supports incremental updates, renaming, and plugin registration. ```APIDOC ## Programmatic API: `HttpFileStore` `HttpFileStore` manages parsing, caching, and lifecycle of `HttpFile` instances. It supports incremental updates (versioning), renaming, and plugin registration. ```typescript import { HttpFileStore } from 'httpyac/store'; import { promises as fs } from 'fs'; const store = new HttpFileStore({ // Register a custom plugin for all files managed by this store myPlugin: (api) => { api.hooks.onResponse.addHook('logger', async (response) => { console.log(`Response: ${response.statusCode} in ${response.timings?.total}ms`); }); }, }); // Parse or retrieve from cache (version 0) const httpFile = await store.getOrCreate( './api.http', () => fs.readFile('./api.http', 'utf8'), 0, { workingDir: process.cwd() } ); // Invalidate and re-parse after file change (bump version) const updatedFile = await store.getOrCreate( './api.http', () => fs.readFile('./api.http', 'utf8'), 1, // higher version forces re-parse { workingDir: process.cwd() } ); // Get all cached files const allFiles = store.getAll(); console.log('Cached files:', allFiles.map(f => f.fileName)); // Remove a file from cache store.remove('./api.http'); // Rename a cached file entry store.rename('./api.http', './api-v2.http'); // Clear all cached entries store.clear(); ``` ``` -------------------------------- ### Create Processor Context and Resolve Variables Source: https://context7.com/anweber/httpyac/llms.txt Use `createEmptyProcessorContext()` and `getVariables()` for advanced use cases like custom variable resolution or programmatic token generation. Import these functions from 'httpyac' and `HttpFileStore` from 'httpyac/store'. ```typescript import { createEmptyProcessorContext, getVariables, getEnvironments } from 'httpyac'; import { HttpFileStore } from 'httpyac/store'; async function resolveVariablesExample() { const store = new HttpFileStore(); const httpFile = await store.initHttpFile('script.http', { workingDir: process.cwd(), config: { environments: { $shared: { apiHost: 'https://api.example.com' }, dev: { token: 'dev-token-123' }, prod: { token: 'prod-token-xyz' }, }, }, }); // Full variable resolution for 'dev' environment const variables = await getVariables({ httpFile, activeEnvironment: ['dev'], variables: { runtimeVar: 'injected' }, }); // variables => { apiHost: 'https://api.example.com', token: 'dev-token-123', runtimeVar: 'injected', ... } // Build a full processor context (used internally by send()) const context = await createEmptyProcessorContext({ httpFile, activeEnvironment: ['dev'], variables: { overrideToken: 'my-token' }, }); console.log('Full context variables:', context.variables); } resolveVariablesExample(); ``` -------------------------------- ### HTTP Request with Meta Data Annotations Source: https://context7.com/anweber/httpyac/llms.txt Use annotations like `@name`, `@description`, `@ref`, `@sleep`, `@timeout`, `@proxy`, `@disabled`, and `@no-redirect` to control request execution and behavior. The `@import` annotation can be used to include definitions from other files. ```http @baseUrl = https://httpbin.org ### # @name Login # @description Authenticate and capture token POST {{baseUrl}}/post Content-Type: application/json { "username": "alice", "password": "secret" } ``` ```http # @name GetProfile # @ref Login # @title Fetch User Profile # @description Runs Login first, then fetches the profile GET {{baseUrl}}/get Authorization: Bearer {{Login.body.token}} ``` ```http # @name SlowRequest # @sleep 2000 # @timeout 30000 GET {{baseUrl}}/delay/1 ``` ```http # @name ThroughProxy # @proxy http://proxy.internal:8080 GET {{baseUrl}}/get ``` ```http # @name ConditionalRegion # @disabled GET {{baseUrl}}/get ``` ```http # @name NoRedirects # @no-redirect GET {{baseUrl}}/redirect/3 ``` ```http # @name ImportOtherFile # @import ./auth.http # @ref AuthRegion GET {{baseUrl}}/protected ``` -------------------------------- ### Manage HTTP Files with `HttpFileStore` Source: https://context7.com/anweber/httpyac/llms.txt The `HttpFileStore` class manages parsing, caching, and lifecycle of `HttpFile` instances. It supports plugins, incremental updates via versioning, renaming, and clearing the cache. Import `HttpFileStore` from 'httpyac/store'. ```typescript import { HttpFileStore } from 'httpyac/store'; import { promises as fs } from 'fs'; const store = new HttpFileStore({ // Register a custom plugin for all files managed by this store myPlugin: (api) => { api.hooks.onResponse.addHook('logger', async (response) => { console.log(`Response: ${response.statusCode} in ${response.timings?.total}ms`); }); }, }); // Parse or retrieve from cache (version 0) const httpFile = await store.getOrCreate( './api.http', () => fs.readFile('./api.http', 'utf8'), 0, { workingDir: process.cwd() } ); // Invalidate and re-parse after file change (bump version) const updatedFile = await store.getOrCreate( './api.http', () => fs.readFile('./api.http', 'utf8'), 1, // higher version forces re-parse { workingDir: process.cwd() } ); // Get all cached files const allFiles = store.getAll(); console.log('Cached files:', allFiles.map(f => f.fileName)); // Remove a file from cache store.remove('./api.http'); // Rename a cached file entry store.rename('./api.http', './api-v2.http'); // Clear all cached entries store.clear(); ``` -------------------------------- ### Programmatic API: `send()` Source: https://context7.com/anweber/httpyac/llms.txt Use `send()` to execute HTTP regions from parsed `.http` files programmatically. It allows for specifying active environments, custom variables, and logging responses. ```APIDOC ## Programmatic API: `send()` Use httpYac as a Node.js library. Parse `.http` files into `HttpFile` objects and execute regions programmatically. ```typescript import { send, getVariables, getEnvironments } from 'httpyac'; import { HttpFileStore } from 'httpyac/store'; import { promises as fs } from 'fs'; async function main() { const httpFileStore = new HttpFileStore(); // Parse a .http file const httpFile = await httpFileStore.getOrCreate( './requests.http', () => fs.readFile('./requests.http', 'utf8'), 0, { workingDir: process.cwd(), config: { log: { level: 'warn' }, request: { timeout: 10000 }, }, } ); // List available environments const envs = await getEnvironments({ httpFile }); console.log('Available environments:', envs); // Resolve variables for the 'staging' environment const variables = await getVariables({ httpFile, activeEnvironment: ['staging'], }); console.log('Resolved variables:', variables); // Execute all non-global regions const success = await send({ httpFile, activeEnvironment: ['staging'], variables: { extraVar: 'runtime-value' }, logResponse: async (response, httpRegion) => { console.log(`[${httpRegion.symbol.name}] ${response.statusCode}`); }, }); console.log('All succeeded:', success); // Execute a specific named region const namedRegion = httpFile.findHttpRegion('GetUser'); if (namedRegion) { await send({ httpFile, httpRegion: namedRegion, activeEnvironment: ['production'], }); } } main().catch(console.error); ``` ``` -------------------------------- ### Programmatic Configuration with .httpyac.js Source: https://context7.com/anweber/httpyac/llms.txt Configure httpyac hooks and plugins programmatically. Intercept requests or provide custom variables. ```javascript // .httpyac.js — programmatic configuration and plugin hooks module.exports.configureHooks = function (api) { // Intercept every request to add a global header api.hooks.onRequest.addHook('addCorrelation', async (request) => { request.headers = request.headers || {}; request.headers['X-App-Version'] = '2.0.0'; }); // Add a custom variable provider api.hooks.provideVariables.addHook('custom', async (envs) => { return { customVar: 'hello-from-plugin' }; }); }; ``` -------------------------------- ### gRPC Request with Server Reflection Source: https://context7.com/anweber/httpyac/llms.txt Send a gRPC request using server reflection, eliminating the need for a proto file. Use the `@grpc-reflect` tag. ```http ### # gRPC with server reflection (no proto file needed) # @name GrpcReflection # @grpc-reflect GRPC grpc://localhost:50051/mypackage.MyService/MyMethod { "id": 42 } ``` -------------------------------- ### Environment Configuration with http-client.env.json Source: https://context7.com/anweber/httpyac/llms.txt Define environment-specific variables for httpyac requests. Supports shared, default, and named environments. ```json // http-client.env.json — environment-specific variables { "$shared": { "apiVersion": "v2" }, "$default": { "baseUrl": "http://localhost:3000", "token": "dev-token" }, "staging": { "baseUrl": "https://staging.api.example.com", "token": "staging-token" }, "production": { "baseUrl": "https://api.example.com", "token": "prod-token" } } ``` -------------------------------- ### Generate JUnit XML Output with httpyac Source: https://context7.com/anweber/httpyac/llms.txt Use the --junit flag to produce JUnit-compatible XML output, suitable for CI systems. Redirect the output to a file using the '>' operator. ```bash httpyac send tests.http --all --junit > results.xml ``` ```xml AssertionError: status (403) == 204 ``` -------------------------------- ### gRPC Request with Metadata Headers Source: https://context7.com/anweber/httpyac/llms.txt Send a gRPC request including metadata headers like authorization and custom request IDs. ```http ### # gRPC with metadata headers GRPC grpc://secure.example.com/pkg.Service/Method authorization: Bearer {{token}} x-request-id: {{$uuid}} { "query": "test" } ``` -------------------------------- ### WebSocket with Response Handler Source: https://context7.com/anweber/httpyac/llms.txt Connect to a WebSocket server and process streaming messages. The `streaming` block allows for custom logic, and `$cancel` can be used to stop the stream. ```http ### # WebSocket with response handler WS wss://ws.example.com/live { "action": "subscribe", "channel": "prices" } {{streaming const msg = JSON.parse(response.body); if (msg.type === 'price') { console.log('Price update:', msg.data); } // Set $cancel to stop streaming if (msg.type === 'done') { exports.$cancel = true; } }} ``` -------------------------------- ### Generate OAuth2 Token via CLI Source: https://context7.com/anweber/httpyac/llms.txt Generate OAuth2 tokens from the command line without sending an HTTP request. Reads variables from .env files or uses inline --var arguments. ```bash # Generate access token using client_credentials (reads variables from .env) httpyac oauth2 \ --flow client_credentials \ --var oauth2_tokenEndpoint=https://auth.example.com/token \ --var oauth2_clientId=my-client \ --var oauth2_clientSecret=my-secret ``` ```bash # Output full token response as JSON httpyac oauth2 --flow client_credentials --output response ``` ```bash # Output only the refresh token httpyac oauth2 --flow password \ --var oauth2_username=alice \ --var oauth2_password=secret \ --output refresh_token ``` ```bash # Use a named environment from http-client.env.json httpyac oauth2 --flow client_credentials --env staging ``` -------------------------------- ### Basic HTTP Request Definition Source: https://context7.com/anweber/httpyac/llms.txt Define HTTP requests in `.http` files using a plain-text format. Regions are separated by `###`. Variables are declared with `@key = value` and referenced with `{{key}}`. ```http # Variables (file-scoped) @baseUrl = https://httpbin.org @user = alice @password = secret123 ### # @name GetAnything # @description Demonstrates a simple GET with variable substitution GET {{baseUrl}}/get?user={{user}} Accept: application/json ### # @name CreatePost POST {{baseUrl}}/post Content-Type: application/json { "user": "{{user}}", "timestamp": "{{$datetime iso8601}}" } ### # @name UpdateUser PUT {{baseUrl}}/put Content-Type: application/x-www-form-urlencoded user={{user}}&active=true ### # @name DeleteItem DELETE {{baseUrl}}/delete Authorization: Basic {{user}} {{password}} ### # @name HeadCheck HEAD {{baseUrl}}/get ### # GraphQL request POST {{baseUrl}}/post Content-Type: application/graphql query GetUser($id: ID!) { user(id: $id) { name email } } ``` -------------------------------- ### Run httpyac in Docker Source: https://context7.com/anweber/httpyac/llms.txt Execute httpyac commands within a Docker container by mounting the current directory as /data. This allows running tests and using environment variables or generating OAuth2 tokens. ```bash # Execute all requests in the mounted directory docker run -it -v ${PWD}:/data ghcr.io/anweber/httpyac:latest send *.http --all ``` ```bash # With environment and variables docker run -it -v ${PWD}:/data ghcr.io/anweber/httpyac:latest \ send requests.http --env production --var apiKey=abc123 --json ``` ```bash # Generate an OAuth2 token docker run -it -v ${PWD}:/data ghcr.io/anweber/httpyac:latest \ oauth2 --flow client_credentials \ --var oauth2_tokenEndpoint=https://auth.example.com/token \ --var oauth2_clientId=client \ --var oauth2_clientSecret=secret ``` -------------------------------- ### MQTT Publish Request Source: https://context7.com/anweber/httpyac/llms.txt Publish a message to a specified topic on an MQTT broker. ```http ### # @name MqttPublish MQTT mqtt://localhost:1883 topic: sensors/temperature { "value": 22.5, "unit": "C" } ``` -------------------------------- ### Declarative Response Assertions Source: https://context7.com/anweber/httpyac/llms.txt Use the `??` syntax to declaratively assert response properties like status, headers, and body content. A variety of predicates are available for flexible assertions. ```http @baseUrl = https://httpbin.org ### # @name AssertExample GET {{baseUrl}}/get?foo=bar ?? status == 200 ?? header content-type contains application/json ?? body $.url == https://httpbin.org/get?foo=bar ?? body $.args.foo == bar ?? duration < 5000 ``` ```http # @name PostAssert POST {{baseUrl}}/post Content-Type: application/json { "name": "Alice", "age": 30 } ?? status == 200 ?? body $.json.name == Alice ?? body $.json.age isNumber ?? body $.json.age >= 18 ?? body $.json.name startsWith Al ?? body $.json.name matches ^Alice$ ``` -------------------------------- ### HTTP Request with File Body Source: https://context7.com/anweber/httpyac/llms.txt Send binary or multipart payloads by referencing local files in the request body using `< ./path/to/file` for binary or `Content-Type: multipart/form-data` for multipart uploads. ```http @baseUrl = https://httpbin.org ### # @name UploadFile POST {{baseUrl}}/post Content-Type: application/octet-stream < ./path/to/file.bin ### # @name MultipartUpload POST {{baseUrl}}/post Content-Type: multipart/form-data; boundary=boundary --boundary Content-Disposition: form-data; name="field1" value1 --boundary Content-Disposition: form-data; name="file"; filename="report.pdf" Content-Type: application/pdf < ./report.pdf --boundary-- ``` -------------------------------- ### gRPC Unary Request Source: https://context7.com/anweber/httpyac/llms.txt Send a gRPC unary request using a proto file definition. Specify the proto file path with `grpc-proto-file`. ```http ### # @name GrpcUnary # Load proto definition GRPC grpc://localhost:50051/helloworld.Greeter/SayHello grpc-proto-file: ./protos/helloworld.proto { "name": "World" } ``` -------------------------------- ### Looping HTTP Requests Source: https://context7.com/anweber/httpyac/llms.txt Control request repetition using `# @loop` with `for`, `for...of`, or `while` semantics. Variables like `$index` and custom loop variables are available within the request. ```http @baseUrl = https://httpbin.org ### # @name RepeatFixed # @loop for 3 POST {{baseUrl}}/post Content-Type: application/json { "iteration": "{{$index}}" } ``` ```http # @name RepeatForOf # @loop for item of items # items must be a variable holding an array POST {{baseUrl}}/post Content-Type: application/json { "value": "{{item}}", "index": "{{$index}}" } {{ const items = ['alpha', 'beta', 'gamma']; }} ``` ```http # @name RepeatWhile # @loop while counter < 3 GET {{baseUrl}}/get?n={{counter}} {{ let counter = 0; // increment counter in response hook }} {{response counter++; }} ``` -------------------------------- ### Generate JSON Output with httpyac Source: https://context7.com/anweber/httpyac/llms.txt Use the --json flag to emit a structured JSON object containing per-request results and an aggregate summary. The output can be redirected to a file using --output. ```bash httpyac send tests.http --all --json --output exchange ``` ```json { "_meta": { "version": "1.1.0" }, "summary": { "totalRequests": 3, "successRequests": 2, "failedRequests": 1, "erroredRequests": 0, "skippedRequests": 0, "totalTests": 6, "successTests": 5, "failedTests": 1, "erroredTests": 0, "skippedTests": 0 }, "requests": [ { "fileName": "/project/tests.http", "name": "GetUser", "line": 3, "title": "Fetch a user by ID", "timestamp": "2025-04-01T10:00:00.000Z", "duration": 142, "summary": { "totalTests": 2, "successTests": 2, "failedTests": 0, "erroredTests": 0, "skippedTests": 0 }, "response": { "statusCode": 200, "headers": { "content-type": "application/json" }, "body": "{ \"id\": 1, \"name\": \"Alice\" }" }, "testResults": [ { "message": "status == 200", "status": "SUCCESS" }, { "message": "body $.name == Alice", "status": "SUCCESS" } ] } ] } ``` -------------------------------- ### Execute HTTP Requests Programmatically with `send()` Source: https://context7.com/anweber/httpyac/llms.txt Use the `send()` function to parse `.http` files and execute regions programmatically. It allows specifying active environments, custom variables, and logging responses. Ensure necessary imports from 'httpyac' and 'httpyac/store'. ```typescript import { send, getVariables, getEnvironments } from 'httpyac'; import { HttpFileStore } from 'httpyac/store'; import { promises as fs } from 'fs'; async function main() { const httpFileStore = new HttpFileStore(); // Parse a .http file const httpFile = await httpFileStore.getOrCreate( './requests.http', () => fs.readFile('./requests.http', 'utf8'), 0, { workingDir: process.cwd(), config: { log: { level: 'warn' }, request: { timeout: 10000 }, }, } ); // List available environments const envs = await getEnvironments({ httpFile }); console.log('Available environments:', envs); // Resolve variables for the 'staging' environment const variables = await getVariables({ httpFile, activeEnvironment: ['staging'], }); console.log('Resolved variables:', variables); // Execute all non-global regions const success = await send({ httpFile, activeEnvironment: ['staging'], variables: { extraVar: 'runtime-value' }, logResponse: async (response, httpRegion) => { console.log(`[${httpRegion.symbol.name}] ${response.statusCode}`); }, }); console.log('All succeeded:', success); // Execute a specific named region const namedRegion = httpFile.findHttpRegion('GetUser'); if (namedRegion) { await send({ httpFile, httpRegion: namedRegion, activeEnvironment: ['production'], }); } } main().catch(console.error); ``` -------------------------------- ### WebSocket Echo Request Source: https://context7.com/anweber/httpyac/llms.txt Connect to a WebSocket server and send a message. The `@keepStreaming` tag is used to keep the connection open. ```http ### # @name WsEcho # @keepStreaming WS wss://echo.websocket.org Content-Type: text/plain Hello, WebSocket! ``` -------------------------------- ### AMQP Publish Request Source: https://context7.com/anweber/httpyac/llms.txt Publish a message to an exchange with a specified routing key using the AMQP protocol. ```http ### # @name AmqpPublish AMQP amqp://localhost:5672 exchange: my-exchange routing-key: orders.new { "orderId": "ORD-001", "amount": 99.99 } ``` -------------------------------- ### MQTT Subscribe Request with Streaming Source: https://context7.com/anweber/httpyac/llms.txt Subscribe to an MQTT topic and process streaming messages. The `@keepStreaming` tag is used, and the `streaming` block handles received messages. ```http ### # @name MqttSubscribe # @keepStreaming MQTT mqtt://localhost:1883 topic: alerts/# {{streaming console.log('MQTT message received:', response.body); if (JSON.parse(response.body).level === 'critical') { exports.$cancel = true; } }} ``` -------------------------------- ### AMQP Consume Request with Streaming Source: https://context7.com/anweber/httpyac/llms.txt Consume messages from an AMQP queue and process them. The `streaming` block handles received messages, and `$cancel` can be used to stop consumption. ```http ### # @name AmqpConsume # @keepStreaming AMQP amqp://guest:guest@localhost:5672 queue: order-events {{streaming console.log('Received:', response.body); exports.$cancel = true; // stop after first message }} ``` -------------------------------- ### Variable Declaration and Lazy Variables Source: https://context7.com/anweber/httpyac/llms.txt Declare variables using `@key = value` for eager evaluation or `@key := value` for lazy evaluation. Lazy variables defer evaluation until runtime and can reference other variables or JavaScript expressions. ```http # Eager variable — evaluated at parse time @host = https://api.example.com # Lazy variable — evaluated at runtime, can reference other variables @token := {{oauth2Token}} # JavaScript expression variable @timestamp := {{$datetime iso8601}} # Global variable — shared across all regions in the file @global.requestId = abc-123 ### GET {{host}}/users Authorization: Bearer {{token}} X-Request-ID: {{requestId}} ``` -------------------------------- ### Inline JavaScript for Request Scripting Source: https://context7.com/anweber/httpyac/llms.txt Embed Node.js code within `{{ ... }}` blocks for pre-request or post-response scripting. Scripts have access to request, response, and other runtime variables. Use `exports` to expose variables to subsequent scripts or requests. ```javascript @baseUrl = https://httpbin.org ### # Pre-request script: set a dynamic variable {{ const now = new Date().toISOString(); exports.requestTime = now; exports.correlationId = `req-${Math.random().toString(36).slice(2)}`; }} # @name DynamicRequest POST {{baseUrl}}/post Content-Type: application/json X-Correlation-ID: {{correlationId}} { "time": "{{requestTime}}" } # Post-response script {{response const body = JSON.parse(response.body); test('status is 200', () => { response.statusCode === 200; }); exports.echoedTime = body.json?.time; console.log('echoed time:', body.json?.time); }} ``` ```javascript # Script fires on every request in this file (+ prefix) {{+ console.log('About to send:', request?.url); }} ``` ```javascript # Script fires after execution (after event) {{after console.log('Finished. Echoed time was:', echoedTime); }} ``` -------------------------------- ### OAuth2 Authorization Header Source: https://context7.com/anweber/httpyac/llms.txt Configure OAuth2 authentication by setting the `Authorization` header with the `oauth2` scheme. HttpYac automatically handles token acquisition, caching, and refreshing for various flows like `client_credentials`, `password`, and `authorization_code`. ```http # Variables for OAuth2 (can also be in .env or http-client.env.json) @oauth2_tokenEndpoint = https://auth.example.com/oauth/token @oauth2_clientId = my-client @oauth2_clientSecret = my-secret @oauth2_scope = openid profile ### # @name ClientCredentials # Token fetched automatically via client_credentials flow GET https://api.example.com/protected Authorization: oauth2 client_credentials ``` ```http # @name PasswordFlow GET https://api.example.com/profile Authorization: oauth2 password # Variables for password flow @oauth2_username = alice @oauth2_password = secret ``` ```http # @name AuthCodeFlow # Opens browser for interactive login GET https://api.example.com/me Authorization: oauth2 authorization_code ``` ```http # Multiple OAuth2 prefixes for different servers @server1_tokenEndpoint = https://auth1.example.com/token @server1_clientId = client1 @server1_clientSecret = secret1 @server2_tokenEndpoint = https://auth2.example.com/token @server2_clientId = client2 @server2_clientSecret = secret2 GET https://api1.example.com/data Authorization: oauth2 client_credentials server1 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.