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.

{{
  //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 HTTP/1.1
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 environmentopen in new window, but there may be variations. These can be bypassed using require.

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.

{{
  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}} HTTP/1.1

Access to Variables

All Variables already defined can be accessed via the global objectopen in new window.

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 Globalopen in new window, the following values are also set on global object.

namedescriptionconditionexample
amqpClientcurrently active AMQP Clientopen in new windowif amqp client is activeconsumeScript.httpopen in new window
amqpChannelcurrently active AMQP Channelopen in new windowif amqp client is activeconsumeScript.httpopen in new window
grpcStreamcurrently active Grpc Writable Streamopen in new windowonly if grpc stream is activegrpcClientStreaming.httpopen in new window
httpFilecurrent httpFileopen in new window-scriptVariablesHttpFile.httpopen in new window
httpRegioncurrent httpRegionopen in new window-scriptVariablesHttpRegion.httpopen in new window
mqttClientcurrently active MQTT Clientopen in new windowonly if mqtt client is activemqttPublish.httpopen in new window
oauth2SessionOAuth2 Responseopen in new windowonly if OAuth2/ OpenId Connect is usedscriptVariablesOAuthSession.httpopen in new window
requestrequest of the next http requestopen in new window-custom.httpopen in new window
responsehttp responseopen in new window of the last executed requestonly use it in post request scripts or for responses imported with @forceRefwebsocket.httpopen in new window
sleepMethodopen in new window to wait for a fixed period of time-grpcClientStreaming.httpopen in new window
testmethod to simplify testsopen in new window (assertopen in new window or chaiopen in new window)-test.httpopen in new window
websocketClientcurrently active Websocket Clientopen in new windowif websocket client is activewebsocket.httpopen in new window
__dirnamepath to current working directoryopen in new window--
__filenameThe file name of the current module.open in new window--

Require

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


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

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

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


 









TIP

External dependencies must be installed independently, exceptions are vscodeopen in new window, gotopen in new window, grpc-jsopen in new window and httpYacopen in new window Dependency, which are provided from the extension.

WARNING

NodeJSopen in new window 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.

@foo = https://httpbin.org

{{
  console.info(foo);
}}

Test

You can write easily test scripts in JavaScript. Tests allow you to ensure that your API is working as expected, to establish that integrations between services are functioning reliably, and to verify that new developments haven't broken any existing functionality. You can also use test code to aid the debugging process when something goes wrong with your API project.


GET https://httpbin.org/json HTTP/1.1
{{
  const { equal } = require('assert');
  test('status code 200', () => {
    equal(response.statusCode, 200);
  });
}}

GET https://httpbin.org/json HTTP/1.1

{{
  const { expect } = require('chai');
  test('status code 200', () => {
    expect(response.statusCode).to.equal(200)
  });
}}

TIP

Auxiliary methodsopen in new window are provided for standard tests such as Status and Content-Type


GET https://httpbin.org/json HTTP/1.1
{{
  test.status(200);
}}

Global Scripts

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

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

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.

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



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 +.

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





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

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

 






events

Intellij Script

Intellij Scripts are supported. An Http clientopen in new window and responseopen in new window 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.

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

email=user@domain.loc&password=2

> ./intellij.js

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

email=user@domain.loc&password=3

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

WARNING

Intellij scripts are always executed after request. Scripts before Request Line are ignored

How to debug scripts

  1. Install httpYac cli with npm install httpyac -g
  2. open Http File in VS Code
  3. add debugger;open in new window statement in script
  4. open Javascript Debug Terminalopen in new window in VS Code
  5. execute command httpyac <file> -l <line>
{{
  //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 HTTP/1.1
Date: {{authDate}}
Authentication: {{authentcation}}






 






Last Updated: