Create Alert

Create an alert on the specified view.

REQUEST URI

https://<ZohoAnalytics_Server_URI>/restapi/v2/workspaces/<workspace-id>/views/<view-id>/alerts

Post

oauthscope: ZohoAnalytics.modeling.create

QUERY PARAMETERS

 

Parameter Name
Description
CONFIG*JSONObject
Config parameter specifications are available in the below section.

FIELDS FOR CONFIG JSON

 

Key
Description
Alert details
alertName*String
The name of the alert.
Must be unique within the view.
Maximum length - 100 characters.

Sample: {"alertName":"Sales Drop Alert"}
summaryTypeString
The slice of the report data against which the rules are evaluated.
Supported values: "data", "subTotal", "grandTotal"
Maximum length - 50 characters.
Default value - data.
This attribute is mandatory when the view is a pivot table.
Check the table summaryType Values for more details.

Sample: {"summaryType":"subTotal"}
rowAxisString
The viewColumnIndex of the row axis column of a pivot or summary view, sent as a string.
This attribute is mandatory when summaryType is subTotal on a pivot or summary view.

Sample: {"rowAxis":"1"}
columnAxisString
The viewColumnIndex of the column axis column of a pivot or summary view, sent as a string.

Sample: {"columnAxis":"5"}
conditionExpressionString
The expression that combines the rules using their position in rules, starting from 1.
Supported tokens: rule numbers, AND, OR, ( and ).
Maximum length - 1000 characters.
Default value - (1).
This attribute is mandatory when rules has more than one rule.

Sample: {"conditionExpression":"(1 AND 2) OR 3"}
notifyOnChangeBoolean
Controls whether a notification is sent only when the alert condition changes from unmet to met, instead of on every evaluation in which the condition is met.
Supported values: "true", "false"
Default value - false.

Sample: {"notifyOnChange":true}
isAnomalyBoolean
Indicates whether the rules of the alert are anomaly rules.
This attribute is accepted but ignored. The value is derived from rules.

Sample: {"isAnomaly":false}
Schedule
scheduleDetails*JSONObject
The schedule on which the alert is evaluated.
Maximum length - 5000 characters.
Check the table scheduleDetails Fields for more details.

Sample: {"scheduleDetails":{"calendarFrequency":"daily","hour":9,"minute":0}}
Notification channels
emailJSONObject
The email notification settings of the alert.
Maximum length - 10000 characters.
Check the table email Fields for more details.

Sample: {"email":{"notifyAdmins":true,"subject":"Sales dropped below threshold","message":"Please review the report."}}
notificationJSONObject
The in-app notification settings of the alert.
Maximum length - 10000 characters.
Check the table notification Fields for more details.

Sample: {"notification":{"notifyAdmins":true,"notifySharedUsers":false,"subject":"Sales spike detected","message":"An anomaly was detected on Sales."}}
slackJSONObject
The Slack incoming webhook settings of the alert.
Maximum length - 50000 characters.
Check the table slack and msteams Fields for more details.

Sample: {"slack":{"url":"https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXX","messageType":"STANDARD","subject":"New East/West orders","message":"Orders from the East and West regions were detected."}}
msteamsJSONObject
The Microsoft Teams incoming webhook settings of the alert. Uses the same structure as slack.
Maximum length - 50000 characters.
Check the table slack and msteams Fields for more details.

Sample: {"msteams":{"url":"https://example.webhook.office.com/webhookb2/00000000-0000-0000-0000-000000000000","messageType":"CUSTOM","payload":"{\"text\":\"New East/West orders detected\"}"}}
webhookJSONObject
The webhook settings of the alert.
Maximum length - 100000 characters.
Check the table webhook Fields for more details.

Sample: {"webhook":{"url":"https://example.com/zoho-analytics/audit-hook","method":"POST","body":"{\"event\":\"biennialAudit\"}"}}
Zoho Flow mappings
workflowsJSONArray
The Zoho Flow workflows mapped to the alert.
This attribute is not supported in this API, since a workflow can be mapped only after the alert is created. Use the Update Alert API instead.
Maximum length - 10000 characters.
actionsByFlowJSONArray
The Zoho Flow actions mapped to the alert.
This attribute is not supported in this API, since an action can be mapped only after the alert is created. Use the Update Alert API instead.
Maximum length - 100000 characters.
Rules
rules*JSONArray
The rules against which the report data is evaluated.
Supported range - 1 to 10 rules.
Maximum length - 100000 characters.
Check the table rules Fields for more details.

Sample: {"rules":[{"operator":"lt","viewColumnIndex":"2","type":"constant","values":["1000"]}]}
Validation
validateSystemTagsBoolean
Controls whether the Data Warning system tags of the view are validated when the alert attaches the report to an email.
When true and the view has a restricted Data Warning tag, the alert is not created. Set it to false to skip the validation.
This attribute has no effect when the report is not attached.
Supported values: "true", "false"
Default value - true.

Sample: {"validateSystemTags":false}

Note: At least one notification channel (email, notification, slack, msteams or webhook) must be specified. A channel without a recipient is not saved, and the alert is not created if no other channel is available.

Note: The Zoho Cliq channel is not supported in this API.

summaryType Values

 

Value
Description
dataEvaluates the rules against the data rows of the report.
Default value for chart and summary views.
subTotalEvaluates the rules against the sub total rows.
Supported only for pivot and summary views. rowAxis is mandatory for this value.
grandTotalEvaluates the rules against the grand total row.
Supported only for pivot and summary views.

scheduleDetails Fields

 

Key
Description
Frequency and time zone
calendarFrequency*String
How often the alert is evaluated.
Supported values: "hourly", "daily", "weekly", "monthly", "yearly"
The value is case-insensitive.
Check the table calendarFrequency Values for more details.

Sample: {"calendarFrequency":"daily"}
intervalInteger
The number of calendarFrequency units between two evaluations.
Supported values:
hourly - 1, 2, 3, 4, 6 or 12.
daily - 1 to 7.
weekly - 1 to 4.
monthly - 1 to 12.
yearly - 1 to 5.
Default value - 1.
This attribute is mandatory for hourly frequency.

Sample: {"interval":3}
timeZoneString
The IANA time zone ID used to evaluate the schedule. For example, Asia/Kolkata, America/New_York, Europe/London or UTC.
Default value - The time zone of the user profile. If it is not available, GMT is used.

Sample: {"timeZone":"Asia/Kolkata"}
Time of day
hourInteger
The hour of the day at which the alert is evaluated.
Supported range - 0 to 23.
This attribute is mandatory for all frequencies except hourly, and must not be specified for hourly.

Sample: {"hour":9}
minuteInteger
The minute of the hour at which the alert is evaluated.
Supported values: multiples of 5 from 0 to 55.
This attribute is mandatory for all frequencies except hourly, and must not be specified for hourly.

Sample: {"minute":30}
Day selection
skipWeekendsBoolean
Controls whether the evaluations that fall on weekend days are skipped.
The weekend days are based on the locale of the schedule time zone. For example, Sunday for Asia/Kolkata, and Saturday and Sunday for America/New_York.
Supported values: "true", "false"
Default value - false.
Applicable only to hourly and daily frequencies.

Sample: {"skipWeekends":true}
weekDaysJSONArray
The days of the week on which the alert is evaluated. Multiple days can be specified.
Supported values: 1 (Sunday) to 7 (Saturday).
This attribute is mandatory for weekly frequency, and must not be specified for other frequencies.

Sample: {"weekDays":[2,4]}
monthDaysJSONArray
The dates of the month on which the alert is evaluated.
Supported values: 1 to 31, or 99 for the last day of the month. 99 cannot be combined with other dates.
For monthly frequency, multiple dates can be specified. For yearly frequency, exactly one date must be specified.
Applicable only to monthly and yearly frequencies. For these frequencies, either monthDays, or weekOfMonth along with dayOfWeek, must be specified.

Sample: {"monthDays":[1,15]}
weekOfMonthInteger
The occurrence of dayOfWeek within the month.
Supported values: 1 (first) to 4 (fourth), 5 (last).
Must be specified along with dayOfWeek. Applicable only to monthly and yearly frequencies.

