TOИIC
Search…
Example: Starting a data generation job
Kicking off a data generation using Python. Note the version that this script was tested against. This script is also hosted on Github.
Python
Node
Powershell
Bash
tonic_generation.py
1
# Note that we do not guarantee backwards compatibility for our API.
2
# Please look at the Swagger API documentation that comes with your instance
3
# for your exact version's endpoints and parameters. If you are using hosted
4
# Tonic, you can find the API documentation here:
5
6
# Tested 2021.04.12 with Tonic API v199
7
import json
8
9
# Be sure to install requests via pip, pipenv, or poetry before running.
10
import requests
11
12
# Parameters
13
TONIC_API_KEY = "<<TONIC API KEY>>"
14
TONIC_URL = "https://<<TONIC HOSTNAME>>"
15
WORKSPACE_NAME = "<<TONIC WORKSPACE>>"
16
17
18
class TonicSession:
19
def __init__(self, base_url, api_key):
20
self._base_url = base_url
21
self._session = requests.Session()
22
self._api_key = api_key
23
self._session.headers.update({"Authorization": "Apikey {}".format(api_key)})
24
25
def _get_url(self, api_snippet):
26
return "{}{}".format(self._base_url, api_snippet)
27
28
def generate_data(self, workspace_id):
29
generate_data_url = self._get_url("/api/generateData/start")
30
params = {"workspaceId": workspace_id}
31
32
r = self._session.post(generate_data_url, params=params)
33
34
if r.ok:
35
print("Data generation started")
36
else:
37
r.raise_for_status()
38
39
def generate_data_status(self, workspace_id):
40
generate_data_status_url = self._get_url("/api/generateData")
41
params = {"workspaceId": workspace_id}
42
43
r = self._session.get(generate_data_status_url, params=params)
44
45
if r.ok:
46
print(json.dumps(r.json(), indent=2))
47
else:
48
r.raise_for_status()
49
50
def get_workspaces(self):
51
workspace_list_url = self._get_url("/api/workspace")
52
53
r = self._session.get(workspace_list_url)
54
55
if r.ok:
56
return r.json()
57
else:
58
r.raise_for_status()
59
60
61
def find_workspace_id(workspaces_json, workspace_name):
62
for workspace in workspaces_json:
63
if workspace["workspaceName"] == workspace_name:
64
return workspace["id"]
65
raise RuntimeError("No Workspace found with name: {}".format(workspace_name))
66
67
68
def main():
69
session = TonicSession(TONIC_URL, TONIC_API_KEY)
70
workspace_id = find_workspace_id(session.get_workspaces(), WORKSPACE_NAME)
71
72
# Starts a new data generation
73
session.generate_data(workspace_id)
74
75
# Prints out the current status of the workspace
76
session.generate_data_status(workspace_id)
77
78
79
if __name__ == "__main__":
80
main()
81
Copied!
tonic_generation.js
1
// Note that we do not guarantee API back compatibility. Please look at the
2
// Swagger API documentation that comes with your instance for your exact
3
// version's endpoints and parameters. If you are using hosted Tonic, you can
4
// find the API documentation here: https://app.tonic.ai/apidocs/index.html
5
6
// Tested 2020.11.30 with Tonic API v145
7
8
// Install node-fetch with npm install node-fetch
9
const fetch = require('node-fetch');
10
11
const apiKey = "<<TONIC API KEY>>";
12
const workspaceName = "<<TONIC WORKSPACE>>";
13
const tonicUrl = "https://<<TONIC HOSTNAME>>"
14
15
async function getWorkspaceId() {
16
let response = await fetch(`${tonicUrl}/api/workspace`, {
17
method: 'get',
18
headers: { 'Authorization': `apikey ${apiKey}` },
19
});
20
21
const workspaces = await response.json();
22
const filteredWorkspaces = workspaces.filter(w => w.fingerprintName === workspaceName);
23
if (filteredWorkspaces.length !== 1) {
24
throw new Error(`No Workspace found with name: ${workspaceName}`);
25
}
26
return filteredWorkspaces[0].id;
27
}
28
29
async function generateData(workspaceId) {
30
let response = await fetch(`${tonicUrl}/api/generateData/start?workspaceId=${workspaceId}&strictMode=RejectOnAllSchemaItems`, {
31
method: 'post',
32
headers: { 'Authorization': `apikey ${apiKey}` },
33
});
34
35
if(!response.ok) {
36
throw new Error(await response.text());
37
}
38
39
const job = await response.json();
40
41
return job.id;
42
}
43
44
getWorkspaceId()
45
.then(workspaceId =>generateData(workspaceId))
46
.then(jobId => console.log(`Job ${jobId} queued`));
Copied!
tonic_generation.ps1
1
# Note that we do not guarantee API back compatibility. Please look at the
2
# Swagger API documentation that comes with your instance for your exact
3
# version's endpoints and parameters. If you are using hosted Tonic, you can
4
# find the API documentation here: https://app.tonic.ai/apidocs/index.html
5
6
# Tested 2020.11.30 with Tonic API v145
7
8
$apiKey = "<<TONIC API KEY>>"
9
$workspaceName = "<<TONIC WORKSPACE>>"
10
$tonicUrl = "https://<<TONIC HOSTNAME>>"
11
12
13
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
14
$headers.Add("Authorization", "apikey $apiKey")
15
$headers.Add("Accept", "application/json")
16
17
$workspaceResponse = Invoke-RestMethod "$tonicUrl/api/workspace" -Method 'GET' -Headers $headers -UseBasicParsing
18
19
$filteredWorkspaces = $workspaceResponse.Where({$_.fingerPrintName -eq $workspaceName})
20
21
if ($filteredWorkspaces.Count -ne 1)
22
{
23
throw "No Workspace found with name: $workspaceName"
24
}
25
26
$workspaceId = $filteredWorkspaces[0].id
27
28
try {
29
$generateResponse = Invoke-RestMethod "$tonicUrl/api/generateData/start?workspaceId=$workspaceId&strictMode=RejectOnAllSchemaItems" -Method 'POST' -Headers $headers -UseBasicParsing
30
$jobId = $generateResponse.id
31
Write-Host "Job $jobId queued"
32
}
33
catch {
34
$result = $_.Exception.Response.GetResponseStream()
35
$reader = New-Object System.IO.StreamReader($result)
36
$reader.BaseStream.Position = 0
37
$reader.DiscardBufferedData()
38
$responseBody = $reader.ReadToEnd();
39
throw $responseBody
40
}
Copied!
tonic_generation.sh
1
#!/bin/bash
2
# Note that we do not guarantee API back compatibility. Please look at the
3
# Swagger API documentation that comes with your instance for your exact
4
# version's endpoints and parameters. If you are using hosted Tonic, you can
5
# find the API documentation here: https://app.tonic.ai/apidocs/index.html
6
7
# Tested 2020.11.30 with Tonic API v145
8
9
# This script requires jq to be installed
10
11
apikey="<<TONIC API KEY>>"
12
workspaceName="<<TONIC WORKSPACE>>"
13
tonicUrl="https://<<TONIC HOSTNAME>>"
14
15
workspaceResponse=$(curl -v --request GET "${tonicUrl}/api/workspace" -H "Authorization: apikey $apikey" -H "Accept: application/json")
16
17
workspaceId=jq '.[] | select(.fingerprintName == $workspaceName) | .id'
18
if [ ${#workspaceId} != 36 ]
19
then
20
echo "No Workspace found with name: $workspaceName"
21
exit 1
22
fi
23
24
generateResponse=$(curl -v --request POST "${tonicUrl}/api/generateData/start?workspaceId=${workspaceId}&strictMode=RejectOnAllSchemaItems" -H "Authorization: apikey $apikey" -H "Accept: application/json" -H "Content-Length: 0")
25
if [[ $generateResponse == *{* ]]
26
then
27
jobId=$(echo $generateResponse | jq '.id' | tr -d '"')
28
echo "Job $jobId queued"
29
else
30
echo $generateResponse | tr -d '"'
31
exit 1
32
fi
33
Copied!
Copy link