We’ve migrated our documentation to a new site, which means some URLs have changed.
Audience

Segment Creation API

The Piano Audience API offers various methods for managing your data and segments. A full list is available at the Piano Audience API page.

In this example, we are going to upload a segment configuration with /segment/create.

The demo segment will include the users with a minimum of N pageviews over the last M days within a defined URL region of the publication.

There are 3 ways to define a URL region:

  • By host name, for instance exampple.com (this corresponds to the event attribute host). Everything from that server counts as pageviews.

  • By URL path, for instance solutions in https://example.com/solutions/ (this corresponds to the document (keyword) attribute taxonomy). Everything under that taxonomy path counts as pageviews.

  • By full qualified URL, for instance https://www.example.com/about/company.html (this corresponds to the event attribute URL). Visits to that particular page count as page views.

Or you can use any combination of the three below variants.

Running the following example will produce an audience segment filter expression followed by the ID of the newly created segment.

_username          = "<YOUR PIANO USER NAME>"
_secret            = "<YOUR PIANO API KEY>"
_siteGroupId       = "<SITE GROUP ID>"
_segments = [
    {
        "name"     : "My Test Segment",
        "taxonomy" : ["section1", "section2/subsection"],
        "host"     : ["server1.domain", "server2.domain"],
        "url"      : ["http://server3.domain/some/path/someFile.html"],
        "min"      : 25,
        "days"     : 30
    }
]
 
import json, datetime, hmac, hashlib, http.client
      
def cxApi(path, obj):
    date = datetime.datetime.utcnow().isoformat() + "Z"
    signature = hmac.new(_secret.encode('utf-8'), date.encode('utf-8'), digestmod=hashlib.sha256).hexdigest()
    headers = {"X-cXense-Authentication": "username=%s date=%s hmac-sha256-hex=%s" % (_username, date, signature)}
    connection = http.client.HTTPSConnection("api.cxense.com", 443)
    connection.request("POST", path, json.dumps(obj), headers)
    response = connection.getresponse()
    status = response.status
    responseObj = json.loads(response.read().decode('utf-8'))
    connection.close()
    return status, responseObj
    
def errorHandling(status, response, message):
    if status != 200:
        raise Exception("%s (http status = %s, error details: '%s')" % (message, status, response['error']))
 
def createUserSegment(requestObj):
    status, response = cxApi('/segment/create', requestObj)
    errorHandling(status, response, "Unable to retrieve traffic data")
    return response
 
def getFilterObj(days, minPageViews, filterGroups):
    return [{
        "type": "time",
        "start": days,
        "filter": {
            "type": "user",
            "having": {
                "min": minPageViews,
                "filter": {
                    "type": "or",
                    "filters": filterGroups
                }
            }
        }
    }]
 
def genDescription(items, minPageViews, days):
    return "Minimum of %s page views during last %s days across: %s" % (minPageViews, days, ', '.join(items))
 
def getSegmentRequestObj(siteGroupId, segment):
    mappings = {'taxonomy':'keyword', 'host':'event', 'url':'event'}
    filterGroups = []
    for group in mappings.keys():
        filterGroups.append({"type":mappings[group], "group":group, "items":segment[group]})   
    minPageViews = segment['min'] if 'min' in segment else '1' 
    return {
        "siteGroupId": siteGroupId,
        "name": segment['name'] if 'name' in segment else '<No segment name defined>',
        "description": genDescription([', '.join(group['items']) for group in filterGroups], minPageViews, segment['days']),
        "filters": getFilterObj("-%sd" % segment['days'], minPageViews, filterGroups),
        "active": True
    }    
 
for segment in _segments:
    requestObj = getSegmentRequestObj(_siteGroupId, segment)
    print(json.dumps(requestObj, indent=4))
    print(createUserSegment(requestObj))

The result of the example above: an audience segment filter expression followed by the id of the newly created segment.

{
    "filters": [
        {
            "filter": {
                "having": {
                    "min": 25,
                    "filter": {
                        "filters": [
                            {
                                "group": "taxonomy",
                                "items": [
                                    "section1",
                                    "section2/subsection"
                                ],
                                "type": "keyword"
                            },
                            {
                                "group": "url",
                                "items": [
                                    "http://server3.domain/some/path/someFile.html"
                                ],
                                "type": "event"
                            },
                            {
                                "group": "host",
                                "items": [
                                    "server1.domain",
                                    "server2.domain"
                                ],
                                "type": "event"
                            }
                        ],
                        "type": "or"
                    }
                },
                "type": "user"
            },
            "type": "time",
            "start": "-30d"
        }
    ],
    "active": true,
    "description": "Minimum of 25 page views during last 30 days across: section1, section2/subsection, http://server3.domain/some/path/someFile.html, server1.domain, server2.domain",
    "name": "My Test Segment",
    "siteGroupId": "9222355312367160874"
}
{'id': '8mg5yqyr0jqx'}

The segment, with its auto-generated description, can now be found in the list of the site group's audience segments.

Segments created via API can later be updated from the UI Segment Editor.

Last updated: