Rules API
You can implement the Oracle Data Cloud category and rules web services to independently classify the page and user attributes ingested from your site or classify your onboarded offline data. Classification is the process in which your data that has been transferred into the Oracle Data Cloud platform is collected and mapped to categories in your private taxonomy. Implementing the category and rule chain APIs enables you to create hierarchical categories within your taxonomy and write rules that define when an attribute (and user) get added to each category.
With the rules API, you can create classification rules based on URLs and key-value pairs (phints) that map the user data extracted from your site with the categories you have created.
Note: Users no longer create campaigns in the Oracle Data Cloud platform UI. The campaign workflow is now part of the audience workflow. The platform still uses campaigns to manage audience data delivery however. They are created automatically when a UI user delivers an audience. In the APIs, you create and use campaigns as before.
In this topic
Explore the API
The embedded I/O doc below enables you to explore the API. The I/O doc explains the parameters for each method and provides templates for your calls. You cannot make live API calls from the tool, however.
Open the link below in a new tab to see the I/O doc in a three-pane format.
For help with this API, contact My Oracle Support (MOS).
Service URI
The URI for the rules API is:
services.bluekai.com/rest/taxonomyRuleChains
Create a rule
To create a rule, include a request body with the following POST call:
services.bluekai.com/rest/taxonomyRuleChains?partner.id={yourPartnerId}
When you create a rule, you specify your partner ID in the query and include parameters in the JSON body of the request. The parameters define the rule. These are the parameters you specify:
- rules: Define the logic of the rule with the following two parameters: taxonomyRuleOperator and taxonomyRuleOperatorParams.
- taxonomyRuleOperator: Enter the ID for the rule operator to be used. The rule operator may be one of the following values:
- 1 - (==) is: The phint value passed in the tag (or offline file) must exactly match the one in the rule.
- 3 - (_*) starts-with: The phint value must start with the one in the rule.
- 4 - (*_ ) ends-with: The phint value passed must end with the one in the rule.
- 5 - (*_*) contains: The phint value must be contained within the one in the rule.
- taxonomyRuleOperatorParams: Enter the names of the phint key and value in the value parameters (yourKey and yourValue). Do not modify the key or value1 parameter names.
- Key syntax: phint keys support only alphanumeric characters and underscores (a-z, 0-9, and _); keys are case insensitive. Do not include spaces in the key.
- Value syntax: phint values support all Latin-1 and UTF-8 characters (alphanumeric characters and special characters); values are case insensitive.
- Creating URL-based Rules: To create a rule for a webpage URL, enter the __bk_l key in the yourKey parameter. To create a rule for a referral URL, enter the __bk_pr key in the yourKey parameter. The Oracle Data Cloud core tag automatically extracts page and referrer URLs from your webpages. This enables you to link categories to your webpages and referrers.
- taxonomyRuleOperator: Enter the ID for the rule operator to be used. The rule operator may be one of the following values:
- categories: Enter the category ID for which this rule applies.
- sites: Enter a list of one or more site IDs for which this rule is applicable. To make the rule applicable to ALL containers/site IDs in your seat, leave this parameter empty and enter your partner ID in the partners parameter.
-
partners: To make this rule applicable to all containers/site IDs in your seat, specify your partner ID. Leave this parameter empty to limit the scope of this rule to the site IDs specified in the sites parameter.
Use the following syntax to specify the partner ID:
"partners": ["id": "nnnnn"]
For example:
"partners": ["id": "99999"]
Sample request bodies
In this example, the rule is restricted to site 48603.
{
"rules": [ {
"taxonomyRuleOperator": { "id": 1 },
"taxonomyRuleOperatorParams": [
{ "name": "key", "value": "drink" },
{ "name": "value1", "value": "banana_smoothie" }
]
} ],
"categories": [ { "id": 1042249} ],
"sites": [ { "id": 48603}],
"partners": []
}
In this example, the rule is applicable to all sites owned by partner seat 99999..
{
"rules": [ {
"taxonomyRuleOperator": { "id": 1 },
"taxonomyRuleOperatorParams": [
{ "name": "key", "value": "drink" },
{ "name": "value1", "value": "banana_smoothie" }
]
} ],
"categories": [ { "id": 1042249} ],
"sites": [],
"partners": ["id": "P99999"]
}
Response:
{
"id": 31070824,
"rules": [
{
"id": 33106879,
"operatorExpression": "testKey=testValue",
"taxonomyRuleOperator": {
"id": 1,
"name": "==",
"formula": "{{key}}={{value1}}",
"description": "is ",
"createdAt": "2016-04-05T21:22:11-05:00",
"updatedAt": "2016-04-05T21:22:11-05:00",
"status": "active"
},
"taxonomyRuleOperatorParams": [
{
"name": "key",
"value": "drink"
},
{
"name": "value1",
"value": "banana_smoothie"
}
]
}
],
"categories": [
{
"id": 1042249,
"name": "Banana Smoothie"
}
],
"ruleChainMetaData": [],
"classificationGroups": [],
"sites": [
{
"id": 48603,
"name": "Test"
}
],
"partners": [],
"createdAt": "2018-01-31T13:16:24-06:00",
"updatedAt": "2018-01-31T13:16:24-06:00",
"status": "active"
}
Bulk import (via file upload)
To create and edit multiple rules at the same time by uploading a TSV or TXT file:
- In the query string of your call to the Rules API, append
import
to the path.serviceUrl = 'https://services.bluekai.com/rest/taxonomyRuleChains/import?partner.id={yourPartnerId}'
- In the
headers
parameter, set theContent-Type
tomultipart/form-data
.headers = {"Content-Type": "multipart/form-data; "Accept": "application/json","User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0"}
- Include a parameter that is set to the name of the .tsv or .txt file to be imported.
- Verify that the import file has the following columns:
Column | Description | Required for Upload | Value Required for Creating Rules via Upload | |||||||||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Action | The value entered in this column depends on the action: Create rule. Leave blank. Edit rule. Enter "modify". Delete rule. Enter "delete". |
YES | NO | |||||||||||||||||||||||||||||||||||||||||||||
Rule ID | The unique ID generated for the rule. This is required for editing or deleting rules. | YES (if editing) | NO | |||||||||||||||||||||||||||||||||||||||||||||
Site ID | A pipe-separated list of the site IDs for which the rule is applicable. If the rules is applicable to all site IDs, your partner ID is listed with the following syntax: P{partnerId} (for example, P4021). | YES | YES | |||||||||||||||||||||||||||||||||||||||||||||
Site ID Switch | Internal-use only. Site ID switches are used to attribute the data collected from a site ID to another one. This is typically used for 3rd-party offline match partners. | YES | NO | |||||||||||||||||||||||||||||||||||||||||||||
Key1 |
The name of the phint key. Phint keys are case-insensitive, and they support
alphanumeric and underscore characters (a-z, 0-9, and _). Rules with Multiple Phints: If a rule contains multiple phints, the export will include an additional
key, op, and value column for each phint. For example, if a rule
has three phints, the export will additionally include key2, Op2,
Value2, key3, Op3, and Value3 columns. |
YES | YES | |||||||||||||||||||||||||||||||||||||||||||||
Op1 |
The operator used to evaluate the phint value linked to the key. This may be one the following values:
For rules created by Oracle service teams, the operator may be one of the following read-only values. These operators may be made available for rule creation in a future vesions of the Taxonomy Manager:
|
YES | YES | |||||||||||||||||||||||||||||||||||||||||||||
Value1 | The phint value. Phint values support all Latin-1 and UTF-8 characters (alphanumeric characters and special symbols). | YES | YES | |||||||||||||||||||||||||||||||||||||||||||||
Category ID |
The unique ID assigned to the category. This column is required for editing categories via bulk upload because Taxonomy Manager identifies categories based on the unique category IDs. |
YES | YES | |||||||||||||||||||||||||||||||||||||||||||||
Category Path | The full taxonomy path of the category. This column is required for adding categories with rules via bulk upload because Taxonomy Manager determines where to create new categories based on the taxonomy path. | NO | NO |
Bulk import demo
The sample bulk_rules_import.py Python code demonstrates how to do a bulk rules import using the Rules API. To run this script, you must have the following:
- Python 2.7+
- Requests library 1.2.3 (or later)
You can use PIP (a Python Package Installation tool) to help install the requests library. To download and install PIP, install the requests library, and then delete the PIP installation file, enter the following commands in your console:
curl -O https://raw.github.com/pypa/pip/master/contrib/get-pip.py
sudo python get-pip.py
sudo pip install requests
rm get-pip.py
To run this script, you need to create a TSV file named rule_import.tsv (download template) that contains the categories you want to edit or create, and provide the following parameters:
url
: The URL of the production environment (services.bluekai.com)verbosity
: Enter a series of four verbose options for printing information.partnerid
: The partner ID associated with the seat for which you are uploading rules.bkuid
: Your web service user keybksecretkey
: Your web service private key
The following example demonstrates the required syntax for calling this script:
bulk_rules_import.py --url https://services.bluekai.com -v -v -v -v --partnerid BlueKai Partner ID--bkuid WebServiceUserKey --bksecretkey WebServicePrivateKey
#! /usr/bin/env python -B
# -*- coding: utf-8 -*-
import sys, requests, json, argparse, unittest, hmac, base64, urllib, urlparse, hashlib
def cli_options():
parser = argparse.ArgumentParser(description='Demo for Rule REST API')
parser.add_argument('-u','--url', default='https://localhost:8080/', help='Web service base URL')
parser.add_argument('-p','--partnerid', help='Partner id to use with this request')
parser.add_argument('-i','--bkuid', default='', help='BlueKai UID')
parser.add_argument('-k','--bksecretkey', default='', help='BlueKai Secret key')
parser.add_argument('-v','--verbose', default=0, action='count', help='Prints additional information')
return parser.parse_args()
args = cli_options()
URL = args.url.strip()
BKUID = args.bkuid
BKSECRETKEY = args.bksecretkey
PARTNERID = args.partnerid
VERBOSITY = args.verbose
USER_AGENT = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:22.0) Gecko/20100101 Firefox/22.0'}
JSON_HEADERS = {'Content-Type': 'multipart/form-data', 'Accept':'application/json'}
COMMON_HEADERS = dict(USER_AGENT.items() + JSON_HEADERS.items())
class RuleRest():
res = False
def info(self, message, verbosityLevel = 1):
if VERBOSITY >= verbosityLevel:
if not isinstance(message, basestring):
print json.dumps(message, indent=4)
else:
print message
def prepare_headers(self, headers = None):
if headers is None:
return COMMON_HEADERS.copy()
else:
return dict(COMMON_HEADERS.items() + headers.items())
def parse_query_params(self, query):
parameterList = query.split('&')
params = {}
if len(parameterList) > 0:
for entry in parameterList:
kvPair = entry.split('=')
params[kvPair[0]] = kvPair[1] if len(kvPair) > 1 else '';
return params
def prepare_request(self, endpoint, method = 'GET', params = None, data = None, headers = None, files = None, sign=True):
if files is not None:
headers.pop('Content-Type', None)
req = requests.Request(method, URL + endpoint, data = data, headers = headers, files = files)
prepared = req.prepare()
if sign:
if params is None:
params = {}
parsedUrl = urlparse.urlparse(URL)
parsedEndpoint = urlparse.urlparse(endpoint)
servletPath = "" if parsedEndpoint.path.strip().startswith("/") else "rest/"
urlPath = parsedUrl.path.strip('/')
if urlPath:
urlPath = urlPath + '/'
fullPath = '/'+ urlPath + servletPath + parsedEndpoint.path.strip('/')
stringToSign = method + fullPath
params = dict(params.items() + self.parse_query_params(parsedUrl.query).items() + self.parse_query_params(parsedEndpoint.query).items())
queryParameterStr = '';
for key in params.keys():
if len(key) > 0:
if isinstance(params[key], list):
for listItem in params[key]:
value = urllib.quote(str(listItem))
stringToSign += value
queryParameterStr += urllib.quote(key) + '=' + value + '&'
else:
value = urllib.quote(str(params[key]))
stringToSign += value
queryParameterStr += urllib.quote(key) + '=' + value + '&'
if prepared.body is not None:
stringToSign += prepared.body
h = hmac.new(BKSECRETKEY, stringToSign.strip(), hashlib.sha256)
s = base64.standard_b64encode(h.digest())
signature = urllib.quote_plus(s)
finalURL = parsedUrl.scheme + '://' + parsedUrl.netloc + fullPath + '?' + queryParameterStr + 'bkuid=' + BKUID + '&bksig=' + signature
else:
finalURL = URL + endpoint
self.info('Sending %s request to: %s' %(method, finalURL))
prepared.url = finalURL
if VERBOSITY >=4:
print "Request object:"
for key, value in prepared.headers.iteritems():
print "%s: %s" % (key, value)
if prepared.body is not None and len(prepared.body)>0:
print ""
print prepared.body
return prepared
def post(self, endpoint, payload = None, params = None, headers = None, files = None):
if payload is not None:
data = payload if isinstance(payload, basestring) else json.dumps(payload)
else:
data = None
self.res = requests.Session().send(self.prepare_request(endpoint, method = 'POST', params = params, data = data, files = files, headers = self.prepare_headers(headers)), verify = False)
return self
def test_bulk_rule_rest_create(self):
files = {'file': open('rule_import.tsv', 'rb')}
created_rules = self.post('taxonomyRuleChains/import', files = files, params={'partner.id':PARTNERID}).res.json()
self.info(created_rules, 2)
instance=RuleRest()
instance.test_bulk_rule_rest_create()
Update a rule
To update a rule, include your partner ID, the rule ID, and a request body with the parameters to be updated in a PUT call.
Sample PUT request:
https://services.bluekai.com/rest/taxonomyRuleChains/?partner.id={yourPartnerId}
Rules with Multi-byte Characters
To create rules for URLs that include multibyte encodings, you must encode the percentage symbols (%) in the UTF-8 encoded characters. For example, to create a URL rule for https://www.マネジメント/site.html
, convert マネジメント to UTF-8, which results in the following encoding:
%e3%83%9e%e3%83%8d%e3%82%b8%e3%83%a1%e3%83%b3%e3%83%88
Encode the percentage symbols in the UTF-8 encoding (convert each % symbol to %25), which results in the following encoding:
%25e3%2583%259e%25e3%2583%258d%25e3%2582%25b8%25e3%2583%25a1%25e3%2583%25b3%25e3%2583%2588
This results in the following encoded string:
https://www.com%2F%25e3%2583%259e%25e3%2583%258d%25e3%2582%25b8%25e3%2583%25a1%25e3%2583%25b3%25e3%2583%2588%2Fsite.html
See also: Percent-encoding
Related API calls
These are the API calls you will typically make before you use the rules API:
Before rules API | Use case |
---|---|
Containers API | The use case for the containers API depends on which data ingest method you are using to transfer your data into the Oracle Data Cloud platform (online ingest, offline onboard, user data API, or mobile ingest):
|
Categories API | Add first-party categories to your private taxonomy. |
These are the API calls you will typically make after you use the taxonomy rule chains API:
After rules API | Use case |
---|---|
Audiences API | Create a target audience that includes your self-classified first-party categories. |
Categories API | View your categories and their inventory. |
GET response summary
The taxonomy rule chains API GET request returns the rules used to map your categories with your site and offline data. Here are the properties included for each rule:
Property | Type | Description | ||||||||||||||||||||||||||||||||||||||||||
status
|
enum | The current status of the rule chain: "active", "draft", or "flagged". | ||||||||||||||||||||||||||||||||||||||||||
rules
|
array | A list of rules in the rule chain. The properties listed below belong to the Rules object. | ||||||||||||||||||||||||||||||||||||||||||
- status |
enum | The current status of the rule: "active", "draft", or "flagged". | ||||||||||||||||||||||||||||||||||||||||||
- taxonomyRuleOperatorParams |
array | A list of key-value pairs in the rule. For example: { "name": "key", "value": "one-changed" }, { "name": "value1", "value": "1" }, |
||||||||||||||||||||||||||||||||||||||||||
- note
|
string | Any user-specified notes related to the rule. | ||||||||||||||||||||||||||||||||||||||||||
- taxonomyRuleOperator |
object | Specifies the logic used to evaluate the phints in the taxonomyRuleOperatorParams object. This includes the id, name, and description of the operator, which may be one of the following values:
|
||||||||||||||||||||||||||||||||||||||||||
createdAt
|
string | A GMT time stamp indicating when the rule chain was created (YYYY-MM-DDTHH:MM:SS+0000). | ||||||||||||||||||||||||||||||||||||||||||
updatedAt
|
string | A GMT time stamp indicating when the rule chain was last updated (YYYY-MM-DDTHH:MM:SS+0000). | ||||||||||||||||||||||||||||||||||||||||||
id
|
int | The unique ID generated for the rule chain. You will need this ID to update the rule chain via a PUT request. | ||||||||||||||||||||||||||||||||||||||||||
categories
|
object | The category (id and name) for which the rule chain is applicable. | ||||||||||||||||||||||||||||||||||||||||||
sites
|
int | A comma-separated list of the site IDs/containers for which the rule is applicable. If the rule is applicable to all site IDs, the list is empty and the partner ID appears in the partners list. |
||||||||||||||||||||||||||||||||||||||||||
partners
|
int | If the rule is applicable to all site IDs, your partner ID appears in this list. If the rule is applicable to only one or more site IDs, this parameter is empty, and the site IDs are included in the sites list. |
POST response errors
If the POST request for creating categories fails, the POST response will use one of the following codes:
Code | Error message | Description |
---|---|---|
400 | Bad Request | The body of the POST response will contain short description of the problems with the POST request. |
401 | Unauthorized | You need to authenticate the request. See authentication and authorization for more information. |
403 | Forbidden | You have reached the maximum number of categories (by default, the limit is 100). |
404 | Not Found | The specified parent category is either not in your taxonomy or is not in your Partner seat |
The body of the POST response will contain a list of error codes for each of the input attributes causing the error, which are as follows:
Code | Description |
---|---|
BK-10001 | Could not find resource for the specified path |
BK-10002 | Bad query parameters |
BK-10003 | Invalid JSON input |
BK-10004 | Input JSON does not pass schema validation |
BK-10005 | Input JSON contain bad property |
BK-10006 | Input JSON has missing properties |
BK-10007 | Input JSON has bad property that does not match min length requirement |
BK-10008 | Input JSON has bad property that does not match max length requirement |
BK-10009 | Not enough privileges to access requested resource |
BK-10010 | The request could not be completed by the service due to malformed data or syntax |
BK-10011 | Incorrect sorting parameter |
BK-10012 | Additional properties detected. Schema does not allow extra properties to be present |
BK-26001 | Taxonomy rule chain was not found |