Send custom data to Databox

After you’ve created your Token and your first Custom Metric it’s time to start sending your custom data to Databox.

There are two ways to send your data to Databox:

  1. Using our SDKs (recommended) or
  2. Directly from a command line

  • cURL
  • PHP
  • JavaScript
  • Java
  • Go
  • Python
  • C#

curl https://push.databox.com/data \
-u <your_token>: \
-X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/vnd.databox.v2+json' \
-d '[
    {
      "key": "<metric_key_id>",
      "value": <metric_value>,
      "date": "<Date_in_ISO8601>",
      "unit": "<unit>",
      "attributes": [{ "key": "<dimension_key>", "value": "<dimension_value>" }]
    }
  ]'

<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use Databox\Api\DefaultApi;
use Databox\ApiException;
use Databox\Configuration;
use Databox\Model\PushData as DataboxPushData;
use GuzzleHttp\Client;

execute();

function execute()
{
    // Configure HTTP basic authorization: basicAuth
    $config = Configuration::getDefaultConfiguration()
        ->setHost('https://push.databox.com')
        ->setUsername('<your_token>');

    $headers = [
        'Content-Type' => 'application/json',
        'Accept'       => 'application/vnd.databox.v2+json'
    ];

    $apiInstance = new DefaultApi(
    // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`.
    // This is optional, `GuzzleHttp\Client` will be used as default.
        new Client(['headers' => $headers]),
        $config
    );

    $pushData = (new DataboxPushData())
        ->setKey('<metric_key_id>') // for e.g. sessions
        ->setValue(125)
        ->setDate('2017-01-01T00:00:00Z') // Date in ISO8601 format
        ->setUnit('<unit>') // for e.g. $
        ->setAttributes(['<dimension_key>' => '<dimension_value>']); // e.g., ['country' => 'US']


    try {
        $apiInstance->dataPost([$pushData]);
        echo "Successfully pushed data to Databox";
    } catch (ApiException $e) {
        echo 'Exception when calling DefaultApi->dataPost: ' . $e->getMessage() . PHP_EOL . $e->getResponseBody() . PHP_EOL;
    }
}

import {
  ApiResponse,
  Configuration,
  DataPostRequest,
  DefaultApi,
} from "databox";

const config: Configuration = new Configuration({
  basePath: "https://push.databox.com",
  username: "<your_token>",
  headers: {
    Accept: "application/vnd.databox.v2+json",
  },
});

const dataPostRequest: DataPostRequest = {
  pushData: [
    {
      key: "<metric_key_id>",
      value: 123,
      date: "<Date_in_ISO8601>",
      unit: "<Unit>", // Optional
      attributes: [{ key: "<dimension_key>", value: "<dimension_value>" }], // Optional
    },
  ],
};

const api = new DefaultApi(config);

try {
  api
    .dataPostRaw(dataPostRequest)
    .then((response: ApiResponse<void>) => response.raw.json())
    .then((responseBody) => {
      console.log("Response data", responseBody);
    });
} catch (error) {
  console.log("Error: ", error);
}

import org.databox.ApiClient;
import org.databox.ApiException;
import org.databox.Configuration;
import org.databox.api.DefaultApi;
import org.databox.auth.HttpBasicAuth;
import org.openapitools.client.model.PushData;
import org.openapitools.client.model.PushDataAttribute;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = Configuration.getDefaultApiClient();
    defaultClient.setBasePath("https://push.databox.com");
    defaultClient.addDefaultHeader("Accept", "application/vnd.databox.v2+json");

    HttpBasicAuth basicAuth = (HttpBasicAuth) defaultClient.getAuthentication("basicAuth");
    basicAuth.setUsername("Your_Databox_API_Token");

    PushData data = new PushData()
            .key("metric_key_id") // e.g. sales
            .value(123f)
            .date("Date_in_ISO8601") // e.g. "2024-08-01T00:00:00Z"
            .unit("unit") // optional - e.g. USD
            .attributes(List.of(new PushDataAttribute().key("dimension_key").value("dimension_value"))); // optional - e.g. currency & USD

    DefaultApi apiInstance = new DefaultApi(defaultClient);
    try {
      apiInstance.dataPost(List.of(data));
    } catch (ApiException e) {
      e.printStackTrace();
    }
  }
}


package main

import (
  "context"
  "fmt"
  "os"
  "time"

  databox "github.com/databox/databox-go/databox"
)

