Skip to content

Scripting

It is possible to use NodeJS scripts. All scripts before the request line are executed before the request is called. All scripts after the request line are executed as soon as the response is received. All exports of the script are stored as variables.

HTTP
{{
  //pre request script
  const crypto = require('crypto');
  const date = new Date();
  const signatureBase64 = crypto.createHmac('sha256', 'secret')
  .update(`${request.method}\u2028${request.url}\u2028${date.getTime()}`).digest("base64");
  exports.authDate = date.toUTCString();
  exports.authentcation = `Basic ${signatureBase64}`;
}}
GET https://httpbin.org/anything
Date: {{authDate}}
Authentication: {{authentcation}}

{{
  // post request script
  const assert = require('assert');
  test("authentcation is valid", () => {
    assert.equal(response.parsedBody.headers.Authentication, authentcation);
  });
}}

WARNING

Scripts are executed in a custom context/ execution environment. This context should behave identically to NodeJS Default execution environment, but there may be variations. These can be bypassed using require.

WARNING

The line break after '{{' is important to distinguish between script execution and variable substitution/ templating.

Async/Await or Promise

If the execution of the script is async, it is necessary to export this Promise. In this case, the program waits for the Promise to be completed.

HTTP
{{
  async function wait(){
    const date = new Date();
    await sleep(10000);
    const afterDate = new Date();
    return afterDate.getTime() - date.getTime();
  }
  exports.wait = wait();
}}
GET https://httpbin.org/anything?delay={{wait}}

Access to Variables

All Variables already defined can be accessed via the global object.

WARNING

Since all variables are placed on the global scope of the script, they may overwrite other variables. Please use unique variable names

In addition to the defined variables and NodeJS Global, the following values are also set on global object.

namedescriptionconditionexample
$globalObject which allows storing global VariablesglobalVariables.http
$requestClientrequestClient to send additional body in streaming event.requestClient.http
httpFilecurrent httpFile-scriptVariablesHttpFile.http
httpRegioncurrent httpRegion-scriptVariablesHttpRegion.http
oauth2SessionOAuth2 Responseonly if OAuth2/ OpenId Connect is usedscriptVariablesOAuthSession.http
requestrequest of the next http request-custom.http
responsehttp response of the last executed requestonly use it in post request scripts or for responses imported with @forceRefwebsocket.http
sleepMethod to wait for a fixed period of time-grpcClientStreaming.http
testmethod to simplify tests (assert or chai)-test.http
__dirnamepath to current working directory--
__filenameThe file name of the current module.--

Require

External scripts can be imported using require, but you need to install dependencies yourself.

HTTP

{{
  const { authenticate } = require('./scriptRequire.cjs');
  const authDate = new Date();

  exports.authDate = authDate.toUTCString();
  exports.authentication = authenticate(authDate, request);
}}

GET https://httpbin.org/anything
Authentication: {{authentication}}
Date: {{authDate}}

TIP

External dependencies must be installed independently, exceptions are , , and Dependency, which are provided from the extension.

External dependencies must be installed independently, but some dependencies are provided from httpyac:

WARNING

NodeJS caches all loaded scripts. Since in VS Code the script is executed in the context of the extension, the content of the script is not reloaded. Therefore, the script must be manually removed from the cache.

Console

The console cannot be accessed in VS Code. Therefore, a separate Console object is provided in the context of the script that redirects the output to the OutputChannel.

HTTP
@foo = https://httpbin.org

{{
  console.info(foo);
}}

Open the OutputChannel by pressing CTRL+K followed by CTRL+H, then select httpyac - Console from the select on the right.

Global Scripts

Scripts with no request in the same region are always executed (Global Scripts).

HTTP
{{
  console.info('on every run')
}}
###
GET https://httpbin.org/json
GET https://httpbin.org/json

Events

The normal script registration is executed in order of occurrence in http File. For the execution of a request, several steps have to be executed besides the actual request: Replace Variables, Prepare Body, Pretty Print Body. With events scripts can be hooked into concrete steps in this process.

HTTP
{{@response
  console.info("on every request");
}}
GET https://httpbin.org/json

The following events are possible.

EventsDescription
requestevent triggered before every request (but after replaceVariableHook)
streamingevent triggered while client streaming
responseevent triggered on response of request
responseLoggingevent triggered on output of response, used for altering output which is provided with variable response
afterevent triggered after all request is sent

TIP

The events can be registered automatically globally using +.

HTTP
{{+after
  console.info(`on every request: ${response.statusCode}`);
}}
###
GET https://httpbin.org/json
GET https://httpbin.org/json

If no event is specified for global registration, the script is executed before every request.

HTTP
{{+
  console.info("on every request");
}}
###
GET https://httpbin.org/json
GET https://httpbin.org/json

events

Dynamic canceling current execution

It is possible to interrupt the execution of the current HttpRegion directly. If a script exports a variable $cancel, the further execution of the current HttpRegion is canceled.

HTTP
{{
  exports.$cancel = true;
}}
GET https://httpbin.org/json

Intellij Script

Intellij Scripts are supported. An Http client and response object corresponding to the interface is created and are available in the script.

WARNING

The execution environment differs between NodeJS and Intellij (uses Nashorn). Possibly the behavior is not completely identical, to Intellij Execution. If there are problems, please let me know.

HTTP
POST https://httpbin.org/anything
Content-Type: application/x-www-form-urlencoded
accept: application/json

email=user@domain.loc&password=2

> ./intellij.js

POST https://httpbin.org/anything
Content-Type: application/x-www-form-urlencoded
accept: application/json

email=user@domain.loc&password=3

> {% client.global.set("email", response.body.form.email); %}

How to debug scripts

  1. Install httpYac cli with npm install httpyac -g
  2. open Http File in VS Code
  3. add debugger; statement in script
  4. open Javascript Debug Terminal in VS Code
  5. execute command httpyac <file> -l <line>
HTTP
{{
  //pre request script
  const crypto = require('crypto');
  const date = new Date();
  const signatureBase64 = crypto.createHmac('sha256', 'secret')
  .update(`${request.method}\u2028${request.url}\u2028${date.getTime()}`).digest("base64");
  debugger;
  exports.authDate = date.toUTCString();
  exports.authentcation = `Basic ${signatureBase64}`;
}}
GET https://httpbin.org/json
Date: {{authDate}}
Authentication: {{authentcation}}