How to track events in unomi server, and access its rest api

1.4k Views Asked by At

I am new to Unomi,

  • I had installed unomi-1.2.0-incubating and started the karaf server it is running successfully.

  • I have elastic search install and working under cluster name contextElasticSearch.

  • I had integrated the context.js in my Front End website to load it from the unomi, and also triggered the page visit event as home page, by making the successful call to unomi context.json, with contectParams like below:

Code:

function contextRequest(successCallback, errorCallback, payload) {
    var data = JSON.stringify(payload);
    // if we don't already have a session id, generate one
    var sessionId = cxs.sessionId || generateUUID();
    var url = 'http://localhost:8181/context.json?sessionId=' + sessionId;
    var xhr = new XMLHttpRequest();
    var isGet = data.length < 100;
    if (isGet) {
        xhr.withCredentials = true;
        xhr.open("GET", url + "&payload=" + encodeURIComponent(data), true);
    } else if ("withCredentials" in xhr) {
        xhr.open("POST", url, true);
        xhr.withCredentials = true;
    } else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open("POST", url);
    }
    xhr.onreadystatechange = function () {
        if (xhr.readyState != 4) {
            return;
        }
        if (xhr.status == 200) {
            var response = xhr.responseText ? JSON.parse(xhr.responseText) : undefined;
            if (response) {
                cxs.sessionId = response.sessionId;
                successCallback(response);
            }
        } else {
            console.log("contextserver: " + xhr.status + " ERROR: " + xhr.statusText);
            if (errorCallback) {
                errorCallback(xhr);
            }
        }
    };
}
var scope = 'unomipages';
var itemId = btoa(window.location.href);
var source = {
  itemType: 'page',
  scope: scope,
  itemId: itemId,
  properties: {
      url: window.location.href
  }
};
var contextPayload: any = {
  source: source,
  events: [
    {
      eventType: 'pageVisitEvent',
      scope: scope,
      source: source
    }
  ],
  requiredProfileProperties: [            
  ]
};

contextRequest(function (response: any) {         
console.log(JSON.stringify(response));
}, function(){}, contextPayload);

My Question is:

  • How to track events in unomi server, and access its rest api?

Let me know if you want any more info from me, or if I am missing any thing.

1

There are 1 best solutions below

0
On

We just published a tutorial on the Unomi website that might help you out, check it here. And, I actually asked a similar question to the mailing list you can review here. I will try an add an events example to the website.

To access you REST API, you want to use http://localhost:8181/cxs. You can read the REST API documentation here, use the URL above as the base for those endpoints. You also need to do basic authentication (default username and password is karaf and karaf).

For tracking events, you will need to create a profile and a session. Here's some Python that demonstrates that:

from requests import post
from datetime import datetime
"""
Make a request to Unomi to create a profile with ID = 10
"""
profile = {
    "itemId":"10",
    "itemType":"profile",
    "version":None,
    "properties": {
        "firstName": "John",
        "lastName": "Smith"
    },
    "systemProperties":{},
    "segments":[],
    "scores":{},
    "mergedWith":None,
    "consents":{}
}

session = {
    "itemId": "10",
    "itemType":"session",
    "scope":None,
    "version":1,
    "profileId":profile_id,
    "profile": profile,
    "properties":{},
    "systemProperties":{},
    "timeStamp": datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
}

# Create or update profile
r = post('http://localhost:8181/cxs/profiles/',
auth=('karaf','karaf'),
json =profile)
print(r)
print(r.content)


# Create session
r = post('http://localhost:8181/cxs/profiles/sessions/10',
    auth=('karaf', 'karaf'),
    json=session)

print(r)
print(r.content)

As for tracking events themselves, consider this Python example using the REST API (there is actually an "Event Collector" in Unomi):

j

son = {
    "eventType": "view",
    "scope": "ACMESPACE",
    "source": {
        "itemType": "site",
        "scope": "ACMESPACE",
        "itemId": "c4761bbf-d85d-432b-8a94-37e866410375"
    },
    "target": {
        "itemType": "page",
        "scope": "ACMESPACE",
        "itemId": "b6acc7b3-6b9d-4a9f-af98-54800ec13a71",
        "properties": {
            "pageInfo": {
            "pageID": "b6acc7b3-6b9d-4a9f-af98-54800ec13a71",
            "pageName": "Home",
            "pagePath": "/sites/ACMESPACE/home",
            "destinationURL": "http://localhost:8080/sites/ACMESPACE/home.html",
            "referringURL": "http://localhost:8080/",
            "language": "en"
        },
        "category": {},
        "attributes": {}
      }
    }
}

session_id = "aSessionId"
session_id = "aProfileId"

r = requests.post('{endpoint}/eventcollector?sessionId={session_id}'\
            .format(endpoint=ENDPOINT, profile_id=profile_id),
        auth=('karaf', 'karaf'),
        json=json)

Takes a little while to understand the relationship between profiles, session and events. Events really relate to sessions and session related to profiles. So to use the REST API to track events, you have to also figure out how you'll track sessions. A little confusing but once you get it, it'll make sense.