const t = "<your_token>" // Your Databox token

func main() {

  // Create a context with basic auth
  auth := context.WithValue(context.Background(), databox.ContextBasicAuth, databox.BasicAuth{UserName: t})

  // Create a configuration
  cfg := databox.NewConfiguration()
  cfg.DefaultHeader["Content-Type"] = "application/json"
  cfg.DefaultHeader["Accept"] = "application/vnd.databox.v2+json"

  // Create an API client
  api := databox.NewAPIClient(cfg)

  // Create a new PushDataAttribute object - this is optional and represent the dimensions of the data
  a := databox.NewPushDataAttribute()
  a.SetKey("<dimension_name>")
  a.SetValue("<dimension_value>")

  var d []databox.PushDataAttribute
  d = append(d, *a)

  // Create a new PushData object and set the data
  data := databox.NewPushData()
  data.SetKey("<metric_key_id>")
  data.SetValue(100.0)
  data.SetDate(time.Now().UTC().Format(time.RFC3339))
  data.SetUnit("<unit>")
  data.SetAttributes(d)

  // Push the data
  r, err := api.DefaultAPI.DataPost(auth).PushData([]databox.PushData{*data}).Execute()
  if err != nil {
    fmt.Fprintf(os.Stderr, "Error when calling `DefaultAPI.DataPost``: %v\n", err)
  }

  fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}

# Configuration setup for the Databox API client
# The API token is used as the username for authentication
# It's recommended to store your API token securely, e.g., in an environment variable
configuration = databox.Configuration(
    host="https://push.databox.com",
    username="<your_token>",
    password=""
)

# It's crucial to specify the correct Accept header for the API request
with databox.ApiClient(configuration, "Accept", "application/vnd.databox.v2+json", ) as api_client:
    api_instance = databox.DefaultApi(api_client)

    # Define the data to be pushed to the Databox Push API# Prepare the data you want to push to Databox
    # The 'key' should match a metric in your Databox account, 'value' is the data point, 'unit' is optional, and 'date' is the timestamp of the data point    
    push_data = [{
        "key": "<metric_key_id>",
        "value": 100,
        "unit": "<unit>",
        "date": "<date_in_ISO8601>",
        "attributes": [{"key": "<dimension_name>", "value": "<dimension_value>"}]
    }]

    try:
        api_instance.data_post(push_data=push_data)
    except ApiException as e:
        # Handle exceptions that occur during the API call, such as invalid data or authentication issues
        pprint("API Exception occurred: %s\n" % e)
    except Exception as e:
        # Handle any other unexpected exceptions
        pprint("An unexpected error occurred: %s\n" % e)


using System.Diagnostics;
using Databox.Api;
using Databox.Client;
using Databox.Model;

namespace Example
{
  public class Example
  {
    public static async Task Main(string[] args)
    {

      Configuration config = new Configuration();
      config.BasePath = "https://push.databox.com";
      config.Username = "<your_token>";
      config.DefaultHeaders.Add("Accept", "application/vnd.databox.v2+json");


      HttpClient httpClient = new HttpClient();
      HttpClientHandler httpClientHandler = new HttpClientHandler();
      var apiInstance = new DefaultApi(httpClient, config, httpClientHandler);
      var dataPostRequest = new List<PushData>() {
        new PushData() {
          Key = "<metric_key_id>",
          Value = 123,
          Date = "<Date_in_ISO8601>",
          Unit = "<Unit>", // Optional
          Attributes = new List<PushDataAttribute>() { // Optional
            new PushDataAttribute() {
              Key = "<Dimension_name>",
              Value = "<Dimension_value>"
            }
          }
        }
      };

      try
      {
        var response = await apiInstance.DataPostWithHttpInfoAsync(dataPostRequest);
        Console.WriteLine(response.Data.ToString());
      }
      catch (ApiException e)
      {
        Console.WriteLine("Exception when calling DefaultApi.DataPostWithHttpInfo: " + e.Message);
        Console.WriteLine("Status Code: " + e.ErrorCode);
        Console.WriteLine(e.StackTrace);
      }
    }
  }
}

When using examples:

  1. Replace <your_token>  with the Token you previously created
  2. Replace the <metric_key_id> with the metric key identifier that you previously defined.

The metric key is case sensitive, you can use any alphanumeric value (a-z, A-Z, 0-9, _).

