Run Validatar jobs from any orchestrator over REST

Prev Next

Any orchestrator that can run a script or make an HTTP call can run a Validatar job, wait for it to finish, and stop the pipeline when a test does not pass. This page has that script in Python, PowerShell and Bash, a variant for a single standard test, and notes for Airflow, dbt, Prefect, Dagster, Control-M, SSIS and other tools. Orchestration Integrations documents every endpoint and field the scripts use.

Prerequisites

  • A Validatar user token with the Execution scope. In Validatar, click the user icon in the top right, choose User Profile, open Tokens and select New Token, with Type set to API. See User Tokens.
  • Access to the project for the token's user.
  • Network access from the orchestrator to the Validatar address.
  • The project id and job id. Open the job in Validatar; the URL reads /projects/<project id>/folders/<folder id>/jobs/<job id>.

All the scripts read these environment variables:

Variable Value
VALIDATAR_API_URL The address you open Validatar with, such as https://acme.cloud.validatar.com (no /core, no trailing slash)
VALIDATAR_API_TOKEN Your user token
VALIDATAR_PROJECT_ID Project that holds the job
VALIDATAR_JOB_ID The job to run
VALIDATAR_TIMEOUT Optional: seconds to wait for the run, default 1800

Each script exits with code 0 when every test in the job passed and 1 otherwise, so the orchestrator marks the task failed on its own.

Run a job and evaluate the results (Python)

Save as validatar_run_job.py. Requires pip install requests.

"""Run a Validatar job and fail unless every test in it passes.

Starts the job through the Execution API, polls the job's results until the
run finishes, then exits 0 when every test passed and 1 otherwise.

Environment variables:
    VALIDATAR_API_URL     instance address, e.g. https://acme.cloud.validatar.com
    VALIDATAR_API_TOKEN   user token with the Execution scope
    VALIDATAR_PROJECT_ID
    VALIDATAR_JOB_ID
    VALIDATAR_TIMEOUT     seconds to wait for the run, default 1800

Requirements: pip install requests
"""
import os
import sys
import time

import requests

API = f"{os.environ['VALIDATAR_API_URL'].rstrip('/')}/core/api/v1"
HEADERS = {"x-val-api-token": os.environ["VALIDATAR_API_TOKEN"], "Accept": "application/json"}
PROJECT_ID = int(os.environ["VALIDATAR_PROJECT_ID"])
JOB_ID = int(os.environ["VALIDATAR_JOB_ID"])
TIMEOUT_SECONDS = int(os.environ.get("VALIDATAR_TIMEOUT", "1800"))
POLL_SECONDS = 5
FINISHED = ("Completed", "Aborted", "Abandoned")

# ---------------------------------------------------------------------------
# Step 1: start the job
# ---------------------------------------------------------------------------
response = requests.post(f"{API}/Execution/projects/{PROJECT_ID}/jobs/{JOB_ID}/execute",
                         headers=HEADERS, timeout=60)
if response.status_code != 200:
    sys.exit(f"Execute failed: HTTP {response.status_code} {response.text[:500]}")
run = response.json()
print(f"Started job {JOB_ID} ({run.get('name')}): batch {run.get('batchId')}, "
      f"execution key {run['executionKey']}")

# ---------------------------------------------------------------------------
# Step 2: poll until the run finishes
# ---------------------------------------------------------------------------
results_url = f"{API}/Execution/projects/{PROJECT_ID}/jobs/{JOB_ID}/results/{run['executionKey']}"
deadline = time.monotonic() + TIMEOUT_SECONDS
summary = {}
while time.monotonic() < deadline:
    time.sleep(POLL_SECONDS)
    try:
        poll = requests.get(results_url, headers=HEADERS, timeout=60)
    except requests.RequestException as error:
        print(f"  poll error, retrying: {error}")
        continue
    if poll.status_code != 200:  # the run may not be recorded yet
        print(f"  poll returned HTTP {poll.status_code}, retrying")
        continue
    summary = poll.json()
    print(f"  status: {summary.get('status')}")
    if summary.get("status") in FINISHED:
        break
else:
    sys.exit(f"Timed out after {TIMEOUT_SECONDS}s. The job may still be running in Validatar.")

# ---------------------------------------------------------------------------
# Step 3: fail unless every test in the run passed
# ---------------------------------------------------------------------------
print(f"Started {summary.get('dateStarted')}, completed {summary.get('dateCompleted')}")
if summary["status"] != "Completed":
    sys.exit(f"FAILED: the job ended with status {summary['status']}.")
tests = summary.get("tests", [])
for t in tests:
    print(f"  [{t.get('status')}] {t.get('name')} (test {t.get('id')})")
