Here is a suggested process flow that an organization can leverage to transfer data from a file located in an external file folder to your CustomerGauge system via an API Integration.


Please note: Our expertise and support is limited to the CG API side of the offering. Kindly only raise support requests if there is a question about our API.



Process:


From the file folder location (either from a physical machine or a virtual machine), execute your script to open the file, loop over the file and call the CustomerGauge PUT API to pass the data to CustomerGauge.

  1. Access the File: Write a script to access the file. If this is a continuous process - this will need a CRON job to execute this on a scheduled basis.

  2. CG API Authentication: Setup the CG API Authentication based on our CG API documentation. Replace the region in the API call with your CustomerGauge system region (eu, au, or us) to configure the API to your use case.

  3. Data Payload: Create the API Payload based on the agreed data fields.

  4. API Call: Use the PUT API call to pass on the data to CG. You will need to loop over the file to get through all of the records on your file. Replace the region in the API call with your CustomerGauge system region (eu, au, or us) to configure the API to your use case.



Example Code


The below is only an example script shared for reference. Please do not copy paste for usage. You will need to write your own based on the system you are executing the action from.


This example is written in Python Language. 



import csv
import http.client
import json
import logging
import urllib.parse
import urllib.request
from functools import lru_cache
from http import HTTPStatus
from typing import Any, Dict
from urllib.error import HTTPError

# Set the constants below to the values corresponding to your use case.

FILE_TO_UPLOAD = r"/full/path/to/file.csv"
"""Full path of the file to be uploaded"""

REGION = "eu"
"""Region of your company. One of au, eu, us"""

CLIENT_ID = "my-client-id"
"""Your Client ID for authentication with the CustomerGauge API"""

CLIENT_SECRET = "my-client-secret"
"""Your Client Secret for authentication with the CustomerGauge API"""

CONFIGURATION_REFERENCE = "my-configuration-reference"
"""Configuration to use with the upload"""


def upload_file(input_file: str) -> None:
    logging.info("Starting upload")
    with open(input_file, mode="r", newline="", encoding="utf-8") as infile:
        reader = csv.reader(infile)

        # Skip the first line, those are the headers.
        next(reader)

        for n, row in enumerate(reader, start=1):
            logging.info("Uploading row #%s", n)
            # Set your own data here as needed.
            # First column is 0, second is 1, and so on.
            record = {
                "email": row[0],
                "account_name": row[1],
                "channel": row[2],
            }
            _upload_record(record)
    logging.info("Upload complete")


def _upload_record(record: Dict[str, Any], retry_auth=True) -> None:
    # Prepare request
    body = {
        "configuration": CONFIGURATION_REFERENCE,
        "record": record,
    }
    body_json = json.dumps(body).encode("utf-8")
    logging.debug("body_json = %s", body_json)
    access_token = _authenticate()
    headers = {
        "Authorization": f"Bearer {access_token}",
        "Content-Type": "application/json",
    }
    url = f"https://imports.api.{REGION}.customergauge.com/records/"
    request = urllib.request.Request(url, data=body_json, headers=headers, method="PUT")
    try:
        response: http.client.HTTPResponse = urllib.request.urlopen(request)
    except HTTPError as exc:
        # Handle token expired.
        if exc.status == HTTPStatus.UNAUTHORIZED and retry_auth:
            logging.info("Authentication token expired, refreshing")
            # Clear the cached token.
            _authenticate.cache_clear()
            # Retry the upload. If authentication fails again in this call, don't retry anymore.
            return _upload_record(record, retry_auth=False)
        # Handle other errors.
        logging.error(exc.read())
        raise exc from None
    else:
        logging.debug("response = %s", response)
        response_body = response.read()
        logging.debug("response_body = %s", response_body)
        if response.status != HTTPStatus.OK:
            raise Exception(
                f"Failed to import record: {response.status} {response.reason} {response_body}"
            )


@lru_cache
def _authenticate() -> str:
    logging.info("Authenticating as %s", CLIENT_ID)
    url = f"https://auth.{REGION}.customergauge.com/oauth2/token"
    data = urllib.parse.urlencode(
        {
            "client_id": CLIENT_ID,
            "grant_type": "client_credentials",
            "client_secret": CLIENT_SECRET,
        }
    ).encode("utf-8")
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    request = urllib.request.Request(url, data=data, headers=headers, method="POST")
    with urllib.request.urlopen(request) as response:
        if response.status != HTTPStatus.OK:
            logging.error(response.read())
            raise Exception(
                f"Authentication failed: {response.status} {response.reason}"
            )
        response_data = json.loads(response.read().decode("utf-8"))
    access_token = response_data["access_token"]
    logging.debug("access_token = %s", access_token)
    return access_token


if __name__ == "__main__":
    logging.basicConfig(
        level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
    )
    upload_file(FILE_TO_UPLOAD)