Skip to main content
Version: 10

Populate a segment through the API or a business process

Level: advanced
note

This functionality is available for Creatio 10.2 and later.

Segments populated by rules work well when Creatio data alone defines the audience. However, the list of contacts often comes from outside Creatio, for example, from a loyalty platform, a nightly scoring job, or a cart abandonment pipeline. A business process can also select the contacts based on an event. Recreating such a list as entry and exit rules takes extra effort, and keeping the rules in sync with the source requires regular manual work.

Since version 10.2, Creatio lets an external system or a business process manage the members of a segment directly. A segment whose population mode is "Direct list" has no entry or exit rules. Creatio changes its members only when a REST API call or a Script task process element adds, removes, replaces, or clears them. Such calls are called membership calls. Learn more: Segmentation population API endpoints.

Limitations of "Direct list" segments​

The following table lists the limitations to take into account before you change the members of a segment whose population mode is "Direct list."

Limitation

Description

A reset segment accepts calls while it is active

A segment whose status is "Active" accepts calls even if its population status is "Draft," for example, after an administrator resets its members.

Calls inside an open database transaction are rejected

The ChangeMembers() method of the ISegmentMembershipService interface rejects a call made inside an open database transaction of the same connection with the "InvalidRequest" rejection.

A paused segment rejects calls

When you pause a "Direct list" segment, Creatio rejects every membership call with the "Paused" rejection. When you resume the segment, the Resume segment window lets you keep or clear the current members. Out of the box, Creatio keeps them. If you select "Clear members and start fresh," Creatio removes the current members, and processes that add contacts per event do not bring them back. In this case, add the contacts again after you resume the segment.

The Repopulate now action does not apply

Creatio does not run the Repopulate now action of the segment page for a "Direct list" segment. The ScheduleActualization operation of the SegmentService web service returns "false" in the success property and a message for such a segment. Use a business process or the membership endpoints to change the segment members.

Only contacts can be segment members

A segment whose population mode is "Direct list" includes "Contact" (Contact code) object records only.

Create and activate a "Direct list" segment​

Create and activate the segment before you change its members using the REST API or a business process.

To create and activate the segment:

  1. Open the Segments section.
  2. Click New. This opens the New record window.
  3. Fill out the Name field, for example, "Loyalty program members."
  4. Click Save.
  5. Open the segment page.
  6. Select "Direct list" in the Population mode field of the Lifecycle profile.
  7. Click Save.
  8. Click Activate segment. This opens the Activate segment window.
  9. Click Activate. You cannot change the population mode after the activation.

As a result, the segment gets the "Active" status in the Lifecycle profile and accepts membership calls. Creatio does not populate the segment on activation. The segment page shows the following elements:

  • How contacts get here profile that contains the "By process or API" value.
  • Contacts in segment profile that shows the exact number of segment members.
  • Contacts tab that lists the current segment members.

You can change the members of a "Direct list" segment in the following ways:

  • Using the REST API, when an external system manages the list of contacts.
  • Using a business process, when Creatio logic selects the contacts.

Change segment members using the REST API​

The following example shows how an external system adds, removes, replaces, and clears the members of a segment. The example requests use cURL. Replace {Creatio URL} with the URL of your Creatio instance, for example, https://mycompany.creatio.com. Learn more about the request and response parameters, the limits, and error handling: Segmentation population API endpoints.

1. Authorize the external system in Creatio​

The user on whose behalf the external system calls Creatio must have permission to edit the "Segments" (SysDataSegment code) object and access to read and edit the segment record.

