Skip to content

CGS API Service to fetch real-time data for your custom dashboards. #148

Description

@tringuyenMSS

STEP-BY-STEP API INTEGRATION GUIDE FOR CLIENT DASHBOARDS

This document provides a step-by-step guide on how to configure a Workflow on Catglobe and consume the API Service to fetch real-time data for your custom dashboards.


Workflow Overview

  1. Step 1: Create a Workflow inside the Catglobe backend using CgScript to process, aggregate, or filter your required dataset.
  2. Step 2: Send an HTTP POST Request from your dashboard application to the Catglobe API endpoint.
  3. Step 3: The API executes the script dynamically and sends back the wrapped execution response directly to your dashboard.

Step 1: Prepare Your Workflow on Catglobe

Before triggering the API, you must set up the data logic within the Catglobe platform using a Workflow.

  • The content of this Workflow is written using CgScript. No deployment process is required after saving your script.
  • Reading Input Parameters: Inside your CgScript Workflow, you can retrieve the custom parameters passed from the API request by calling the native function: Workflow_getParameters(). This will return the raw string payload that you can then parse or manipulate within your script.
  • Formatting the Output: To make it easy to parse and decode the data on your dashboard side, you should serialize your final dataset inside the CgScript Workflow using the native function: Catglobe.Json.Encode(data).
  • Take note of the ResourceId assigned to the Workflow

Step 2: API Request Configuration

To fetch the data, your dashboard needs to dispatch an HTTP POST request to the single endpoint detailed below:

1. Endpoint Properties

2. Request Body Structure (JSON)

The payload must include the following fields:

  • Username (String): Your dedicated API connection account with execution permissions.
  • Password (String): The corresponding password for the account.
  • ResourceId (Integer): The target system ID of the Workflow resource to run.
  • Parameters (String): Contextual input parameters for the CgScript. This must be a JSON array serialized into a string. It can be a simple array of values or an array containing complex objects. This entire string string will be captured by Workflow_getParameters() inside your backend script.

Example Request Payload:

{
  "Username": "your_api_username",
  "Password": "your_secure_password",
  "ResourceId": 12345,
  "Parameters": "[{\"region\": \"APAC\", \"limit\": 50}, {\"region\": \"EMEA\", \"limit\": 10}]"
}

3. Response Body Structure (JSON)

Upon processing completion, the API endpoint responds with a standardized wrapper:

  • Type (Integer): Represents the underlying data type of the result block. It may vary depending on the computed output (e.g., error indicators, int, string, object). For dashboard integrations, this field can generally be skipped as long as the Workflow explicitly serializes its payload.
  • Result (String): The output string generated by your CgScript Workflow. Since you serialize your final dataset using Catglobe.Json.Encode(data), this field will contain the serialized JSON string payload.

Example Response Payload:

{
  "Type": 1,
  "Result": "{\"status\": \"success\", \"totalResponses\": 1550, \"charts\": [{\"label\": \"Q1\", \"value\": 85}]}"
}

Step 3: Implementation Code Examples

Below are standard integration templates across common environments to communicate with the Catglobe API.

1. JavaScript Example (Fetch API for Web Dashboards)

// Define the API endpoint and credentials
const url = 'https://voxmeter.catglobe.com/api/RunWorkflow';

// Parameters can be any array structure (including array of objects) serialized into a string
const complexParamArray = [
    { filterType: "dateRange", start: "2026-01-01", end: "2026-06-17" },
    { targetSegments: ["premium", "enterprise"] }
];

const requestData = {
    Username: "your_api_username",
    Password: "your_secure_password",
    ResourceId: 12345,
    Parameters: JSON.stringify(complexParamArray)
};

// Send POST request to the Catglobe API service
fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(requestData)
})
.then(response => {
    if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
})
.then(data => {
    // Check if the payload result segment is populated
    if (data && data.Result) {
        // Decode the inner JSON string generated by Catglobe.Json.Encode()
        const dashboardData = JSON.parse(data.Result);
        console.log("Data for Dashboard:", dashboardData);
    } else {
        console.error("Empty response or execution error.", data);
    }
})
.catch(error => {
    console.error("Error fetching data from Catglobe API:", error);
});

2. C# Example (.NET / Blazor Dashboards)

using System;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

public class CatglobeApiService
{
    private readonly HttpClient _httpClient;
    private const string ApiUrl = "https://voxmeter.catglobe.com/api/RunWorkflow";

    public CatglobeApiService(HttpClient httpClient)
    {
        _httpClient = httpClient;
    }

    public async Task<string> FetchDashboardDataAsync()
    {
        // Construct an array of objects to pass as arguments
        var paramArray = new[]
        {
            new { key = "region", value = "APAC" },
            new { key = "includeMeta", value = "true" }
        };
        var serializedParams = JsonSerializer.Serialize(paramArray);

        var payload = new
        {
            Username = "your_api_username",
            Password = "your_secure_password",
            ResourceId = 12345,
            Parameters = serializedParams
        };

        var jsonPayload = JsonSerializer.Serialize(payload);
        var content = new StringContent(jsonPayload, Encoding.UTF8, "application/json");

        try
        {
            var response = await _httpClient.PostAsync(ApiUrl, content);
            response.EnsureSuccessStatusCode();

            var jsonResponse = await response.Content.ReadAsStringAsync();
            using var doc = JsonDocument.Parse(jsonResponse);
            var root = doc.RootElement;

            // Extract the result string directly to decode inside the dashboard application logic
            if (root.TryGetProperty("Result", out var resultProp))
            {
                return resultProp.GetString();
            }
            
            return null;
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error communicating with Catglobe API: {ex.Message}");
            throw;
        }
    }
}

Important Considerations & Best Practices

  • Security Warning: Do not store or transmit your API credentials (Username and Password) directly via client-side code (e.g., frontend JavaScript running in browser instances). It is strongly recommended to route these requests through your own secure backend proxy layer.
  • Handling Nested JSON Strings: Because the Result property returns explicitly as a string payload, your application must run an initial JSON parse operation (JSON.parse() in JS or JsonSerializer.Deserialize() in C#) against that string property to extract usable JSON objects or arrays.
  • Network Timeouts: For operations processing exceptionally large backend datasets inside Catglobe, ensure your dashboard client's HTTP timeout limit is appropriately scaled up to mitigate dropped network states.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions