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 environment, 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 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.
name | description | condition | example |
---|---|---|---|
amqpClient | currently active AMQP Client | if amqp client is active | consumeScript.http |
amqpChannel | currently active AMQP Channel | if amqp client is active | consumeScript.http |
grpcStream | currently active Grpc Writable Stream | only if grpc stream is active | grpcClientStreaming.http |
httpFile | current httpFile | - | scriptVariablesHttpFile.http |
httpRegion | current httpRegion | - | scriptVariablesHttpRegion.http |
mqttClient | currently active MQTT Client | only if mqtt client is active | mqttPublish.http |
oauth2Session | OAuth2 Response | only if OAuth2/ OpenId Connect is used | scriptVariablesOAuthSession.http |
request | request of the next http request | - | custom.http |
response | http response of the last executed request | only use it in post request scripts or for responses imported with @forceRef | websocket.http |
sleep | Method to wait for a fixed period of time | - | grpcClientStreaming.http |
test | method to simplify tests (assert or chai) | - | test.http |
websocketClient | currently active Websocket Client | if websocket client is active | websocket.http |
__dirname | path to current working directory | - | - |
__filename | The file name of the current module. | - | - |
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 vscode, got, grpc-js and httpYac Dependency, which are provided from the extension.
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.
@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 methods 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.
Events | Description |
---|---|
request | event triggered before every request (but after replaceVariableHook) |
streaming | event triggered while client streaming |
response | event triggered on response of request |
responseLogging | event triggered on output of response, used for altering output which is provided with variable response |
after | event 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
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.
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
- Install httpYac cli with
npm install httpyac -g
- open Http File in VS Code
- add debugger; statement in script
- open Javascript Debug Terminal in VS Code
- 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}}