Sample: {"weekOfMonth":5}
dayOfWeekInteger
The day of the week used along with weekOfMonth. For example, weekOfMonth 2 with dayOfWeek 3 means the second Tuesday of the month.
Supported values: 1 (Sunday) to 7 (Saturday).
Must be specified along with weekOfMonth. Applicable only to monthly and yearly frequencies.

Sample: {"dayOfWeek":6}
monthsJSONArray
The months in which the alert is evaluated. Multiple months can be specified.
Supported values: 1 (January) to 12 (December).
This attribute is mandatory for yearly frequency, and must not be specified for other frequencies.

Sample: {"months":[1,7]}

Note: A field specified for a frequency that it does not apply to is not accepted.

Note: For monthly and yearly frequencies, specify either monthDays, or weekOfMonth along with dayOfWeek. Specifying both or neither is not supported.

Note: Sample schedules for each frequency:
Hourly: {"calendarFrequency": "hourly", "interval": 6, "skipWeekends": true}
Daily: {"calendarFrequency": "daily", "interval": 3, "hour": 9, "minute": 30, "skipWeekends": true}
Weekly: {"calendarFrequency": "weekly", "interval": 2, "hour": 9, "minute": 30, "weekDays": [2, 4]}
Monthly, by date: {"calendarFrequency": "monthly", "hour": 9, "minute": 30, "monthDays": [1, 15]}
Monthly, by weekday: {"calendarFrequency": "monthly", "interval": 3, "hour": 9, "minute": 30, "weekOfMonth": 5, "dayOfWeek": 6}
Yearly, by date: {"calendarFrequency": "yearly", "hour": 9, "minute": 30, "months": [1, 7], "monthDays": [15]}
Yearly, by weekday: {"calendarFrequency": "yearly", "interval": 2, "hour": 6, "minute": 0, "months": [4], "weekOfMonth": 1, "dayOfWeek": 2}

calendarFrequency Values

 

Value
Description
hourlyEvaluates the alert every N hours.
hour and minute are not used. interval is mandatory and supports 1, 2, 3, 4, 6 or 12.
dailyEvaluates the alert every N days at a fixed time.
interval supports 1 to 7.
weeklyEvaluates the alert every N weeks on the selected weekDays.
interval supports 1 to 4. weekDays is mandatory.
monthlyEvaluates the alert every N months on a date or on the Nth weekday.
interval supports 1 to 12. Exactly one day selection must be specified.
yearlyEvaluates the alert every N years in the selected months.
interval supports 1 to 5. months is mandatory, exactly one day selection must be specified, and monthDays supports only one date.

email Fields

 

Key
Description
Content
subject*String
The subject of the email.
Maximum length - 500 characters.

Sample: {"subject":"Sales dropped below threshold"}
message*String
The body of the email.
HTML content is supported. When systemMailId is true, all HTML is removed.
Maximum length - 5000 characters.

Sample: {"message":"Please review the report."}
Recipients
notifyAdminsBoolean
Controls whether the workspace admins are added to the recipients.
Supported values: "true", "false"
Default value - false.

Sample: {"notifyAdmins":true}
emailIdsJSONArray
The email addresses of the recipients.
Maximum - 25 email addresses.

Sample: {"emailIds":["jane.doe@example.com","manager@example.com"]}
groupIdsJSONArray
The IDs of the workspace groups whose members receive the email, sent as strings.
Supported range - 1 to 1000 groups.

Sample: {"groupIds":["137687000002108009"]}
Attachments
includeReportBoolean
Controls whether the report is included in the email.
Supported values: "true", "false"
Default value - false.

Sample: {"includeReport":true}
attachmentTypeString
How the report is included in the email.
Supported values: "inline", "attachment"
This attribute is mandatory when includeReport is true.
Check the table attachmentType Values for more details.

Sample: {"attachmentType":"inline"}
attachFilteredDatasetBoolean
Controls whether the data of the rows that matched the alert rules is attached.
This can be set independently of includeReport.
Supported values: "true", "false"
Default value - false.

Sample: {"attachFilteredDataset":true}
Sender
systemMailIdBoolean
Controls whether the email is sent from the Zoho Analytics system mail ID instead of the email address of the alert creator.
The display email settings of the organization can override this setting.
Supported values: "true", "false"
Default value - false.

