# Example script: Starting a data generation job

Kicking off a data generation using Python. Note the version that this script was tested against.

{% tabs %}
{% tab title="Python" %}
{% code title="tonic\_generation.py" %}

```python
# Note that we do not guarantee backwards compatibility for our API.
# Please look at the Swagger API documentation that comes with your instance
# for your exact version's endpoints and parameters. If you are using hosted
# Tonic, you can find the API documentation here:

# Tested 2021.04.12 with Tonic API v199
import json

# Be sure to install requests via pip, pipenv, or poetry before running.
import requests

# Parameters
TONIC_API_KEY = "<<TONIC API TOKEN>>"
TONIC_URL = "https://<<TONIC HOSTNAME>>"
WORKSPACE_NAME = "<<TONIC WORKSPACE>>"


class TonicSession:
    def __init__(self, base_url, api_key):
        self._base_url = base_url
        self._session = requests.Session()
        self._api_key = api_key
        self._session.headers.update({"Authorization": "Apikey {}".format(api_key)})

    def _get_url(self, api_snippet):
        return "{}{}".format(self._base_url, api_snippet)

    def generate_data(self, workspace_id):
        generate_data_url = self._get_url("/api/generateData/start")
        params = {"workspaceId": workspace_id}

        r = self._session.post(generate_data_url, params=params)

        if r.ok:
            print("Data generation started")
        else:
            r.raise_for_status()

    def generate_data_status(self, workspace_id):
        generate_data_status_url = self._get_url("/api/generateData")
        params = {"workspaceId": workspace_id}

        r = self._session.get(generate_data_status_url, params=params)

        if r.ok:
            print(json.dumps(r.json(), indent=2))
        else:
            r.raise_for_status()

    def get_workspaces(self):
        workspace_list_url = self._get_url("/api/workspace")

        r = self._session.get(workspace_list_url)

        if r.ok:
            return r.json()
        else:
            r.raise_for_status()


def find_workspace_id(workspaces_json, workspace_name):
    for workspace in workspaces_json:
        if workspace["workspaceName"] == workspace_name:
            return workspace["id"]
    raise RuntimeError("No Workspace found with name: {}".format(workspace_name))


def main():
    session = TonicSession(TONIC_URL, TONIC_API_KEY)
    workspace_id = find_workspace_id(session.get_workspaces(), WORKSPACE_NAME)

    # Starts a new data generation
    session.generate_data(workspace_id)

    # Prints out the current status of the workspace
    session.generate_data_status(workspace_id)


if __name__ == "__main__":
    main()

```

{% endcode %}
{% endtab %}

{% tab title="Node" %}
{% code title="tonic\_generation.js" %}

```javascript
// Note that we do not guarantee API back compatibility. Please look at the
// Swagger API documentation that comes with your instance for your exact
// version's endpoints and parameters. If you are using hosted Tonic, you can
// find the API documentation here: https://app.tonic.ai/apidocs/index.html

// Tested 2020.11.30 with Tonic API v145

// Install node-fetch with npm install node-fetch
const fetch = require('node-fetch');

const apiKey = "<<TONIC API TOKEN>>";
const workspaceName = "<<TONIC WORKSPACE>>";
const tonicUrl = "https://<<TONIC HOSTNAME>>"

async function getWorkspaceId() {
    let response = await fetch(`${tonicUrl}/api/workspace`, {
        method: 'get',
        headers: { 'Authorization': `apikey ${apiKey}` },
    });

    const workspaces = await response.json();
    const filteredWorkspaces = workspaces.filter(w => w.fingerprintName === workspaceName);
    if (filteredWorkspaces.length !== 1) {
        throw new Error(`No Workspace found with name: ${workspaceName}`);
    }
    return filteredWorkspaces[0].id;
}

async function generateData(workspaceId) {
    let response = await fetch(`${tonicUrl}/api/generateData/start?workspaceId=${workspaceId}&strictMode=RejectOnAllSchemaItems`, {
        method: 'post',
        headers: { 'Authorization': `apikey ${apiKey}` },
    });

    if(!response.ok) {
        throw new Error(await response.text());
    }

    const job = await response.json();

    return job.id;
}

getWorkspaceId()
.then(workspaceId =>generateData(workspaceId))
.then(jobId => console.log(`Job ${jobId} queued`));
```

{% endcode %}
{% endtab %}

{% tab title="Powershell" %}
{% code title="tonic\_generation.ps1" %}

```bash
# Note that we do not guarantee API back compatibility. Please look at the
# Swagger API documentation that comes with your instance for your exact
# version's endpoints and parameters. If you are using hosted Tonic, you can
# find the API documentation here: https://app.tonic.ai/apidocs/index.html

# Tested 2020.11.30 with Tonic API v145

$apiKey = "<<TONIC API TOKEN>>"
$workspaceName = "<<TONIC WORKSPACE>>"
$tonicUrl = "https://<<TONIC HOSTNAME>>"


$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", "apikey $apiKey")
$headers.Add("Accept", "application/json")

$workspaceResponse = Invoke-RestMethod "$tonicUrl/api/workspace" -Method 'GET' -Headers $headers -UseBasicParsing

$filteredWorkspaces = $workspaceResponse.Where({$_.fingerPrintName -eq $workspaceName})

if ($filteredWorkspaces.Count -ne 1)
{
    throw "No Workspace found with name: $workspaceName"
}

$workspaceId = $filteredWorkspaces[0].id

try {
    $generateResponse = Invoke-RestMethod "$tonicUrl/api/generateData/start?workspaceId=$workspaceId&strictMode=RejectOnAllSchemaItems" -Method 'POST' -Headers $headers -UseBasicParsing
    $jobId = $generateResponse.id
    Write-Host "Job $jobId queued"
}
catch {
    $result = $_.Exception.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($result)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    throw $responseBody
}
```

{% endcode %}
{% endtab %}

{% tab title="Bash" %}
{% code title="tonic\_generation.sh" %}

```bash
#!/bin/bash
# Note that we do not guarantee API back compatibility. Please look at the
# Swagger API documentation that comes with your instance for your exact
# version's endpoints and parameters. If you are using hosted Tonic, you can
# find the API documentation here: https://app.tonic.ai/apidocs/index.html

# Tested 2020.11.30 with Tonic API v145

# This script requires jq to be installed

apikey="<<TONIC API TOKEN>>"
workspaceName="<<TONIC WORKSPACE>>"
tonicUrl="https://<<TONIC HOSTNAME>>"

workspaceResponse=$(curl -v --request GET "${tonicUrl}/api/workspace" -H "Authorization: apikey $apikey" -H "Accept: application/json")

workspaceId=jq '.[] | select(.fingerprintName == $workspaceName) | .id'
if [ ${#workspaceId} != 36 ]
then
    echo "No Workspace found with name: $workspaceName"
    exit 1
fi

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")
if [[ $generateResponse == *{* ]]
then
    jobId=$(echo $generateResponse | jq '.id' | tr -d '"')
    echo "Job $jobId queued"
else
    echo $generateResponse | tr -d '"'
    exit 1
fi

```

{% endcode %}
{% endtab %}
{% endtabs %}
