Scripts

Scripts let you run JavaScript around a request. Use a Pre-Script to prepare the request and a Post-Script to check the response, write tests, or save values for the next request.

#

Open the script editor

  1. Open an endpoint and go to the Script tab.
  2. Choose Pre-Script or Post-Script.
  3. Write your code in the editor, or click an item in the Snippets list on the right to insert it.
  4. Save the endpoint. Scripts run every time you click Send.
Script Runs Typical uses
Pre-Script Before the request is sent Add or remove headers, change the URL, set timestamps or IDs, read environment variables
Post-Script After the response arrives Test status and body, read response headers, save tokens to the environment
#

The hm object

Scripts use the hm object to reach the request, the response and the environment.

Code What it does
hm.environment.get("key") Read a variable from the selected environment
hm.environment.set("key", "value") Create or update a variable
hm.environment.unset("key") / hm.environment.clear() Remove one variable / all variables
hm.environment.has("key") Check that a variable exists
hm.request.url, hm.request.method, hm.request.body Read the request
hm.request.headers.add("key", "value") Add a header
hm.request.headers.remove("key"), .has("key"), .getHeaders() Manage headers
hm.response.status, hm.response.body Read the response (Post-Script only)
hm.response.headers.getHeaders() Read response headers (Post-Script only)
hm.test("name", fn) Define a test

You can also use expect (Chai assertions), _ (Lodash), moment (date helpers) and console.log.

#

Example: add a signed header

const timestamp = Date.now().toString();
hm.environment.set("requestTime", timestamp);
hm.request.headers.add("X-Request-Time", timestamp);
#

Example: test the response and save a token

hm.test("Status code is 200", () => {
  expect(hm.response.status).to.equal(200);
});

hm.test("Returns a token", () => {
  expect(hm.response.body).to.have.property("access_token");
});

hm.environment.set("token", hm.response.body.access_token);

Use the token in another request with Authorization: Bearer {{token}}.

#

See the results

  • Test Results in the response panel lists each test as passed or failed, with a summary such as (2/2 Passed).
  • Console shows console.log output. Switch between Pre-Script and Post-Script to see each one.
  • If a script has an error, DocStar shows the error message under the request.

See Responses and Cookies.

#

Limits and tips

  • Select an environment before you send. Without one, hm.environment.set changes are not saved.
  • Scripts change a variable's Current value, not its Initial value.
  • A Pre-Script can change the URL and headers. To change the body, use {{variables}} in the body and set them in the Pre-Script.
  • Scripts run only in the DocStar editor. They don't run when readers click TRY on your published docs.
  • Scripts are saved with the endpoint, so don't hard-code secrets in them.