Sample: {"systemMailId":false}

Note: The email channel must have at least one recipient. If notifyAdmins is false and both emailIds and groupIds are empty, the channel is not saved.

Note: Up to 25 email addresses can be specified in emailIds. To notify a larger audience, use groupIds or notifyAdmins.

attachmentType Values

 

Value
Description
inlineDisplays the report within the email body.
attachmentSends the report as a file attachment.

notification Fields

 

Key
Description
notifyAdmins*Boolean
Controls whether the workspace admins are notified.
Supported values: "true", "false"

Sample: {"notifyAdmins":true}
notifySharedUsers*Boolean
Controls whether all the users with whom the view is shared are notified.
Supported values: "true", "false"

Sample: {"notifySharedUsers":false}
subject*String
The title of the notification.
Maximum length - 500 characters.

Sample: {"subject":"Sales spike detected"}
message*String
The body of the notification.
HTML content is supported.
Maximum length - 5000 characters.

Sample: {"message":"An anomaly was detected on Sales."}

Note: At least one of notifyAdmins and notifySharedUsers must be true. Otherwise, the channel is not saved.

slack and msteams Fields

 

Key
Description
url*String
The incoming webhook URL of the channel.
The URL must start with https://.
Maximum length - 5000 characters.

Sample: {"url":"https://hooks.slack.com/services/T00000000/B00000000/XXXXXXXXXXXX"}
messageType*String
How the message is composed.
Supported values: "STANDARD", "CUSTOM"
The value is case-insensitive.
Check the table messageType Values for more details.

Sample: {"messageType":"STANDARD"}
subjectString
The subject of the message.
Maximum length - 500 characters.
This attribute is mandatory when messageType is STANDARD.

Sample: {"subject":"New East/West orders"}
messageString
The body of the message. Used only when messageType is STANDARD.
Maximum length - 5000 characters.
Default value - empty string.

Sample: {"message":"Orders from the East and West regions were detected."}
payloadString
The custom message posted to the webhook, specified as a JSON object or array serialized into a string. Used only when messageType is CUSTOM.
Maximum length - 50000 characters.
This attribute is mandatory when messageType is CUSTOM.

Sample: {"payload":"{\"text\":\"New East/West orders detected\"}"}

Note: The slack and msteams objects use the same structure.

messageType Values

 

Value
Description
STANDARDZoho Analytics composes the message using subject and message.
subject is mandatory. payload is ignored.
CUSTOMPosts the specified payload as is, so that formats such as Slack Block Kit or Microsoft Teams message cards can be used.
payload is mandatory and must be valid JSON. subject and message are ignored.

webhook Fields

 

Key
Description
url*String
The target URL of the webhook.
The URL must start with https://.
Maximum length - 5000 characters.

Sample: {"url":"https://example.com/zoho-analytics/alert-hook"}
methodString
The HTTP method used to invoke the webhook.
Supported values: "GET", "POST", "PUT", "PATCH", "DELETE"
Maximum length - 10 characters.
Default value - POST.
Check the table method Values for more details.

Sample: {"method":"POST"}
bodyString
The raw request body sent to the webhook. The content is not validated.
Maximum length - 50000 characters.
Default value - empty string.

Sample: {"body":"{\"event\":\"newOrders\",\"severity\":\"info\"}"}
paramsJSONArray
The query or form parameters added to the request.
Supported range - 0 to 10 parameters.
Maximum length - 50000 characters.
Check the table params and headers Fields for more details.

Sample: {"params":[{"name":"source","value":"analytics"}]}
headersJSONArray
The additional HTTP headers sent with the request.
Supported range - 0 to 10 headers.
Maximum length - 10000 characters.
Check the table params and headers Fields for more details.

Sample: {"headers":[{"name":"X-Source","value":"ZohoAnalytics"}]}

method Values

 

Value
Description
GETInvokes the webhook with an HTTP GET request.
POSTInvokes the webhook with an HTTP POST request. This is the default method.
PUTInvokes the webhook with an HTTP PUT request.
PATCHInvokes the webhook with an HTTP PATCH request.
DELETEInvokes the webhook with an HTTP DELETE request.

