Pre- and post-execution scripts for HTTP monitors

Dynatrace 1.174+

When executing a complex API request, pre- and post-scripting enable you to add logic between the HTTP monitor steps (for example, skipping a request under certain conditions, adding a header, modifying body content, or modifying a URL). The scripts are based on custom JavaScript code that's run before and after each HTTP request is executed. You can also set values in your scripts and pass them as variables between requests.

How to define pre- and post-script execution

Edit the request and enable the pre- or post-script execution to display the code editor box. While you type, the editor displays inline help with a short descriptions of the available methods. You can also add the scripts using script mode. Simply add the script as the value of the preProcessingScript or postProcessingScript objects. However, with this approach, you won't be able to use the inline method helper and have to escape all the JSON characters and break lines with /n.

Pre- and post-execution scripts have direct access only to the data retrieved as the result of the current request. In other words, the response details are available only within the same request’s post- execution script. To pass the information to a different request within the same monitor, use a variable instead.

Passing variables

The variables can be passed only in the context of a single execution of an HTTP monitor. You should also make sure that when you refer to a variable, the data behind it is logically available to the monitor. For example, if you set a variable based on the data retrieved from the response body, you can't refer to it in the pre-execution script, because at this moment, this content doesn't exist yet. See the example below on how to set the variable and retrieve it using api.setValue and api.Getvalue methods.

After you set a variable using the api.setValue method, you can apply its value in other HTTP monitor request configuration fields using the {variable_name} convention. The UI will inform you whenever this is possible.

Passing variables

Example monitor

In this example, we perform an OAuth2 authorization using pre- and post-execution scripts that retrieve and apply the token.

The monitor is composed of two requests. The first one retrieves the access token and the post-execution script saves it as a bearerToken variable. Then, we run the second request where the pre-execution script adds the value of the bearerToken variable to the request authorization header.

Request 1

Request URL: https://somesite.com/sso/oauth2/access_token?realm=/somename
HTTP method: POST
Post-execution script:

if (response.getStatusCode() != 200) {
    api.fail("HTTP error: " + response.getStatusCode());
}
var responseBody = response.getResponseBody();
var jsonData = JSON.parse(responseBody);
api.setValue("bearerToken", jsonData.access_token);
api.info(jsonData.access_token);

Additional HTTP headers:
Content-Type: application/x-www-form-urlencoded
Request body:

scope=openid%20read&client_secret=somesecret&grant_type=password&username=user%40somesite%2Ecom&password=password123&client_id=clientid

Request 2

Request URL: https://account.somesite.com/rest/user/user%40somesite%2Ecom?
HTTP method: GET
Pre-execution script:

request.addHeader("Authorization", "Bearer " + api.getValue("bearerToken"));

Full monitor script

Download

Method reference

When writing your scripts, you can use the following methods in your JavaScript code. The script editor has a built-in, type-ahead syntax guide and syntax check.

Store and retrieve values across events (steps)

  • api.setValue(key, value)—Sets a local value.
  • api.getValue(key)—Gets the local value of the key that had been previously set by api.setValue.
  • api.getValues—Returns an object holding the key-value pairs that had been previously set by api.setValue.

Mark events as failed or finished

  • api.fail(message)—Marks the event as failed, providing a message as the reason and marks the test execution as failed.
  • api.finish()—Finishes the JavaScript event so that the next event is executed.

Skip synthetic events

  • api.skipNextSyntheticRequest()—Skips execution of the next request.
  • api.skipNextSyntheticRequests(n)—Skips execution of the next n consecutive requests.
  • api.skipSyntheticRequest(requestIndex)—Skips execution of the request with the index requestIndex.
  • api.skipSyntheticRequests(requestIndexes)—Skips execution of multiple events; the Int32Array of the request indexes specifies the indexes of the events to skip.

Basic logging

  • api.info(message)—Logs the message using the info log level.
  • api.warn(message)—Logs the message using the warning log level.
  • api.error(message)—Logs the message using the error log level.

Basic Encoding

  • api.urlEncode(url)—Converts a string to the application/x-www-form-urlencoded MIME format.
  • api.base64UrlEncode(urlToEncode)—Encodes input using base64url encoding.
  • api.HMACSHA256(message, secret)—Creates base64 hash using HMAC SHA256.
  • api.btoa(value)—Creates a base64-encoded ASCII string from a string of binary data.

Random value generating

  • api.randomNextInt()—Returns a pseudorandom, uniformly distributed int value.
  • api.randomNextIntWithBound(value)—Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive).
  • api.randomNextFloat()—Returns a pseudorandom, uniformly distributed float value.
  • api.randomNextLong()—Returns a pseudorandom, uniformly distributed long value.
  • api.randomString(numberOfChars, supportedChars)—Creates a random string whose length is the number of characters; the characters are chosen from the set of characters specified as a string.

Date formatting

  • api.dateToFormat(timestamp, format)—Returns the given timestamp using the given pattern.
  • api.date()—Returns the current date.

Monitor data

  • api.UUID()—Returns a universally unique identifier.

Pre-execution script methods

These methods are request specific, so you can only use them for pre-execution scripts.

  • request.addHeader(key,value)—Adds the request header.
  • request.setUrl(URL)—Sets the request URL.
  • request.setBody(requestBody)—Sets the request body.

Post-execution script methods

These methods are response specific, so you can only use them for post-execution scripts.

  • response.getResponseBody()—Returns the entire response body as a string.
  • response.getHeaders()—Returns an object holding HTTP headers.
  • response.getStatusCode()—Returns the status code for the request.