Select how to authorize the external system in Creatio:

  • using OAuth 2.0 authorization

    OAuth 2.0 authorization works only on a Creatio instance that uses the Identity Service.

    To authorize the external system in Creatio using OAuth 2.0 authorization:

    1. Register an OAuth 2.0 integration that uses the client credentials grant. Instructions: Authorize external requests using client credentials grant.

    2. Copy the client ID and client secret of the integration.

    3. Request an access token from the Identity Service. The following example requests a token using the client ID and client secret of the integration. {Identity Service URL} is the value of the "Authorization server Url for OAuth 2.0 integrations" (OAuth20IdentityServerUrl code) system setting.

      Request
      curl -s -X POST "{Identity Service URL}/connect/token" \
      -H "Content-Type: application/x-www-form-urlencoded" \
      --data-urlencode "client_id={client ID}" \
      --data-urlencode "client_secret={client secret}" \
      --data-urlencode "grant_type=client_credentials"

      The Identity Service returns the access token.

      Response
      {
      "access_token": "eyJhbGciOi...",
      "expires_in": 3600,
      "token_type": "Bearer",
      "scope": "ApplicationAccess_..."
      }
    4. Send the token in the Authorization: Bearer {access token} header of each request. The token expires after the number of seconds specified in the expires_in property. Request a new token after that.

  • using cookie-based authentication
    1. Send the user name and password to the AuthService.svc web service. The following example logs in to Creatio and saves the cookies that Creatio returns to the "cookies.txt" file.

      Request
      curl -s -c cookies.txt -X POST "{Creatio URL}/ServiceModel/AuthService.svc/Login" \
      -H "Content-Type: application/json" \
      -d '{"UserName": "{user name}", "UserPassword": "{password}"}'

      Creatio returns the result of the login.

      Response
      {
      "RedirectUrl": null,
      "PasswordChangeUrl": null,
      "Exception": null,
      "UserType": "General",
      "Code": 0,
      "Message": ""
      }

      The "0" value of the Code property means that the login succeeded. Learn more: AuthService.svc web service.

    2. Send every cookie of the login in the Cookie header of each subsequent request, in the name=value; name=value format.

    3. Send the CRT_CSRF header in each POST request. Set the header to the value of the CRT_CSRF cookie. Creatio rejects a POST request without the header with the 403 Forbidden HTTP status code.

As a result, the external system gets access to the Creatio API.

The example requests below use OAuth 2.0 authorization. To use cookie-based authentication instead, replace the -H "Authorization: Bearer {access token}" header with the -H "Cookie: {login cookies}" and -H "CRT_CSRF: {csrf token}" headers. Replace {login cookies} with every cookie that the authentication request returned, in the name=value; name=value format, and {csrf token} with the value of the CRT_CSRF cookie.

2. Get the segment and contact IDs​

The membership endpoints take the segment ID and, except for ClearMembers, the contact IDs. Skip this step if the external system already stores the IDs. Instead of contact IDs, you can also pass a filter that selects the contacts. Learn more: Segmentation population API endpoints.

Get the segment ID​

Get the segment ID in one of the following ways:

  • Copy the ID from the address bar of the segment page. The ID is the last part of the address, for example, {Creatio URL}/0/Shell/#Card/SysDataSegment_FormPage/edit/11111111-1111-1111-1111-111111111111.

  • Read the ID using OData by the segment name. The following example reads the ID of the "Loyalty program members" segment.

    Request
    curl -s "{OData URL}/SysDataSegment?\$filter=Name%20eq%20'Loyalty%20program%20members'&\$select=Id,Name" \
    -H "Authorization: Bearer {access token}"

    Replace {OData URL} with {Creatio URL}/0/odata on .NET Framework and with {Creatio URL}/odata on .NET. Learn more: OData basics.

As a result, if you read the ID using OData, Creatio returns the following response.

Response
{
"@odata.context": "{OData URL}/$metadata#SysDataSegment(Id,Name)",
"value": [
{
"Id": "11111111-1111-1111-1111-111111111111",
"Name": "Loyalty program members"
}
]
}

The segment ID is passed in the segmentId parameter.

Get the contact IDs​

To get the contact IDs, read the IDs of "Contact" (Contact code) object records using OData, for example, by email. The following example reads the ID of the contact whose email is andrew.baker@example.com.

Request
curl -s "{OData URL}/Contact?\$filter=Email%20eq%20'andrew.baker@example.com'&\$select=Id,Name" \
-H "Authorization: Bearer {access token}"

Replace {OData URL} with {Creatio URL}/0/odata on .NET Framework and with {Creatio URL}/odata on .NET. To find many contacts, read them in a single request with a filter that covers all of them instead of a request per contact, and store the IDs on the side of the external system for subsequent calls.

