Create Custom Segment

The Create Custom Segment API can be used to create filter-based custom segments. For more information, refer to Custom Segment.

API Endpoint

API Endpoint
POST https://api-0X.moengage.com/v3/custom-segments/

Each customer is hosted on a different data center; you can find your data center number (value of X) by checking the data center and API endpoint mapping page.

Authentication

The API request will be authenticated through Basic Authentication. Basic Authentication sends a Base64-encoded string containing your username and password with every API request. It encodes a 'username:password' string in Base64 and appends the encoded string with 'Basic '. This string is included in the authorization header as shown below:

{"Authorization":"Basic bmF2ZWVua3VtYXI6bW9lbmdhZ2U="}

The username and password details can be obtained from the MoEngage Dashboard. We've revamped the settings UI in the Dashboard. If you're using the API for the first time, follow these steps for the revamped and old UIs:

Revamped UI

  1. Navigate to Settings -> Account -> APIs.
  2. Click Generate Key in the Data tile in the API Keys section, and click Save.
  3. Use the App ID as the username and the Data API Key as the password to generate the authentication header.

Old UI

  1. Navigate to Settings -> APIs -> DATA API Settings.
  2. Click Generate Key.
  3. Click Save on the Data APIs settings section. 
  4. Use the DATA API ID as the username and the DATA API KEY as the password to generate the authentication header.

Request Headers

Key Required Sample Values Description

Content-Type

Required

{"Content-Type": "application/json"}

Set the Content-Type header to application/json.

Authorization

Required

{"Authorization": "Basic bmF2ZWVua3VtYXI6bW9lbmdhZ2U=="}

This authentication parameter, used for access control, must be passed along with the request. To generate the authentication header, refer to Authentication.

MOE-APPKEY Required

{“MOE-APPKEY”: “APP ID”}

This is the APP ID of your MoEngage account. The MOE-APPKEY has to be passed along with the request. You can find your MoEngage APP ID in the MoEngage Dashboard:

Revamped UI: Settings -> Account -> APIs -> App ID

Old UI: Settings -> API -> General Settings -> DATA API

Request Body

Key Required Values Description
name Required String

This field contains the name of the custom segment to be created; it should be unique across all custom segments.

included_filters Required JSON Object

This field contains the filtering criteria used for segmentation. The users satisfying this set of filters will be a part of the segment.

Example:

"included_filters": { 

     "filter_operator": <operator_name>,

      "filters": [ Array of JSON Objects]

}

Depending on the filter type and filter criteria, the payload format will vary. For more information, refer to Included Filters Object.

Included Filters Object