params and headers Fields

 

Key
Description
name*String
The name of the parameter or header.
Supported length - 1 to 255 characters.

Sample: {"name":"X-Source"}
value*String
The value of the parameter or header.
Maximum length - 5000 characters.

Sample: {"value":"ZohoAnalytics"}

Note: The params and headers arrays use the same structure. The values are stored encrypted, and are returned decrypted by the Get Alert Configuration API.

rules Fields

 

Key
Description
operator*String
The comparison operator of the rule. It must be one of the allowedOperators of the column, returned by the Get View Metadata For Alert API.
Supported values:
Comparison - is, isnot, gt, lt, gte, lte, btw, notbtw.
Null check - isn, notisn.
Relative date - curYear, prevYear, nextYear, curQuarter, prevQuarter, nextQuarter, curMonth, prevMonth, nextMonth, curWeek, prevWeek, nextWeek, today, yest, tom.
N period date - prevNYears, lastNYears, nextNYears, prevNQuarters, lastNQuarters, nextNQuarters, prevNMonths, lastNMonths, nextNMonths, prevNWeeks, lastNWeeks, nextNWeeks, prevNDays, lastNDays, nextNDays.
Anomaly - sinceLastAlert. For anomaly rules, the operator must be one of the allowedAnomalyOperators of the view.
Maximum length - 50 characters.

Sample: {"operator":"lt"}
viewColumnIndexString
The position of the column that the rule tests, as returned by the Get View Metadata For Alert API.
The value must be sent as a string.
This attribute is mandatory for rules without anomaly, and must not be specified for anomaly rules.

Sample: {"viewColumnIndex":"2"}
typeString
What the column is compared with. It must be one of the allowedRuleTypes of the column.
Supported values: "constant", "column", "threshold"
Default value - constant.
Check the table type Values for more details.

Sample: {"type":"constant"}
valuesJSONArray
The values to compare with, sent as strings.
Supported range - 1 to 300 values.
Maximum length - 5000 characters.
The number of values required depends on the operator and the column. Must not be specified for operators that take no value, such as isn, notisn and sinceLastAlert.

Sample: {"values":["10000","50000"]}
anomalyJSONObject
Makes the rule an anomaly rule.
If one rule has anomaly, all the rules must have it. Supported only on chart views.
Maximum length - 10000 characters.
Check the table anomaly Fields for more details.

Sample: {"anomaly":{"name":"Sales Spike","value":"","comboType":"top","comboTypeValue":"5"}}

Note: The number of entries in values depends on the operator and the column:
When type is column: one entry, the viewColumnIndex of another NUMBER column in the same view.
When type is threshold: one entry, a threshold name from the thresholds of the column, for example "T1".
btw and notbtw: two entries, the lower bound followed by the upper bound.
is and isnot on a categorical or date bucket column: one or more entries.
is and isnot on a NUMBER, DATE or TIMESTAMP column: exactly one entry.
gt, lt, gte and lte: exactly one entry.
N period date operators, such as prevNMonths: one entry, the value of N as a numeric string.
isn, notisn, sinceLastAlert and the relative date operators, such as curYear and today: values must not be specified.

Note: For DATE and TIMESTAMP columns, the values used with is, isnot, gt, lt, gte, lte, btw and notbtw must be in the yyyy-MM-dd HH:mm:ss or yyyy-MM-dd format. When only the date is specified, the time defaults to 00:00:00.

Note:viewColumnIndex is based on the position of the column, and changes when the report is edited. Get the latest values using the Get View Metadata For Alert API before you create or update an alert.

type Values

 

Value
Description
constantCompares the column with a constant value.
Always available. Used by default when type is not specified.
columnCompares the column with another NUMBER column of the same view.
Available only when the view has at least two NUMBER columns. Supported only on chart views.
thresholdCompares the column with a chart threshold, such as T1 or T2.
Available only when the column has at least one threshold. Supported only on chart views.

anomaly Fields

 

Key
Description
name*String
The name of an anomaly configured on the view, as returned in anomalies by the Get View Metadata For Alert API. The name must match exactly.
Maximum length - 100 characters.