As a result, Creatio returns the following response.

Response
{
"@odata.context": "{OData URL}/$metadata#Contact(Id,Name)",
"value": [
{ "Id": "22222222-2222-2222-2222-222222222222", "Name": "Andrew Baker" }
]
}

The contact IDs are passed in the recordIds parameter.

3. Change the segment members​

All membership endpoints take the same headers. The AddMembers, RemoveMembers, and ReplaceMembers endpoints take the segment ID and the contact IDs in the request body. The ClearMembers endpoint takes the segment ID only. Perform the operations that your scenario requires.

The example requests below use the "11111111-1111-1111-1111-111111111111" segment ID and the following contacts:

  • "22222222-2222-2222-2222-222222222222" — Andrew Baker.
  • "33333333-3333-3333-3333-333333333333" — Mary King.
  • "55555555-5555-5555-5555-555555555555" — John Best.
  • "44444444-4444-4444-4444-444444444444" — a contact that never becomes a member.

Add contacts to the segment​

  1. Call the AddMembers endpoint.
  2. Pass the segment ID and the contact IDs in the request body.

The following example adds Andrew Baker and Mary King to the segment.

Request (OAuth 2.0 authorization)
curl -s -X POST "{Creatio URL}/0/rest/SegmentService/AddMembers" \
-H "Authorization: Bearer {access token}" \
-H "Content-Type: application/json" \
-d '{
"segmentId": "11111111-1111-1111-1111-111111111111",
"recordIds": [
"22222222-2222-2222-2222-222222222222",
"33333333-3333-3333-3333-333333333333"
]
}'

The following example adds Andrew Baker and Mary King to the segment using cookie-based authentication.

Request (cookie-based authentication)
curl -s -X POST "{Creatio URL}/0/rest/SegmentService/AddMembers" \
-H "CRT_CSRF: {csrf token}" \
-H "Cookie: {login cookies}" \
-H "Content-Type: application/json" \
-d '{
"segmentId": "11111111-1111-1111-1111-111111111111",
"recordIds": [
"22222222-2222-2222-2222-222222222222",
"33333333-3333-3333-3333-333333333333"
]
}'

As a result, Creatio returns the following response.

Response
{
"success": true,
"segmentId": "11111111-1111-1111-1111-111111111111",
"outcome": "Applied",
"rejection": "None",
"requestedCount": 2,
"insertedCount": 2,
"restoredCount": 0,
"alreadyInSegmentCount": 0,
"notFoundCount": 0,
"removedCount": 0,
"notInSegmentCount": 0,
"totalActiveMembers": 2,
"startedOn": "2026-11-11T15:37:32.810Z",
"completedOn": "2026-11-11T15:37:34.024Z"
}

Andrew Baker and Mary King become segment members. The insertedCount property shows the number of added contacts. The totalActiveMembers property and the Contacts in segment profile on the segment page show the same number of members.

Remove members from the segment​

  1. Call the RemoveMembers endpoint.
  2. Pass the segment ID and the IDs of the members to remove in the request body.

The following example removes Mary King and the "44444444-4444-4444-4444-444444444444" contact, which is not a member.

Request
curl -s -X POST "{Creatio URL}/0/rest/SegmentService/RemoveMembers" \
-H "Authorization: Bearer {access token}" \
-H "Content-Type: application/json" \
-d '{
"segmentId": "11111111-1111-1111-1111-111111111111",
"recordIds": [
"33333333-3333-3333-3333-333333333333",
"44444444-4444-4444-4444-444444444444"
]
}'

As a result, Creatio returns the following response.

Response
{
"success": true,
"segmentId": "11111111-1111-1111-1111-111111111111",
"outcome": "Applied",
"rejection": "None",
"requestedCount": 2,
"insertedCount": 0,
"restoredCount": 0,
"alreadyInSegmentCount": 0,
"notFoundCount": 0,
"removedCount": 1,
"notInSegmentCount": 1,
"totalActiveMembers": 1,
"startedOn": "2026-11-11T15:37:35.801Z",
"completedOn": "2026-11-11T15:37:36.984Z"
}