The included_filters contains information about the filters used to create the custom segment. It contains the following fields:

  • filter_operator - This is an Enum(String) that contains the logical operator (logical AND and logical OR operators) used to group the filters. Allowed Values: and, or. This is a mandatory field.
  • filters - This array contains the list of filters to be combined using the filter operator. This is a mandatory field. The types of filters that can be combined are:
      • user attributes-based filters
      • action-based filters (with or without attributes).
    Each of the filter types has a different payload structure which is explained in the tables below.

    Attribute Filters

    Both user and event attributes use the same payload structure.

    Key Required Type Value Description
    filter_type Required Enum(String)

    user_attributes/

    actions

    This field is used to identify the type of filter and contains the user_attributes to be used for user-attribute query and actions for actions/event-based query.
    name Required String

    <user_atrribute

    _name>

    This field contains the name of the user attribute
    data_type Required Enum(String) string/ double/ datetime/ bool This field contains the data type of the user attribute.
    operator Required Enum(String) Allowed values based on data_type are:

    bool : is, exists

    double: is, between, lessThan, greaterThan, in, exists

    string: is, contains, startsWith, endsWith, in, exists

    datetime: inTheLast, on, between, before, after, inTheNext, exists, today

    This field contains the operators to be used in the filter. The allowed operator values depend on the data type of the user attribute used in the current filter. The operators are explained below.

    •  is - Actual value matches the given value exactly
    • exists - Value exists. Null values are considered existing values.
    • between - Actual value falls between a given range of values(value and value 1 field)
    • lessThan - Actual value is less than the given value
    • greaterThan - Actual value is greater than the given value.
    • in - Actual value matches any one of the given list of values.
    • contains - Actual value contains the given value (a regex such as .*val.*) 
    • startsWith - Actual value starts with the given value (a regex such as val.*)
    • endsWith - Actual value ends with the given value(a regex such as .*val)
    • inTheLast - Actual datetime value falls in the last N days/hours/weeks
    • on - Actual date value matches the given date
    • between - Actual datetime value falls with the given datetime values specified by the value and value1 fields
    • before - Actual datetime value falls before the given datetime
    • after - Actual datetime value falls after the given datetime
    • inTheNext - Actual datetime lies in the next N days/hours/weeks
    value

    Required for all operators except 'exists'

    based on data_type (list for 'in' operator)

    <filter value>

    This field contains the value of the user attribute to be used for the filter.

    value1

    Required for operator 'between'

    based on data_type

    <filter value2>

    This field contains the value of the user attribute to be used for the filter. In the case of between, it works as follows:

    value <= attribute_value <= value1

    negate

    Optional

    Boolean

    true/false

    This field identifies whether the current query is a negate query. The default value is false.

    For example, email != 'test.moe.com'

    In this example, the operator is 'is', negate=true, and value='test@moe.com'

    case_sensitive

    Optional

    Boolean

    true/false

    This field contains whether the string is case-sensitive. To add the case-sensitive condition for the query, choose case_sensitive=true. The default value is false.

    Action based filters

    Key Required Type Value Description
    action_name Required String <action_name>

    This field contains the name of the event using which the custom segment is filtered.

    Note: This should be the internal event name tracked by the SDK and not the readable name.

    filter_type Required Enum(String) actions This field is used to identify the type of filter. For action-based filters, the filter_type should be 'actions'.
    attributes Optional List of Objects […{…action_attributes}] This field is used to filter the users based on the event attributes. The attributes used for filters should belong to the action name provided in the action_name field. 
    executed Required Boolean true/false This field is used to determine if the current action in the query should have been performed or not.
    execution

    Required

    JSON Object

    {
      "type":"atleast",
       "count": 1
    }

    This field indicates how many times the event should’ve been performed by the user to satisfy the segmentation criteria. This JSON contains the following fields:

    • type - This field indicates the type of comparison to be made. The following values are possible: at least (the event should have been performed at least N times), exactly (the event should have been performed exactly N times), and at most (the event should have been performed at most N times). 
    • count - This field indicates the number of times the event must have been performed.
    primary_time_range

    Required

    JSON Object

    {
      "type": "between",
      "value": "2023-02-   15T00:00:00.000Z",
      "value1": "2023-0224T23:59:59.999Z",
      "value_type":     "absolute",
      "period_unit": "days"
    }

    This field contains the time range for the event. For more information, refer to Primary Time Range.

    Primary Time Range

    Key Required Type Value Description
    type Required Enum(String)

    on/inTheLast/

    before/after/

    between

    This field is used to define the type of operator used for comparison. The following values are possible, which are self-explanatory. You can refer to the examples below for your exact use cases.
    value_type Required Enum(String)

    absolute/

    relative_past

    This field indicates whether the time range specified above is relative(in terms of days) or absolute(in terms of absolute date range/threshold).
    value Required

    Integer (when the type is relative_past)

    Datetime (when the type is absolute
    ISODateFormat. Example: 2022-12-21T00:00:00.000Z)

    <int/datetime_value> The datetime value for the absolute type, or an integer in case of relative no. of days, is to be used for filtering the event execution’s date range.
    value1 Optional

    Integer (when the type is relative_past)

    Datetime (when the type is absolute
    ISODateFormat. Example: 2022-12-21T00:00:00.000Z)

    <int/datetime_value> For operators like between, we'll need 2 values for defining the date range. In that case, value and value1 correspond to the start-date and end-date, respectively.
    period_unit Required Enum(String) days/weeks/months The unit of time, in case of the relative time range. Values are self-explanatory.

Generate Request from Dashboard

To simplify the request generation, MoEngage has added an option in the dashboard, where you can specify filters in the dashboard as per your requirement and generate the payload.

Login to the MoEngage dashboard (get access). Click on Test & Debug at the bottom left in the side panel, and then click on Segment Payload.

On this page, specify the name for your segment payload, and provide the required filters. Click on Generate payload button to generate the payload.

Seg_Payload.gif

Response

Key Data Type Description
response_id String This field contains the unique response id corresponding to the current request. This field is present in the case of both successful and failed requests.
type String This field contains the type of resource referenced in the current request. Default value: custom_segment
data JSON Object

This field contains information about the custom segment created for the request. This field is present in the response only for successful requests.

Structure of data object:

"data": {

    "name": "<custom_segment_name>",

    "id": "<custom_segment_id>",

    "created_time": "<creation_timestamp>",

    "updated_time": "updation_timestamp",

    "type": "ELASTIC_SEARCH", 

    "source": "API",

    "description": "<description of custom segment>"

     "included_filters": { 

         "filter_operator": <operator_name>,

          "filters": [ Array of JSON Objects]

     }

}

For more information, refer to Response Payload.

error JSOn Object

This field contains the reason for the request's failure.

Structure:

 "error": {

    "code": "<error_code>", 

    "message": "<error_message>" 

}

The error object contains the following fields:

  • code - This field contains the error code that provides a brief explanation of the error and is a String. For example, 400 - Invalid Request, 401- Authentication required, and so on. This field is present in the response only in the case of errors.
  • message - This field describes why the request has failed and is a String. For example, in the case of 401 errors, the following message will be present: 'APP_SECRET key mismatch. Please login to the dashboard to verify key'.

Response Payload