not_passed = [t for t in tests if t.get("status") != "Passed"]
if not tests:
    sys.exit("FAILED: the job ran no tests. Check the job's steps.")
if not_passed:
    sys.exit(f"FAILED: {len(not_passed)} of {len(tests)} test(s) did not pass.")
print(f"PASSED: all {len(tests)} test(s) passed.")

Run a job and evaluate the results (PowerShell)

Save as validatar-run-job.ps1 and run it with pwsh -File validatar-run-job.ps1 (or powershell -File on Windows PowerShell 5.1).

<#
Run a Validatar job and fail unless every test in it passes.

Starts the job through the Execution API, polls the job's results until the
run finishes, then exits 0 when every test passed and 1 otherwise.
Reads the same environment variables as validatar_run_job.py.
Works in Windows PowerShell 5.1 and PowerShell 7.
#>
$ErrorActionPreference = "Stop"
if ($PSVersionTable.PSVersion.Major -le 5) {
    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
}

$Api         = "$($env:VALIDATAR_API_URL.TrimEnd('/'))/core/api/v1"
$Headers     = @{ "x-val-api-token" = $env:VALIDATAR_API_TOKEN }
$ProjectId   = [int]$env:VALIDATAR_PROJECT_ID
$JobId       = [int]$env:VALIDATAR_JOB_ID
$Timeout     = if ($env:VALIDATAR_TIMEOUT) { [int]$env:VALIDATAR_TIMEOUT } else { 1800 }
$PollSeconds = 5
$Finished    = @("Completed", "Aborted", "Abandoned")

# ---------------------------------------------------------------------------
# Step 1: start the job
# ---------------------------------------------------------------------------
try {
    $Run = Invoke-RestMethod -Method Post -Uri "$Api/Execution/projects/$ProjectId/jobs/$JobId/execute" -Headers $Headers
}
catch {
    Write-Host "Execute failed: $($_.Exception.Message) $($_.ErrorDetails.Message)"
    exit 1
}
Write-Host "Started job $JobId ($($Run.name)): batch $($Run.batchId), execution key $($Run.executionKey)"

# ---------------------------------------------------------------------------
# Step 2: poll until the run finishes
# ---------------------------------------------------------------------------
$ResultsUrl = "$Api/Execution/projects/$ProjectId/jobs/$JobId/results/$($Run.executionKey)"
$Deadline = (Get-Date).AddSeconds($Timeout)
$Summary = $null
while ((Get-Date) -lt $Deadline) {
    Start-Sleep -Seconds $PollSeconds
    try {
        $Summary = Invoke-RestMethod -Method Get -Uri $ResultsUrl -Headers $Headers
    }
    catch {
        # The run may not be recorded yet, or the network blinked: poll again
        Write-Host "  poll failed, retrying: $($_.Exception.Message)"
        continue
    }
    Write-Host "  status: $($Summary.status)"
    if ($Finished -contains $Summary.status) { break }
}
if (-not $Summary -or $Finished -notcontains $Summary.status) {
    Write-Host "Timed out after $Timeout seconds. The job may still be running in Validatar."
    exit 1
}

# ---------------------------------------------------------------------------
# Step 3: fail unless every test in the run passed
# ---------------------------------------------------------------------------
Write-Host "Started $($Summary.dateStarted), completed $($Summary.dateCompleted)"
if ($Summary.status -ne "Completed") {
    Write-Host "FAILED: the job ended with status $($Summary.status)."
    exit 1
}
$Tests = @($Summary.tests)
foreach ($t in $Tests) {
    Write-Host "  [$($t.status)] $($t.name) (test $($t.id))"
}
$NotPassed = @($Tests | Where-Object { $_.status -ne "Passed" })
if ($Tests.Count -eq 0) {
    Write-Host "FAILED: the job ran no tests. Check the job's steps."
    exit 1
}
if ($NotPassed.Count -gt 0) {
    Write-Host "FAILED: $($NotPassed.Count) of $($Tests.Count) test(s) did not pass."
    exit 1
}
Write-Host "PASSED: all $($Tests.Count) test(s) passed."
exit 0

Run a job and evaluate the results (Bash)

Save as validatar-run-job.sh. It needs curl and python3, which it uses to read JSON.

#!/usr/bin/env bash
# Run a Validatar job and fail unless every test in it passes.
#
# Starts the job through the Execution API, polls the job's results until the
# run finishes, then exits 0 when every test passed and 1 otherwise.
# Reads the same environment variables as validatar_run_job.py.
# Needs curl and python3.
set -euo pipefail