The example above will store the value 123.000 to the metric ‘<metric_key_id>‘, located in the custom Data Source with the hash identification <your_token>.

By default, the current date and time (now) will be used to store information about sent events. If you would like to store events that happened in the past or will happen in the future, you can use the optional Date property. Learn more about Date and Time.

Pro Tip: A metric value must be purely numeric. Whole numbers can be up to 16 digits long. When storing decimal values (using the decimal separator “.”), up to 6 decimal digits are supported.

For currency values, you can attach a unit to it. Percentages can be formatted directly in Databox. For duration and relative time metrics you have to push a UNIX timestamp (epoch time) in milliseconds as the metric value and then select the ‘Duration’ or ‘Relative time’ Format.

Sending multiple metrics at once

You can also send multiple metrics at once, like so:

  • cURL
  • PHP
  • JavaScript
  • Java
  • Go
  • Python
  • C#

curl https://push.databox.com/data \
-u <your_token>: \
-X POST \
-H 'Content-Type: application/json' \
-H 'Accept: application/vnd.databox.v2+json' \
-d '[
    {
      "key": "conversion_rate",
      "value": 0.20
    },
    {
      "key": "sales", 
      "value": 200
    }
  ]'


<?php

require_once __DIR__ . '/../../../vendor/autoload.php';

use Databox\Api\DefaultApi;
use Databox\ApiException;
use Databox\Configuration;
use Databox\Model\PushData as DataboxPushData;
use GuzzleHttp\Client;

execute();

function execute()
{
    // Configure HTTP basic authorization: basicAuth
    $config = Configuration::getDefaultConfiguration()
        ->setHost('https://push.databox.com')
        ->setUsername('<your_token>');

    $headers = [
        'Content-Type' => 'application/json',
        'Accept'       => 'application/vnd.databox.v2+json'
    ];

    $apiInstance = new DefaultApi(
        new Client(['headers' => $headers]),
        $config
    );

    try {
        $apiInstance->dataPost([
            (new DataboxPushData())
                ->setKey('conversion_rate')
                ->setValue(0.09),
            
            (new DataboxPushData())
                ->setKey('sales')
                ->setValue(100)
        ]);

        echo "Successfully pushed data to Databox";
    } catch (ApiException $e) {
        echo 'Exception when calling DefaultApi->dataPost: ' . $e->getMessage() . PHP_EOL . $e->getResponseBody() . PHP_EOL;
    }
}



import {
  ApiResponse,
  Configuration,
  DataPostRequest,
  DefaultApi,
} from "databox";

const config: Configuration = new Configuration({
  basePath: "https://push.databox.com",
  username: "<your_token>",
  headers: {
    Accept: "application/vnd.databox.v2+json",
  },
});

const dataPostRequest: DataPostRequest = {
  pushData: [
    {
      key: "conversion_rate",
      value: 0.9,
    },
    {
      key: "sales",
      value: 100,
    }
  ],
};

const api = new DefaultApi(config);

try {
  api
    .dataPostRaw(dataPostRequest)
    .then((response: ApiResponse<void>) => response.raw.json())
    .then((responseBody) => {
      console.log("Response data", responseBody);
    });
} catch (error) {
  console.log("Error: ", error);
}



import org.databox.ApiClient;
import org.databox.ApiException;
import org.databox.Configuration;
import org.databox.api.DefaultApi;
import org.databox.auth.HttpBasicAuth;
import org.openapitools.client.model.PushData;

import java.util.List;

public class PushDataExample {
    public static void main(String[] args) {
        ApiClient defaultClient = Configuration.getDefaultApiClient();
        defaultClient.setBasePath("https://push.databox.com");
        defaultClient.addDefaultHeader("Accept", "application/vnd.databox.v2+json");

        HttpBasicAuth basicAuth = (HttpBasicAuth) defaultClient.getAuthentication("basicAuth");
        basicAuth.setUsername("<your_token>");

        DefaultApi apiInstance = new DefaultApi(defaultClient);

        try {
            apiInstance.dataPost(List.of(
                new PushData()
                    .key("conversion_rate")
                    .value(0.09f),
                
                new PushData()
                    .key("sales")
                    .value(100)
            ));
        } catch (ApiException e) {
            e.printStackTrace();
        }
    }
}


package main