Sample: {"name":"Sales Spike"}
valueString
The argument of the anomaly operator, when the operator takes one. For example, the N of lastNMonths.
Maximum length - 1000 characters.
Default value - empty string.

Sample: {"value":""}
comboTypeString
How the detected anomalies are considered.
Supported values: "top", "all"
Maximum length - 5 characters.
Default value - empty string.
Check the table comboType Values for more details.

Sample: {"comboType":"top"}
comboTypeValueString
The number of top anomalies to consider, sent as a numeric string. It must be a positive integer.
Maximum length - 10 characters.
Default value - empty string.
This attribute is mandatory when comboType is top.

Sample: {"comboTypeValue":"5"}

comboType Values

 

Value
Description
topConsiders only the N most significant anomalies.
comboTypeValue must be a positive integer.
allConsiders all the detected anomalies.
comboTypeValue is ignored.

Sample Request:

Copiedcurl "https://analyticsapi.zoho.com/restapi/v2/workspaces/35130000001055707/views/35130000001055717/alerts" -X 'POST' -H 'ZANALYTICS-ORGID: <org-id>' -H 'Authorization: Zoho-oauthtoken <access_token>' --data-urlencode 'CONFIG={"alertName":"Sales Drop Alert","scheduleDetails":{"calendarFrequency":"daily","hour":9,"minute":0},"email":{"notifyAdmins":true,"subject":"Sales dropped below threshold","message":"Please review the report."},"rules":[{"operator":"lt","viewColumnIndex":"2","type":"constant","values":["1000"]}]}'
Copiedusing System;
using System.Collections.Generic;
using System.Text.Json;
using ZohoAnalytics;

namespace ZohoAnalyticsTest
{
    class Program
    {
        long orgId = 55522777;
        long workspaceId = 35130000001055707;
        long viewId = 35130000001055717;

        public void CreateAlert(IAnalyticsClient ac)
        {
            string alertName = "Sales Drop Alert";
            Dictionary<string, object> scheduleDetails = JsonSerializer.Deserialize<Dictionary<string, object>>("{\"calendarFrequency\":\"daily\",\"hour\":9,\"minute\":0}");
            List<Dictionary<string, object>> rules = JsonSerializer.Deserialize<List<Dictionary<string, object>>>("[{\"operator\":\"lt\",\"viewColumnIndex\":\"2\",\"type\":\"constant\",\"values\":[\"1000\"]}]");
            Dictionary<string, object> config = JsonSerializer.Deserialize<Dictionary<string, object>>("{\"email\":{\"notifyAdmins\":true,\"subject\":\"Sales dropped below threshold\",\"message\":\"Please review the report.\"}}");
            IViewAPI view = ac.GetViewInstance(orgId, workspaceId, viewId);
            long result = view.CreateAlert(alertName, scheduleDetails, rules, config);
            Console.WriteLine(result);
        }

        static void Main(string[] args)
        {
            string clientId = "1000.xxxxxxx";
            string clientSecret = "xxxxxxx";
            string refreshToken = "1000.xxxxxxx.xxxxxxx";
            IAnalyticsClient ac = new AnalyticsClient(clientId, clientSecret, refreshToken);
            Program obj = new Program();
            obj.CreateAlert(ac);
        }
    }
}
Copiedpackage main

import (
    "fmt"
    ZAnalytics "zoho/pkg/analyticsclient"
)

var (
    clientId = "1000.xxxxxxx"
    clientSecret = "xxxxxxx"
    refreshToken = "1000.xxxxxxx.xxxxxxx"
    orgId = "55522777"
    workspaceId = "35130000001055707"
    viewId = "35130000001055717"
)

func CreateAlert(ac ZAnalytics.Client) {
    alertname := "Sales Drop Alert"
    scheduledetails := map[string]interface{}{
        "calendarFrequency": "daily",
        "hour": 9,
        "minute": 0,
    }
    rules := []interface{}{
        map[string]interface{}{
            "operator": "lt",
            "viewColumnIndex": "2",
            "type": "constant",
            "values": []string{"1000"},
        },
    }
    config := map[string]interface{}{
        "email": map[string]interface{}{
            "notifyAdmins": true,
            "subject": "Sales dropped below threshold",
            "message": "Please review the report.",
        },
    }
    view := ZAnalytics.GetViewInstance(&ac, orgId, workspaceId, viewId)
    result, exception := view.CreateAlert(alertname, scheduledetails, rules, config)
    if exception != nil {
        fmt.Println(exception.ErrorMessage)
        return
    }
    fmt.Println(result)
}