API_URL="${VALIDATAR_API_URL:?Set VALIDATAR_API_URL}"
API="${API_URL%/}/core/api/v1"
TOKEN="${VALIDATAR_API_TOKEN:?Set VALIDATAR_API_TOKEN}"
PROJECT_ID="${VALIDATAR_PROJECT_ID:?Set VALIDATAR_PROJECT_ID}"
JOB_ID="${VALIDATAR_JOB_ID:?Set VALIDATAR_JOB_ID}"
TIMEOUT="${VALIDATAR_TIMEOUT:-1800}"
POLL_INTERVAL=5

BODY=$(mktemp)
trap 'rm -f "$BODY"' EXIT

json_field() {  # json_field FIELD FILE: print one top-level field of a JSON file
  python3 -c "import json, sys; print(json.load(open(sys.argv[2])).get(sys.argv[1], ''))" "$1" "$2"
}

# ---------------------------------------------------------------------------
# Step 1: start the job
# ---------------------------------------------------------------------------
HTTP_CODE=$(curl -s -o "$BODY" -w "%{http_code}" -X POST \
  "${API}/Execution/projects/${PROJECT_ID}/jobs/${JOB_ID}/execute" \
  -H "x-val-api-token: ${TOKEN}" \
  -H "Content-Type: application/json" \
  -d '')
if [ "$HTTP_CODE" != "200" ]; then
  echo "Execute failed: HTTP ${HTTP_CODE}"
  cat "$BODY"; echo
  exit 1
fi
EXECUTION_KEY=$(json_field executionKey "$BODY")
echo "Started job ${JOB_ID}: batch $(json_field batchId "$BODY"), execution key ${EXECUTION_KEY}"

# ---------------------------------------------------------------------------
# Step 2: poll until the run finishes
# ---------------------------------------------------------------------------
RESULTS_URL="${API}/Execution/projects/${PROJECT_ID}/jobs/${JOB_ID}/results/${EXECUTION_KEY}"
STATUS=""
ELAPSED=0
while [ "$ELAPSED" -lt "$TIMEOUT" ]; do
  sleep "$POLL_INTERVAL"
  ELAPSED=$((ELAPSED + POLL_INTERVAL))
  HTTP_CODE=$(curl -s -o "$BODY" -w "%{http_code}" "$RESULTS_URL" -H "x-val-api-token: ${TOKEN}" || true)
  if [ "$HTTP_CODE" != "200" ]; then
    echo "  [${ELAPSED}s] poll returned HTTP ${HTTP_CODE}, retrying"   # not recorded yet, or a network blip
    continue
  fi
  STATUS=$(json_field status "$BODY")
  echo "  [${ELAPSED}s] status: ${STATUS}"
  case "$STATUS" in Completed|Aborted|Abandoned) break ;; esac
done

case "$STATUS" in
  Completed) ;;
  Aborted|Abandoned) echo "FAILED: the job ended with status ${STATUS}."; exit 1 ;;
  *) echo "Timed out after ${TIMEOUT}s. The job may still be running in Validatar."; exit 1 ;;
esac

# ---------------------------------------------------------------------------
# Step 3: fail unless every test in the run passed
# ---------------------------------------------------------------------------
python3 - "$BODY" <<'PY'
import json, sys
tests = json.load(open(sys.argv[1])).get("tests", [])
for t in tests:
    print(f"  [{t.get('status')}] {t.get('name')} (test {t.get('id')})")
not_passed = [t for t in tests if t.get("status") != "Passed"]
if not tests:
    sys.exit("FAILED: the job ran no tests. Check the job's steps.")
if not_passed:
    sys.exit(f"FAILED: {len(not_passed)} of {len(tests)} test(s) did not pass.")
print(f"PASSED: all {len(tests)} test(s) passed.")
PY

Run a single standard test (Python)

To gate on one standard test instead of a job, start the test and poll its result. The execute call returns as soon as the run starts, so the script polls until result is no longer Running.

"""Run one Validatar standard test and fail unless it passes.

The execute call returns as soon as the run starts, so the script polls the
test's results until the result is no longer Running.

Environment variables:
    VALIDATAR_API_URL, VALIDATAR_API_TOKEN (Execution scope), VALIDATAR_PROJECT_ID,
    VALIDATAR_TEST_ID, VALIDATAR_TIMEOUT (seconds, default 600)

Requirements: pip install requests
"""
import os
import sys
import time

import requests

API = f"{os.environ['VALIDATAR_API_URL'].rstrip('/')}/core/api/v1"
HEADERS = {"x-val-api-token": os.environ["VALIDATAR_API_TOKEN"], "Accept": "application/json"}
PROJECT_ID = int(os.environ["VALIDATAR_PROJECT_ID"])
TEST_ID = int(os.environ["VALIDATAR_TEST_ID"])
TIMEOUT_SECONDS = int(os.environ.get("VALIDATAR_TIMEOUT", "600"))