Key Data Type Description
created_time String (datetime ISO Format) This field contains the time of custom-segment creation. This field is present in the response only for successful requests.
updated_time String (datetime ISO Format) This field contains the time of custom-segment update. The updated time can change due to internally running services too. This field is present in the response only for successful requests.
type Enum(String)

This field contains a fixed value and is used for internal purposes. Value of field: ELASTIC_SEARCH

This field is present in the response only for successful requests.

source Enum(String)

This field contains the name of the custom-segment creation source and has a fixed value for internal use. Value of field: API

This field is present in the response only for successful requests.

description String This field contains the textual description summarising the custom-segment definition. This field is present in the response only for successful requests.
included_filters JSON Object This field contains the filter criteria for custom segment creation (the included_filters section in the request payload). This field is present in the response only for successful requests.

Response Codes

Status Code Request State Description

201

Success

This response is returned when the request is processed successfully. 

400

Bad Request

This response is returned when the required parameters are missing from the request or when the provided parameters are invalid.

401

Authorization Failure

This response is returned when the authorization fails due to incorrect values for the APP KEY/ HTTP Auth Header.

409

API SECRET not configured

This response is returned when the authorization fails due to the APP SECRET key not being set on the Dashboard.

413

Unsupported media type

This response is returned when the number of filters nested, or referenced filters in the query exceeds the allowed limit.

429

Rate Limit Breach

This response is returned when the number of requests per minute has exceeded the rate limit.

5xx

Internal Server Error

This response is returned when the system runs into an unexpected error.

Rate Limit

The rate limit is 50 request/minute, 200 requests/hour, and 1000 requests/day.

Sample cURL Request

cURL
curl --location --request POST 'https://api-0X.moengage.com/v3/custom-segments/' \
--header 'Content-Type: application/json' \
--header 'Authorization: Basic bmF2ZWVua3VtYXI6bW9lbmdhZ2U=' \
--header 'MOE-APPKEY: EXAMPLE_APP_KEY_ID' \
--data-raw '{"name": "segment_example_name",
  "included_filters": {
    "filter_operator": "and",
    "filters": [
      {
        "filter_type": "user_attributes",
        "name": "Name",
        "data_type": "string",
        "operator": "is",
        "value": "chandan",
        "negate": false,
        "case_sensitive": false
      }
    ]
  }
}'

Sample Response

201 400 401 409 413 429 500
Sample Response for a successful request
{
    "data": {
        "name": "custom-segment name",
        "id": "custom-segment id",
        "created_time": "2022-12-20T06:21:44.112000",
        "updated_time": "2022-12-20T06:21:44.160000",
        "type": "ELASTIC_SEARCH",
        "source": "API",
        "description": "Subscription Status 19Dec_7  is active  (case insensitive) AND Has executed Email Sent atleast 1 time in-between Jan 05, 2021 and Jan 08, 2021",
        "included_filters": {
            "filter_operator": "and",
            "filters": [
                {
                    "filter_type": "user_attributes",
                    "name": "Subscription Status 19Dec_7",
                    "data_type": "string",
                    "operator": "is",
                    "value": "active",
                    "value1": "",
                    "negate": false,
                    "case_sensitive": false
                },
                {
                    "filter_type": "actions",
                    "attributes": {
                        "filter_operator": "and",
                        "filters": []
                    },
                    "executed": true,
                    "primary_time_range": {
                        "type": "between",
                        "value": "2023-02-15T00:00:00.000Z",
                        "value1": "2023-02-24T23:59:59.999Z",
                        "value_type": "absolute",
                        "period_unit": "days"
                    },
                    "action_name": "MOE_EMAIL_SENT",
                    "execution": {
                        "count": 1,
                        "type": "atleast"
                    }
                }
            ]
        }
    },
    "response_id": "cNjnTEJw",
    "type": "custom_segment"
}

Postman Collections

We have made it easy for you to test the APIs. Click here to view it in Postman.

FAQs

  • How can I generate the payload for custom segment creation?
    You can simply generate the payload from the MoEngage dashboard. Log in to the MoEngage dashboard and navigate to the Test & Debug → Segment Payload section. Choose your filters and click on Generate Payload.
  • What are user attribute and action, action attribute filters?
    For information about these, refer to Create Segments.
  • How do I get the id of a custom segment I created earlier but didn't save?
    You can use the LIST Custom Segment API with the name query param filter to get the id of the custom segment for the name of the custom segment.
  • Why am I getting 409 HTTPConflict even when creating a custom segment with a different name?
    Both the name and the definition of a custom segment are unique. If the definition of the custom segment in the request matches an existing segment, we return a conflict 409 error even when the name specified in the request differs from the name of the existing custom segment.
  • How do I know which existing segment is conflicting in the case of 409 HTTPConflict?
    In the case of 409 HTTPConflict, we return a conflicting name/id in the response payload. You can check the payload to get the existing custom segment with the same definition.
  • How do I increase the rate limits?
    Please connect with your account manager.

Previous

Next

Was this article helpful?
0 out of 0 found this helpful

How can we improve this article?