import (
  "context"
  "fmt"
  "os"
  "time"

  databox "github.com/databox/databox-go/databox"
)

const t = "<your_token>" // Your Databox token

func main() {

  // Create a context with basic auth
  auth := context.WithValue(context.Background(), databox.ContextBasicAuth, databox.BasicAuth{UserName: t})

  // Create a configuration
  cfg := databox.NewConfiguration()
  cfg.DefaultHeader["Content-Type"] = "application/json"
  cfg.DefaultHeader["Accept"] = "application/vnd.databox.v2+json"

  // Create an API client
  api := databox.NewAPIClient(cfg)

  data1 := databox.NewPushData()
  data1.SetKey("conversion_rate")
  data1.SetValue(0.09)

  data2 := databox.NewPushData()
  data2.SetKey("sales")
  data2.SetValue(100)


  // Push the data (send both PushData objects)
  r, err := api.DefaultAPI.DataPost(auth).PushData([]databox.PushData{*data1, *data2}).Execute()
  if err != nil {
    fmt.Fprintf(os.Stderr, "Error when calling `DefaultAPI.DataPost``: %v\n", err)
  }

  fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
}

# Configuration setup for the Databox API client
# The API token is used as the username for authentication
# It's recommended to store your API token securely, e.g., in an environment variable
configuration = databox.Configuration(
    host="https://push.databox.com",
    username="<your_token>",
    password=""
)

# It's crucial to specify the correct Accept header for the API request
with databox.ApiClient(configuration, "Accept", "application/vnd.databox.v2+json", ) as api_client:
    api_instance = databox.DefaultApi(api_client)

    # Define the data to be pushed to the Databox Push API# Prepare the data you want to push to Databox
    push_data = [
        {
            "key": "conversion_rate",
            "value": 0.9
        },
        {
            "key": "sales",
            "value": 100,
        }
    ]

    try:
        api_instance.data_post(push_data=push_data)
    except ApiException as e:
        # Handle exceptions that occur during the API call, such as invalid data or authentication issues
        pprint("API Exception occurred: %s\n" % e)
    except Exception as e:
        # Handle any other unexpected exceptions
        pprint("An unexpected error occurred: %s\n" % e)


using System.Diagnostics;
using Databox.Api;
using Databox.Client;
using Databox.Model;

namespace Example
{
  public class Example
  {
    public static async Task Main(string[] args)
    {

      Configuration config = new Configuration();
      config.BasePath = "https://push.databox.com";
      config.Username = "<your_token>";
      config.DefaultHeaders.Add("Accept", "application/vnd.databox.v2+json");


      HttpClient httpClient = new HttpClient();
      HttpClientHandler httpClientHandler = new HttpClientHandler();
      var apiInstance = new DefaultApi(httpClient, config, httpClientHandler);
      var dataPostRequest = new List<PushData>() {
        new PushData()
        {
            Key = "conversion_rate",
            Value = 0.9f
        },
        new PushData()
        {
            Key = "sales",
            Value = 100
        }
      };

      try
      {
        var response = await apiInstance.DataPostWithHttpInfoAsync(dataPostRequest);
        Console.WriteLine(response.Data.ToString());
      }
      catch (ApiException e)
      {
        Console.WriteLine("Exception when calling DefaultApi.DataPostWithHttpInfo: " + e.Message);
        Console.WriteLine("Status Code: " + e.ErrorCode);
        Console.WriteLine(e.StackTrace);
      }
    }
  }
}

Pro Tip: If your metric is not created yet or if you used the wrong metric key identifier (i.e. ‘$sales’), the PushAPI service will create it upon first push. However, we recommend you create a metric beforehand and set the necessary parameters to avoid incorrect data presentation.

Storing multiple values with the same timestamp

In case you are storing new or multiple values on a specific (same) timestamp, every new value will be overwritten. This is the default behaviour and useful in case you’re updating a daily value multiple times per day or if you’re updating historical timestamps with updated values.

In case you are storing event values where more than one event appeared at the same time (either exact timestamp or just day), you want both values to be stored. For this, enable the setting “Handling multiple values for identical Date/Time” from the Metric definition popup. Note that this setting is available for all aggregation functions except “Latest”.

Metric Definition

If your payload has been accepted, you will receive a 200 – OK message. If you receive an error, review this Responses and errors guide.

Once you’ve successfully sent your data, it’s time to view your data in Databox.