# Step 1: start the test. saveInRepository keeps the result and returns a batchId.
response = requests.post(f"{API}/Execution/projects/{PROJECT_ID}/tests/{TEST_ID}/execute",
                         headers=HEADERS, json={"saveInRepository": True}, timeout=60)
if response.status_code != 200:
    sys.exit(f"Execute failed: HTTP {response.status_code} {response.text[:500]}")
run = response.json()
print(f"Started test {TEST_ID} ({run.get('name')}): batch {run.get('batchId')}")

# Step 2: poll until the result is Passed, Failed or Error
results_url = f"{API}/Execution/projects/{PROJECT_ID}/tests/{TEST_ID}/results/{run['executionKey']}"
deadline = time.monotonic() + TIMEOUT_SECONDS
result = "Running"
while time.monotonic() < deadline:
    time.sleep(2)
    try:
        poll = requests.get(results_url, headers=HEADERS, timeout=60)
    except requests.RequestException:
        continue
    if poll.status_code == 200:
        result = poll.json().get("result") or "Running"
        if result != "Running":
            break
else:
    sys.exit(f"Timed out after {TIMEOUT_SECONDS}s. The test may still be running in Validatar.")

# Step 3: pass only on Passed
print(f"Result: {result}")
sys.exit(0 if result == "Passed" else 1)

Run it from your orchestrator

The scripts work anywhere Python, PowerShell or Bash runs. Keep the token in the orchestrator's secret store and pass it to the script as VALIDATAR_API_TOKEN.

Apache Airflow

Run the script from a BashOperator (python validatar_run_job.py) placed after the load task, with the token from an Airflow Variable or Connection passed through env. A non-zero exit fails the task.

dbt

With dbt Core, run the script right after dbt build in the same scheduler step, so the job checks the models that were just built. With dbt Cloud, subscribe a webhook to job run completion and have the receiver run the script.

Prefect

Call the script's logic from a @task inside your @flow, and keep the token in a Prefect Secret block.

Dagster

Call the script's logic from an @op (or an asset check) and pass the token through a resource or EnvVar.

Control-M

Run the script from an OS job, or call the execute and results endpoints directly from a Web Services REST job. The OS job fails on a non-zero exit code.

SSIS

Use an Execute Process task that runs powershell.exe -File validatar-run-job.ps1, and pass the project id and job id through SSIS variables. A non-zero exit code fails the task by default.

Azure Data Factory

Call the execute endpoint from a Web activity, then poll the results endpoint in an Until loop with a Web activity and a Wait activity. Keep the token in Azure Key Vault.

Informatica

Run the script from a command task after the mapping that loads the data: a Command Task step in an Informatica Cloud taskflow, or a Command task in a PowerCenter workflow.

Luigi

Wrap the Python logic in a luigi.Task and run it from the task's run() method.

Talend

Run the script from a tSystem component, or call the endpoints directly with tRESTClient.

Check that it worked

  1. The script prints Started job <id> (...): batch <batch id>, one line per test, and PASSED: all N test(s) passed.
  2. Open https://<your-instance>.cloud.validatar.com/projects/<project id>/results/<batch id> in Validatar. It shows the same run, with the same tests and results.
  3. To prove the gate stops the pipeline, run it against a job with a test you know fails. The script prints FAILED: ..., exits with code 1, and the orchestrator marks the task failed.

Troubleshooting

HTTP 404 on the execute call

  • VALIDATAR_API_URL holds the wrong address. Use the address you open Validatar with, such as https://acme.cloud.validatar.com, without /core and without a trailing slash. The scripts add /core/api/v1/Execution/.
  • If the address is right, check that the job id belongs to the project id. The response body says Job not found when it does not.

HTTP 401 or 403

  • The header name must be exactly x-val-api-token, not Authorization or Bearer.
  • Confirm the token has the Execution scope.
  • Check that the token's user can open the project.

Timeout without completion

  • Raise VALIDATAR_TIMEOUT if the job runs longer than 30 minutes.
  • Open the job in Validatar to see whether the run is still going or stopped with an error.

"The job ran no tests"

  • The job finished without running any test. Open it in Validatar and check that its steps point at tests or folders that contain tests.

Connection refused or timed out

  • Check VALIDATAR_API_URL.
  • For Validatar Server behind a firewall, the orchestrator must be able to reach the server.
  • For Validatar Cloud, check that no corporate proxy blocks the connection.