func main() {
    ac := ZAnalytics.GetAnalyticsClient(clientId, clientSecret, refreshToken)
    CreateAlert(ac)
}
Copiedimport com.zoho.analytics.client.*;
import org.json.*;

public class Test {
    private long orgId = 55522777l;
    private long workspaceId = 35130000001055707l;
    private long viewId = 35130000001055717l;

    public static void main(String args[]) {
        String clientId = "1000.xxxxxxx";
        String clientSecret = "xxxxxxx";
        String refreshToken = "1000.xxxxxxx.xxxxxxx";
        Test tObj = new Test();
        AnalyticsClient ac = new AnalyticsClient(clientId, clientSecret, refreshToken);
        try {
            tObj.createAlert(ac);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public void createAlert(AnalyticsClient ac) throws Exception {
        String alertName = "Sales Drop Alert";
        JSONObject scheduleDetails = new JSONObject("{\"calendarFrequency\":\"daily\",\"hour\":9,\"minute\":0}");
        JSONArray rules = new JSONArray("[{\"operator\":\"lt\",\"viewColumnIndex\":\"2\",\"type\":\"constant\",\"values\":[\"1000\"]}]");
        JSONObject config = new JSONObject("{\"email\":{\"notifyAdmins\":true,\"subject\":\"Sales dropped below threshold\",\"message\":\"Please review the report.\"}}");
        ViewAPI view = ac.getViewInstance(orgId, workspaceId, viewId);
        long result = view.createAlert(alertName, scheduleDetails, rules, config);
        System.out.println(result);
    }
}
Copied<?php
require 'AnalyticsClient.php';

class Test {
    public $ac;
    public $org_id = "55522777";
    public $workspace_id = "35130000001055707";
    public $view_id = "35130000001055717";

    function __construct() {
        $this->ac = new AnalyticsClient("1000.xxxxxxx", "xxxxxxx", "1000.xxxxxxx.xxxxxxx");
    }

    function createAlert() {
        $alert_name = "Sales Drop Alert";
        $schedule_details = array(
            "calendarFrequency" => "daily",
            "hour" => 9,
            "minute" => 0
        );
        $rules = array(
            array(
                "operator" => "lt",
                "viewColumnIndex" => "2",
                "type" => "constant",
                "values" => array("1000")
            )
        );
        $config = array(
            "email" => array(
                "notifyAdmins" => true,
                "subject" => "Sales dropped below threshold",
                "message" => "Please review the report."
            )
        );
        $view = $this->ac->getViewInstance($this->org_id, $this->workspace_id, $this->view_id);
        $response = $view->createAlert($alert_name, $schedule_details, $rules, $config);
        print_r($response);
    }
}

$obj = new Test();
$obj->createAlert();
?>
Copiedfrom AnalyticsClient import AnalyticsClient

class Config:
    CLIENTID = "1000.xxxxxxx"
    CLIENTSECRET = "xxxxxxx"
    REFRESHTOKEN = "1000.xxxxxxx.xxxxxxx"
    ORGID = "55522777"
    WORKSPACEID = "35130000001055707"
    VIEWID = "35130000001055717"

class Sample:
    ac = AnalyticsClient(Config.CLIENTID, Config.CLIENTSECRET, Config.REFRESHTOKEN)

    def create_alert(self, ac):
        alert_name = "Sales Drop Alert"
        schedule_details = {
            "calendarFrequency": "daily",
            "hour": 9,
            "minute": 0
        }
        rules = [
            {
                "operator": "lt",
                "viewColumnIndex": "2",
                "type": "constant",
                "values": ["1000"]
            }
        ]
        config = {
            "email": {
                "notifyAdmins": True,
                "subject": "Sales dropped below threshold",
                "message": "Please review the report."
            }
        }
        view = ac.get_view_instance(Config.ORGID, Config.WORKSPACEID, Config.VIEWID)
        result = view.create_alert(alert_name, schedule_details, rules, config)
        print(result)

obj = Sample()
obj.create_alert(obj.ac)
Copiedvar analyticsClient = require('./AnalyticsClient');
var ac = new analyticsClient('1000.xxxxxxx', 'xxxxxxx', '1000.xxxxxxx.xxxxxxx');
var orgId = '55522777';
var workspaceId = '35130000001055707';
var viewId = '35130000001055717';

var alertName = "Sales Drop Alert";
var scheduleDetails = {
    "calendarFrequency": "daily",
    "hour": 9,
    "minute": 0
};
var rules = [
    {
        "operator": "lt",
        "viewColumnIndex": "2",
        "type": "constant",
        "values": ["1000"]
    }
];
var config = {
    "email": {
        "notifyAdmins": true,
        "subject": "Sales dropped below threshold",
        "message": "Please review the report."
    }
};
var view = ac.getViewInstance(orgId, workspaceId, viewId);
view.createAlert(alertName, scheduleDetails, rules, config).then((result) => { console.log(result); }).catch((error) => { console.log(error); });
CopiedorgId = "55522777";
workspaceId = "35130000001055707";
viewId = "35130000001055717";
headersMap = Map();
headersMap.put("ZANALYTICS-ORGID", orgId);
config = {"alertName": "Sales Drop Alert", "scheduleDetails": {"calendarFrequency": "daily", "hour": 9, "minute": 0}, "email": {"notifyAdmins": true, "subject": "Sales dropped below threshold", "message": "Please review the report."}, "rules": [{"operator": "lt", "viewColumnIndex": "2", "type": "constant", "values": ["1000"]}]};
response = invokeurl
parameters = "CONFIG=" + zoho.encryption.urlEncode(config.toString());
[
  url :"https://analyticsapi.zoho.com/restapi/v2/workspaces/" + workspaceId + "/views/" + viewId + "/alerts"
  type :POST
  parameters:parameters
  headers:headersMap
  connection:"analytics_oauth_connection"
];
info response;
Copiedrequire 'zoho_analytics_client'

class Config
  ORGID = "55522777"
  WORKSPACEID = "35130000001055707"
  VIEWID = "35130000001055717"
end

class Sample
  def initialize
    @ac = AnalyticsClient.new.with_data_center("US").with_oauth({
      "clientId" => "1000.xxxxxxx",
      "clientSecret" => "xxxxxxx",
      "refreshToken" => "1000.xxxxxxx.xxxxxxx"
    }).build
  end

  def create_alert
    alert_name = "Sales Drop Alert"
    schedule_details = {
      "calendarFrequency" => "daily",
      "hour" => 9,
      "minute" => 0
    }
    rules = [
      {
        "operator" => "lt",
        "viewColumnIndex" => "2",
        "type" => "constant",
        "values" => ["1000"]
      }
    ]
    config = {
      "email" => {
        "notifyAdmins" => true,
        "subject" => "Sales dropped below threshold",
        "message" => "Please review the report."
      }
    }
    view = @ac.get_view_instance(Config::ORGID, Config::WORKSPACEID, Config::VIEWID)
    result = view.create_alert(alert_name, schedule_details, rules, config)
    puts result
  end
end

obj = Sample.new
obj.create_alert

Download client libraries:  C# | GO | JAVA | PHP | PYTHON | NodeJS | Ruby

Sample value for CONFIG parameter:

Copied{
  "alertName": "Sales Drop Alert",
  "scheduleDetails": {
    "calendarFrequency": "daily",
    "hour": 9,
    "minute": 0
  },
  "email": {
    "notifyAdmins": true,
    "subject": "Sales dropped below threshold",
    "message": "Please review the report."
  },
  "rules": [
    {
      "operator": "lt",
      "viewColumnIndex": "2",
      "type": "constant",
      "values": [
        "1000"
      ]
    }
  ]
}

Sample Response:

CopiedHTTP/1.1 200 OK
Content-Type:application/json;charset=UTF-8

{
    "status": "success",
    "summary": "Create alert",
    "data": {
        "alertId": "137687000010815003"
    }
}