Mary King leaves the segment. The removedCount property shows the number of removed members. Creatio skips the "44444444-4444-4444-4444-444444444444" contact and counts it in the notInSegmentCount property.

Replace the segment members​

  1. Call the ReplaceMembers endpoint.
  2. Pass the segment ID and the IDs of the contacts that the segment must contain after the call in the request body.

The following example makes the segment contain Mary King and John Best.

Request
curl -s -X POST "{Creatio URL}/0/rest/SegmentService/ReplaceMembers" \
-H "Authorization: Bearer {access token}" \
-H "Content-Type: application/json" \
-d '{
"segmentId": "11111111-1111-1111-1111-111111111111",
"recordIds": [
"33333333-3333-3333-3333-333333333333",
"55555555-5555-5555-5555-555555555555"
]
}'

As a result, Creatio returns the following response.

Response
{
"success": true,
"segmentId": "11111111-1111-1111-1111-111111111111",
"outcome": "Applied",
"rejection": "None",
"requestedCount": 2,
"insertedCount": 1,
"restoredCount": 1,
"alreadyInSegmentCount": 0,
"notFoundCount": 0,
"removedCount": 1,
"notInSegmentCount": 0,
"totalActiveMembers": 2,
"startedOn": "2026-11-11T15:37:37.249Z",
"completedOn": "2026-11-11T15:37:38.504Z"
}

The segment contains only Mary King and John Best. Mary King returns to the segment (the restoredCount property), John Best joins it (the insertedCount property), and Andrew Baker leaves it because he is not in the list (the removedCount property).

Clear the segment​

  1. Call the ClearMembers endpoint.
  2. Pass the segment ID in the request body. Do not send the recordIds parameter.

The following example removes every member from the segment.

Request
curl -s -X POST "{Creatio URL}/0/rest/SegmentService/ClearMembers" \
-H "Authorization: Bearer {access token}" \
-H "Content-Type: application/json" \
-d '{
"segmentId": "11111111-1111-1111-1111-111111111111"
}'

As a result, Creatio returns the following response.

Response
{
"success": true,
"segmentId": "11111111-1111-1111-1111-111111111111",
"outcome": "Applied",
"rejection": "None",
"requestedCount": 0,
"insertedCount": 0,
"restoredCount": 0,
"alreadyInSegmentCount": 0,
"notFoundCount": 0,
"removedCount": 2,
"notInSegmentCount": 0,
"totalActiveMembers": 0,
"startedOn": "2026-11-11T15:37:38.773Z",
"completedOn": "2026-11-11T15:37:39.909Z"
}

The segment has no members. The removedCount property shows the number of removed members.

Change segment members using a business process​

The following example adds contacts to a segment using a Script task process element. You can start the process from another process, for example, when a contact fills out a form, or from a signal. The process takes the segment from a process parameter. The process can add a single contact per run or several contacts in a single call:

  • A single contact suits a scenario that runs per event. The process takes the contact from a process parameter. Do not run such a process in a loop to fill a segment with many contacts, since each call has its own overhead and calls on a segment run one after another.
  • Several contacts suit a scenario that fills a segment in bulk. The process reads the contacts using the Read data element and adds them in a single call.

Use an active segment whose population mode is "Direct list." Instructions: Create and activate a "Direct list" segment.

