Pre- and post-execution scripts for HTTP monitors

Dynatrace version 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 cannot refer to it in the pre-execution script, because at this moment, this content does not 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:
HTTP method: POST
Post-execution script:

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

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


Request 2

Request URL:
HTTP method: GET
Pre-execution script:

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

Full monitor script

	"version": "1.0",
	"requests": [
			"description": "GET access_token",
			"url": "",
			"method": "POST",
			"requestBody": "scope=openid%20read&client_secret=somesecret&grant_type=password&username=user%40somesite%2Ecom&password=password123&client_id=clientid",
			"configuration": {
				"requestHeaders": [
						"name": "Content-Type",
						"value": "application/x-www-form-urlencoded"
				"acceptAnyCertificate": true,
				"followRedirects": true
			"preProcessingScript": "",
			"postProcessingScript": "if (response.getStatusCode() != 200) {\n\"HTTP error: \" + response.getStatusCode());\n}\nvar responseBody = response.getResponseBody();\nvar jsonData = JSON.parse(responseBody);\napi.setValue(\"bearerToken\", jsonData.access_token);\;"
			"description": "GET tenants",
			"url": "",
			"method": "GET",
			"requestBody": "",
			"configuration": {
				"acceptAnyCertificate": true,
				"followRedirects": true
			"preProcessingScript": "request.addHeader(\"Authorization\", \"Bearer \" + api.getValue(\"bearerToken\"));",
			"postProcessingScript": ""

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

  •—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

  •—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.

The messages are logged in the synthetic.x.y.log file, for example synthetic.1.2.log saved in the ActiveGate log directory.

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 base64UrlDecode(encodedUrl)—Decodes base64url input. Available from ActiveGate version 1.181.
  • 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.
  • api.atob(value)—Converts a string of binary data to a base-64-encoded ASCII string. Maximal value parameter length: 10000 characters. Available from ActiveGate version 1.181.

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 provided format based on the Java SimpleDateFormat class.
  •—Returns the current date.


api.setValue("dateToFormat", api.dateToFormat("1346524199000", "dd/MM/yy"));
api.setValue("dateToFormatCurrentDate", api.dateToFormat(, "dd/MM/yy"));

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.