To set up the business process:

  1. Create a business process.

    1. Open the Process library section.

    2. Click New process. This opens the Process Designer.

    3. Open the Settings tab in the process setup area.

    4. Fill out the process properties.

      Property

      Value

      Title

      Add contacts to segment

      Code

      UsrAddContactsToSegment

    5. Select or clear the Use system security context for script tasks checkbox.

      • If the checkbox is selected, the Script task element runs with system access permissions: the user who runs the process does not need permission to edit the segment, and Creatio treats every contact of the list as readable.
      • If the checkbox is cleared, Creatio applies the access permissions of the user who runs the process, as for the REST API.

      Out of the box, the checkbox is selected. Learn more: Process Designer (user documentation).

    6. Click Save.

  2. Add the process parameters.

    1. Click an arbitrary place in the working area.

    2. Open the Parameters tab in the process setup area.

    3. Click Add parameter → select the data type of the parameter.

    4. Fill out the parameter properties. The Value property sets the segment and the contact to use when you run the process from the Process Designer. When another process calls this process, map the input parameters from the caller instead. Instructions: Process parameters (user documentation).

      Element

      Type

      Property

      Value

      Parameter that contains the segment to change

      Lookup

      Title

      Segment

      Code

      SegmentId

      Data type

      Lookup

      Lookup

      Segments

      Direction

      Input

      Value

      Loyalty program members

      Parameter that contains the contact to add

      Lookup

      Title

      Contact

      Code

      ContactId

      Data type

      Lookup

      Lookup

      Contact

      Direction

      Input

      Value

      Andrew Baker

      Parameter that indicates whether the call succeeded

      Boolean

      Title

      Success

      Code

      Success

      Data type

      Boolean

      Direction

      Output

      Parameter that contains the reason for a rejected call, or "None"

      Text

      Title

      Rejection

      Code

      Rejection

      Data type

      Text

      Direction

      Output

      Parameter that contains the description of a rejection or failure

      Text

      Title

      Message

      Code

      Message

      Data type

      Text

      Direction

      Output

    Add the Contact parameter only if you add a single contact.

  3. Set up the "Read data" element. Skip this step if you add a single contact.

    1. Click btn_System_actions.png → place the Read data element between the Simple start event and the Terminate end event in the working area. Instructions: "Read data" process element (user documentation).

    2. Set the Which data read mode to use? property to "Read collection of records."

    3. Set the Which object to read data from? property to "Contact."

    4. Set up the filter that selects the contacts.

      1. Click Add condition in the How to filter records? block. This opens the Select column window.
      2. Select the column to filter by, for example, "Type."
      3. Click Select.
      4. Select the comparison type and the value of the condition, for example, "Customer."
    5. Set the number of records to read in the Read first … records property. Out of the box, the element reads the first 50 records.

  4. Set up the "Script task" element.

    1. Click btn_System_actions.png → place the Script task element before the Terminate end event in the working area. If you added the Read data element, place the Script task element after it. Instructions: "Script task" process element (user documentation).

    2. Fill out the element properties.

      Property

      Value

      Title

      Add contacts to segment

    3. Go to the element setup area.

    4. Add the source code. The code adds the contacts to the segment and writes the result of the call to the output parameters. Select the code that matches how many contacts the process adds:

      • add a single contact
        "Add contacts to segment" script task
        /* Describe the call: add the contact to the segment. */
        var request = new ChangeSegmentMembersRequest {
        SegmentId = Get<Guid>("SegmentId"),
        Operation = SegmentMembershipOperation.Add,
        RecordIds = new[] { Get<Guid>("ContactId") }
        };
        /* Apply the call synchronously. The method does not throw
        an exception for a rejection or a failure. */
        ChangeSegmentMembersResult result =
        ClassFactory.Get<ISegmentMembershipService>()
        .ChangeMembers(request);
        /* Write the result of the call to the output parameters
        of the process. */
        Set<bool>("Success",
        result.Outcome == ChangeSegmentMembersOutcome.Applied
        || result.Outcome == ChangeSegmentMembersOutcome.NoChanges);
        Set<string>("Rejection", result.Rejection.ToString());
        Set<string>("Message", result.Message ?? string.Empty);
        return true;

        The code works as follows:

        • The ChangeSegmentMembersRequest class describes the call. The SegmentId property is the segment ID. The Operation property is a value of the SegmentMembershipOperation enumeration: Add, Remove, ReplaceAll, or Clear. The RecordIds property is the list of contact IDs. Instead of RecordIds, you can set the FilterData property, a filter in the same JSON format as the filterData parameter of the endpoints. Set exactly one of these properties, and neither for Clear.
        • The ChangeMembers() method of the ISegmentMembershipService interface applies the call synchronously and returns the result. The rules, rejections, and limits are the same as for the REST API. Learn more: Segmentation population API endpoints.
        • The ChangeSegmentMembersResult class contains the same values as the response of the endpoints: the Outcome, Rejection, and Message properties, and the counters, for example, the InsertedCount and TotalActiveMembers properties. The ChangeMembers() method does not throw an exception for a rejection or a failure, so check the Outcome property.
      • add several contacts in a single call

        The example uses the "ReadDataUserTask1" element code, which Creatio assigns to the first Read data element of a process. Check the code of your element in the element setup area.

        "Add contacts to segment" script task
        /* Retrieve the contacts that the "Read data" element returned. */
        var contacts = Get<ICompositeObjectList<ICompositeObject>>(
        "ReadDataUserTask1.ResultCompositeObjectList");
        /* Collect the contact IDs. */
        var contactIds = new List<Guid>();
        foreach (ICompositeObject contact in contacts) {
        if (contact.TryGetValue<Guid>("Id", out Guid contactId)) {
        contactIds.Add(contactId);
        }
        }
        /* Skip the call if there are no contacts.
        A call with an empty list is rejected. */
        if (contactIds.Count == 0) {
        Set<bool>("Success", true);
        Set<string>("Rejection", "None");
        Set<string>("Message", "No contacts to add.");
        return true;
        }
        /* Describe the call: add the contacts to the segment. */
        var request = new ChangeSegmentMembersRequest {
        SegmentId = Get<Guid>("SegmentId"),
        Operation = SegmentMembershipOperation.Add,
        RecordIds = contactIds
        };
        /* Apply the call synchronously. The method does not throw
        an exception for a rejection or a failure. */
        ChangeSegmentMembersResult result =
        ClassFactory.Get<ISegmentMembershipService>()
        .ChangeMembers(request);
        /* Write the result of the call to the output parameters
        of the process. */
        Set<bool>("Success",
        result.Outcome == ChangeSegmentMembersOutcome.Applied
        || result.Outcome == ChangeSegmentMembersOutcome.NoChanges);
        Set<string>("Rejection", result.Rejection.ToString());
        Set<string>("Message", result.Message ?? string.Empty);
        return true;

        The code skips the call when the Read data element returns no contacts, since Creatio rejects a call with an empty list with the "InvalidRequest" rejection. The code writes the result of the call to the Success, Rejection, and Message output parameters. Keep a call within 100000 contacts.

  5. Set up the business process methods.

    1. Click an arbitrary place in the working area.

    2. Open the Methods tab.

    3. Add the business process methods.

      1. Click btn_add_element.png next to Usings.

      2. Fill out the method properties.

        Property

        Value

        Namespace

        Creatio.Segmentation

      3. Click Save.

      4. Repeat steps 1–3 for the Terrasoft.Core.Factories namespace.

      Without the namespaces, the Script task element does not compile.

    4. Click Save.

  6. Click Publish. Creatio compiles the Script task element when you publish the process.

  7. Click Run.

As a result, the process adds the contacts to the segment:

  • If you add a single contact, the contact becomes a member of the segment. The Contacts in segment profile on the segment page increases by one, and the contact appears on the Contacts tab.
  • If you add several contacts, a single call adds every contact that the Read data element returns to the segment. For a large set, consider setting the FilterData property with the same filter instead of reading the records. In this case, Creatio selects the contacts in the database, and the process does not hold them in memory.

The Success process parameter is "true," and Rejection is "None." If you run the process again with the same data, nothing changes, and Success is still "true," since the call returns the "NoChanges" outcome. If the segment is not activated yet, the process also completes, but Success is "false," Rejection is "Draft," and Message prompts to activate the segment. Use these parameters in the process flow, for example, in a conditional flow, to handle a rejection.


See also​

Segmentation population API endpoints

Manage segments using Segmentation Engine API

Segmentation Engine API endpoints

Authorize external requests using client credentials grant

AuthService.svc web service

OData basics

"Script task" process element (user documentation)

"Read data" process element (user documentation)

Process parameters (user documentation)

Process Designer (user documentation)