---
title: Create targeting rules for a flag env
description: Creates a new targeting rule (allocation) for a specific feature flag in a specific environment.
breadcrumbs: Docs > API > Create targeting rules for a flag env
---

> For the complete documentation index, see [llms.txt](https://docs.datadoghq.com/llms.txt).

# Create targeting rules for a flag env

## v2 (latest)

| Datadog site      | API endpoint                                                                                                        |
| ----------------- | ------------------------------------------------------------------------------------------------------------------- |
| app.datadoghq.com | POST https://api.datadoghq.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations     |
| us3.datadoghq.com | POST https://api.us3.datadoghq.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations |
| us5.datadoghq.com | POST https://api.us5.datadoghq.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations |
| app.datadoghq.eu  | POST https://api.datadoghq.eu/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations      |
| ap1.datadoghq.com | POST https://api.ap1.datadoghq.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations |
| ap2.datadoghq.com | POST https://api.ap2.datadoghq.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations |
| uk1.datadoghq.com | POST https://api.uk1.datadoghq.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations |
| app.ddog-gov.com  | POST https://api.ddog-gov.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations      |
| us2.ddog-gov.com  | POST https://api.us2.ddog-gov.com/api/v2/feature-flags/{feature_flag_id}/environments/{environment_id}/allocations  |

### Overview

Creates a new targeting rule (allocation) for a specific feature flag in a specific environment.

This endpoint requires the `feature_flag_config_write` permission.

OAuth apps require the `feature_flag_config_write` authorization [scope](https://docs.datadoghq.com/api/latest/scopes.md#feature-flags) to access this endpoint.

### Arguments

#### Path Parameters

| Field                        | Type   | Description                 |
| ---------------------------- | ------ | --------------------------- |
| feature_flag_id [*required*] | string | The ID of the feature flag. |
| environment_id [*required*]  | string | The ID of the environment.  |

### Request

#### Body Data (required)

{% tabs %}
{% tab label="Model" %}
| Parent field      | Field                           | Type      | Description                                                                                                                                                                                                                             |
| ----------------- | ------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|                   | data [*required*]               | object    | Data wrapper for allocation request payloads.                                                                                                                                                                                           |
| data              | attributes [*required*]         | object    | Request to create or update a targeting rule (allocation) for a feature flag environment.                                                                                                                                               |
| attributes        | experiment_id                   | string    | The experiment ID for experiment-linked allocations.                                                                                                                                                                                    |
| attributes        | exposure_schedule               | object    | Progressive release request payload.                                                                                                                                                                                                    |
| exposure_schedule | absolute_start_time             | date-time | The absolute UTC start time for this schedule.                                                                                                                                                                                          |
| exposure_schedule | control_variant_id              | string    | The control variant ID used for experiment comparisons.                                                                                                                                                                                 |
| exposure_schedule | control_variant_key             | string    | The control variant key used during creation workflows.                                                                                                                                                                                 |
| exposure_schedule | id                              | uuid      | The unique identifier of the progressive rollout.                                                                                                                                                                                       |
| exposure_schedule | rollout_options [*required*]    | object    | Rollout options request payload.                                                                                                                                                                                                        |
| rollout_options   | autostart                       | boolean   | Whether the schedule should begin automatically.                                                                                                                                                                                        |
| rollout_options   | selection_interval_ms           | int64     | Interval in milliseconds for uniform interval strategies.                                                                                                                                                                               |
| rollout_options   | strategy [*required*]           | enum      | The progression strategy used by a progressive rollout. Allowed enum values: `UNIFORM_INTERVALS`, `NO_ROLLOUT`.                                                                                                                         |
| exposure_schedule | rollout_steps [*required*]      | [object]  | Ordered progression steps for exposure.                                                                                                                                                                                                 |
| rollout_steps     | exposure_ratio [*required*]     | double    | The exposure ratio for this step.                                                                                                                                                                                                       |
| rollout_steps     | grouped_step_index [*required*] | int64     | Logical index grouping related steps.                                                                                                                                                                                                   |
| rollout_steps     | id                              | uuid      | The unique identifier of the progression step.                                                                                                                                                                                          |
| rollout_steps     | interval_ms                     | int64     | Step duration in milliseconds.                                                                                                                                                                                                          |
| rollout_steps     | is_pause_record [*required*]    | boolean   | Whether this step represents a pause record.                                                                                                                                                                                            |
| attributes        | guardrail_metrics               | [object]  | Guardrail metrics used to monitor and auto-pause or abort.                                                                                                                                                                              |
| guardrail_metrics | metric_id [*required*]          | string    | The metric ID to monitor.                                                                                                                                                                                                               |
| guardrail_metrics | trigger_action [*required*]     | enum      | Action to perform when a guardrail threshold is triggered. Allowed enum values: `PAUSE`, `ABORT`.                                                                                                                                       |
| attributes        | id                              | uuid      | The unique identifier of the targeting rule allocation. Use this ID with the allocation management endpoints, such as `/api/v2/allocations/{allocation_id}`. It is not included in SDK evaluation results or exposure events.           |
| attributes        | key [*required*]                | string    | The unique key of the targeting rule allocation. SDKs report this key in flag evaluation results and exposure events to indicate which targeting rule assigned the variant. Use it to match evaluation or experiment data to this rule. |
| attributes        | name [*required*]               | string    | The display name of the targeting rule.                                                                                                                                                                                                 |
| attributes        | targeting_rules                 | [object]  | Targeting rules that determine audience eligibility.                                                                                                                                                                                    |
| targeting_rules   | conditions [*required*]         | [object]  | Conditions that must match for this rule.                                                                                                                                                                                               |
| conditions        | attribute                       | string    | The user or request attribute to evaluate. Required for inline conditions; omit when `saved_filter_id` is set.                                                                                                                          |
| conditions        | operator                        | enum      | The operator used in a targeting condition. Allowed enum values: `LT`, `LTE`, `GT`, `GTE`, `MATCHES`, `NOT_MATCHES`, `ONE_OF`, `NOT_ONE_OF`, `IS_NULL`, `EQUALS`.                                                                       |
| conditions        | saved_filter_id                 | uuid      | The ID of a saved filter to reference as this condition. Mutually exclusive with `operator`, `attribute`, and `value`. When set, the saved filter's targeting rules are evaluated in place of an inline predicate.                      |
| conditions        | value                           | [string]  | Values used by the selected operator. Required for inline conditions; omit when `saved_filter_id` is set.                                                                                                                               |
| attributes        | type [*required*]               | enum      | The type of targeting rule (called allocation in the API model). Allowed enum values: `FEATURE_GATE`, `CANARY`.                                                                                                                         |
| attributes        | variant_weights                 | [object]  | Variant distribution weights.                                                                                                                                                                                                           |
| variant_weights   | value [*required*]              | double    | The percentage weight for this variant.                                                                                                                                                                                                 |
| variant_weights   | variant_id                      | uuid      | The variant ID to assign weight to.                                                                                                                                                                                                     |
| variant_weights   | variant_key                     | string    | The variant key to assign weight to.                                                                                                                                                                                                    |
| data              | type [*required*]               | enum      | The resource type. Allowed enum values: `allocations`.                                                                                                                                                                                  |
{% /tab %}

{% tab label="Example" %}
```json
{
  "data": {
    "type": "allocations",
    "attributes": {
      "name": "New targeting rule Example-Feature-Flag",
      "key": "new-targeting-rule-example-feature-flag",
      "targeting_rules": [],
      "variant_weights": [
        {
          "variant_id": "550e8400-e29b-41d4-a716-446655440002",
          "value": 100
        }
      ],
      "guardrail_metrics": [],
      "type": "CANARY"
    }
  }
}
```
{% /tab %}
{% /tabs %}

### Response

{% tabs %}
{% tab label="201" %}
Created

{% tabs %}
{% tab label="Model" %}
Response containing a single targeting rule (allocation).

| Parent field       | Field                                        | Type      | Description                                                                                                                                                                                                                             |
| ------------------ | -------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|                    | data [*required*]                            | object    | Data wrapper for targeting rule allocation responses.                                                                                                                                                                                   |
| data               | attributes [*required*]                      | object    | Targeting rule (allocation) details for a feature flag environment.                                                                                                                                                                     |
| attributes         | created_at [*required*]                      | date-time | The timestamp when the targeting rule allocation was created.                                                                                                                                                                           |
| attributes         | environment_ids [*required*]                 | [string]  | Environment IDs associated with this targeting rule allocation.                                                                                                                                                                         |
| attributes         | experiment_id                                | string    | The experiment ID linked to this targeting rule allocation.                                                                                                                                                                             |
| attributes         | exposure_schedule                            | object    | Progressive release details for a targeting rule allocation.                                                                                                                                                                            |
| exposure_schedule  | absolute_start_time                          | date-time | The absolute UTC start time for this schedule.                                                                                                                                                                                          |
| exposure_schedule  | allocation_id [*required*]                   | uuid      | The unique identifier (UUID) of the targeting rule allocation this progressive rollout belongs to. This is not the allocation key that SDKs report in evaluation results and exposure events.                                           |
| exposure_schedule  | control_variant_id                           | string    | The control variant ID used for experiment comparisons.                                                                                                                                                                                 |
| exposure_schedule  | created_at [*required*]                      | date-time | The timestamp when the schedule was created.                                                                                                                                                                                            |
| exposure_schedule  | guardrail_triggered_action                   | string    | Last guardrail action triggered for this schedule.                                                                                                                                                                                      |
| exposure_schedule  | guardrail_triggers [*required*]              | [object]  | Guardrail trigger records for this schedule.                                                                                                                                                                                            |
| guardrail_triggers | allocation_exposure_schedule_id [*required*] | uuid      | The progressive rollout ID this trigger belongs to.                                                                                                                                                                                     |
| guardrail_triggers | created_at [*required*]                      | date-time | The timestamp when this trigger was created.                                                                                                                                                                                            |
| guardrail_triggers | flagging_variant_id [*required*]             | uuid      | The variant ID that triggered this event.                                                                                                                                                                                               |
| guardrail_triggers | id [*required*]                              | uuid      | The unique identifier of the guardrail trigger.                                                                                                                                                                                         |
| guardrail_triggers | metric_id [*required*]                       | string    | The metric ID associated with the trigger.                                                                                                                                                                                              |
| guardrail_triggers | triggered_action [*required*]                | string    | The action that was triggered.                                                                                                                                                                                                          |
| guardrail_triggers | updated_at [*required*]                      | date-time | The timestamp when this trigger was last updated.                                                                                                                                                                                       |
| exposure_schedule  | id                                           | uuid      | The unique identifier of the progressive rollout.                                                                                                                                                                                       |
| exposure_schedule  | rollout_options [*required*]                 | object    | Applied progression options for a progressive rollout.                                                                                                                                                                                  |
| rollout_options    | autostart [*required*]                       | boolean   | Whether the schedule starts automatically.                                                                                                                                                                                              |
| rollout_options    | selection_interval_ms [*required*]           | int64     | Interval in milliseconds for uniform interval strategies.                                                                                                                                                                               |
| rollout_options    | strategy [*required*]                        | enum      | The progression strategy used by a progressive rollout. Allowed enum values: `UNIFORM_INTERVALS`, `NO_ROLLOUT`.                                                                                                                         |
| exposure_schedule  | rollout_steps [*required*]                   | [object]  | Ordered progression steps for exposure.                                                                                                                                                                                                 |
| rollout_steps      | allocation_exposure_schedule_id [*required*] | uuid      | The progressive rollout ID this step belongs to.                                                                                                                                                                                        |
| rollout_steps      | created_at [*required*]                      | date-time | The timestamp when the progression step was created.                                                                                                                                                                                    |
| rollout_steps      | exposure_ratio [*required*]                  | double    | The exposure ratio for this step.                                                                                                                                                                                                       |
| rollout_steps      | grouped_step_index [*required*]              | int64     | Logical index grouping related steps.                                                                                                                                                                                                   |
| rollout_steps      | id [*required*]                              | uuid      | The unique identifier of the progression step.                                                                                                                                                                                          |
| rollout_steps      | interval_ms                                  | int64     | Step duration in milliseconds.                                                                                                                                                                                                          |
| rollout_steps      | is_pause_record [*required*]                 | boolean   | Whether this step represents a pause record.                                                                                                                                                                                            |
| rollout_steps      | order_position [*required*]                  | int64     | Sort order for the progression step.                                                                                                                                                                                                    |
| rollout_steps      | updated_at [*required*]                      | date-time | The timestamp when the progression step was last updated.                                                                                                                                                                               |
| exposure_schedule  | updated_at [*required*]                      | date-time | The timestamp when the schedule was last updated.                                                                                                                                                                                       |
| attributes         | guardrail_metrics [*required*]               | [object]  | Guardrail metrics associated with this targeting rule allocation.                                                                                                                                                                       |
| guardrail_metrics  | metric_id [*required*]                       | string    | The metric ID to monitor.                                                                                                                                                                                                               |
| guardrail_metrics  | trigger_action [*required*]                  | enum      | Action to perform when a guardrail threshold is triggered. Allowed enum values: `PAUSE`, `ABORT`.                                                                                                                                       |
| guardrail_metrics  | triggered_by                                 | string    | The signal or system that triggered the action.                                                                                                                                                                                         |
| attributes         | id                                           | uuid      | The unique identifier of the targeting rule allocation. Use this ID with the allocation management endpoints, such as `/api/v2/allocations/{allocation_id}`. It is not included in SDK evaluation results or exposure events.           |
| attributes         | key [*required*]                             | string    | The unique key of the targeting rule allocation. SDKs report this key in flag evaluation results and exposure events to indicate which targeting rule assigned the variant. Use it to match evaluation or experiment data to this rule. |
| attributes         | name [*required*]                            | string    | The display name of the targeting rule.                                                                                                                                                                                                 |
| attributes         | order_position [*required*]                  | int64     | Sort order position within the environment.                                                                                                                                                                                             |
| attributes         | targeting_rules [*required*]                 | [object]  | Conditions associated with this targeting rule allocation.                                                                                                                                                                              |
| targeting_rules    | conditions [*required*]                      | [object]  | Conditions evaluated by this targeting rule.                                                                                                                                                                                            |
| conditions         | attribute                                    | string    | The user or request attribute to evaluate. Omitted for saved-filter references.                                                                                                                                                         |
| conditions         | created_at [*required*]                      | date-time | The timestamp when the condition was created.                                                                                                                                                                                           |
| conditions         | id [*required*]                              | uuid      | The unique identifier of the condition.                                                                                                                                                                                                 |
| conditions         | operator                                     | enum      | The operator used in a targeting condition. Allowed enum values: `LT`, `LTE`, `GT`, `GTE`, `MATCHES`, `NOT_MATCHES`, `ONE_OF`, `NOT_ONE_OF`, `IS_NULL`, `EQUALS`.                                                                       |
| conditions         | saved_filter_id                              | uuid      | The ID of the saved filter referenced by this condition, or null for inline conditions.                                                                                                                                                 |
| conditions         | updated_at [*required*]                      | date-time | The timestamp when the condition was last updated.                                                                                                                                                                                      |
| conditions         | value                                        | [string]  | Values used by the selected operator. Omitted for saved-filter references.                                                                                                                                                              |
| targeting_rules    | created_at [*required*]                      | date-time | The timestamp when the targeting rule was created.                                                                                                                                                                                      |
| targeting_rules    | id [*required*]                              | uuid      | The unique identifier of the targeting rule.                                                                                                                                                                                            |
| targeting_rules    | updated_at [*required*]                      | date-time | The timestamp when the targeting rule was last updated.                                                                                                                                                                                 |
| attributes         | type [*required*]                            | enum      | The type of targeting rule (called allocation in the API model). Allowed enum values: `FEATURE_GATE`, `CANARY`.                                                                                                                         |
| attributes         | updated_at [*required*]                      | date-time | The timestamp when the targeting rule allocation was last updated.                                                                                                                                                                      |
| attributes         | variant_weights [*required*]                 | [object]  | Weighted variant assignments for this targeting rule allocation.                                                                                                                                                                        |
| variant_weights    | created_at                                   | date-time | The timestamp when the variant weight was created.                                                                                                                                                                                      |
| variant_weights    | id                                           | uuid      | Unique identifier of the variant weight assignment.                                                                                                                                                                                     |
| variant_weights    | updated_at                                   | date-time | The timestamp when the variant weight was last updated.                                                                                                                                                                                 |
| variant_weights    | value [*required*]                           | double    | The percentage weight for the variant.                                                                                                                                                                                                  |
| variant_weights    | variant                                      | object    | A variant of a feature flag.                                                                                                                                                                                                            |
| variant            | created_at                                   | date-time | The timestamp when the variant was created.                                                                                                                                                                                             |
| variant            | id [*required*]                              | uuid      | The unique identifier of the variant.                                                                                                                                                                                                   |
| variant            | key [*required*]                             | string    | The unique key of the variant.                                                                                                                                                                                                          |
| variant            | name [*required*]                            | string    | The name of the variant.                                                                                                                                                                                                                |
| variant            | updated_at                                   | date-time | The timestamp when the variant was last updated.                                                                                                                                                                                        |
| variant            | value [*required*]                           | string    | The value of the variant as a string.                                                                                                                                                                                                   |
| variant_weights    | variant_id [*required*]                      | uuid      | The variant ID.                                                                                                                                                                                                                         |
| data               | id [*required*]                              | uuid      | The unique identifier of the targeting rule allocation. Use this ID with the allocation management endpoints, such as `/api/v2/allocations/{allocation_id}`. It is not included in SDK evaluation results or exposure events.           |
| data               | type [*required*]                            | enum      | The resource type. Allowed enum values: `allocations`.                                                                                                                                                                                  |
{% /tab %}

{% tab label="Example" %}
```json
{
  "data": {
    "attributes": {
      "created_at": "2024-01-01T12:00:00Z",
      "environment_ids": [
        "550e8400-e29b-41d4-a716-446655440001"
      ],
      "experiment_id": "550e8400-e29b-41d4-a716-446655440030",
      "exposure_schedule": {
        "absolute_start_time": "2025-06-13T12:00:00Z",
        "allocation_id": "550e8400-e29b-41d4-a716-446655440020",
        "control_variant_id": "550e8400-e29b-41d4-a716-446655440012",
        "created_at": "2024-01-01T12:00:00Z",
        "guardrail_triggered_action": "PAUSE",
        "guardrail_triggers": [
          {
            "allocation_exposure_schedule_id": "550e8400-e29b-41d4-a716-446655440010",
            "created_at": "2024-01-01T12:00:00Z",
            "flagging_variant_id": "550e8400-e29b-41d4-a716-446655440001",
            "id": "550e8400-e29b-41d4-a716-446655440080",
            "metric_id": "metric-error-rate",
            "triggered_action": "PAUSE",
            "updated_at": "2024-01-01T12:00:00Z"
          }
        ],
        "id": "550e8400-e29b-41d4-a716-446655440010",
        "rollout_options": {
          "autostart": false,
          "selection_interval_ms": 3600000,
          "strategy": "UNIFORM_INTERVALS"
        },
        "rollout_steps": [
          {
            "allocation_exposure_schedule_id": "550e8400-e29b-41d4-a716-446655440010",
            "created_at": "2024-01-01T12:00:00Z",
            "exposure_ratio": 0.1,
            "grouped_step_index": 0,
            "id": "550e8400-e29b-41d4-a716-446655440040",
            "interval_ms": 3600000,
            "is_pause_record": false,
            "order_position": 0,
            "updated_at": "2024-01-01T12:00:00Z"
          }
        ],
        "updated_at": "2024-01-01T12:00:00Z"
      },
      "guardrail_metrics": [
        {
          "metric_id": "metric-error-rate",
          "trigger_action": "PAUSE",
          "triggered_by": "guardrail_monitor"
        }
      ],
      "id": "550e8400-e29b-41d4-a716-446655440020",
      "key": "prod-rollout",
      "name": "Production Rollout",
      "order_position": 0,
      "targeting_rules": [
        {
          "conditions": [
            {
              "attribute": "country",
              "created_at": "2024-01-01T12:00:00Z",
              "id": "550e8400-e29b-41d4-a716-446655440070",
              "operator": "ONE_OF",
              "saved_filter_id": "550e8400-e29b-41d4-a716-446655440090",
              "updated_at": "2024-01-01T12:00:00Z",
              "value": [
                "US",
                "CA"
              ]
            }
          ],
          "created_at": "2024-01-01T12:00:00Z",
          "id": "550e8400-e29b-41d4-a716-446655440060",
          "updated_at": "2024-01-01T12:00:00Z"
        }
      ],
      "type": "FEATURE_GATE",
      "updated_at": "2024-01-01T12:00:00Z",
      "variant_weights": [
        {
          "created_at": "2024-01-01T12:00:00Z",
          "id": "59061199-e2ff-46e9-8b40-2193e3b21687",
          "updated_at": "2024-01-01T12:00:00Z",
          "value": 50,
          "variant": {
            "created_at": "2023-01-01T00:00:00Z",
            "id": "550e8400-e29b-41d4-a716-446655440002",
            "key": "variant-abc123",
            "name": "Variant ABC123",
            "updated_at": "2023-01-01T00:00:00Z",
            "value": "true"
          },
          "variant_id": "550e8400-e29b-41d4-a716-446655440001"
        }
      ]
    },
    "id": "550e8400-e29b-41d4-a716-446655440020",
    "type": "allocations"
  }
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="202" %}
Accepted - Approval required for this change

{% tabs %}
{% tab label="Model" %}
Response containing a single targeting rule (allocation).

| Parent field       | Field                                        | Type      | Description                                                                                                                                                                                                                             |
| ------------------ | -------------------------------------------- | --------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|                    | data [*required*]                            | object    | Data wrapper for targeting rule allocation responses.                                                                                                                                                                                   |
| data               | attributes [*required*]                      | object    | Targeting rule (allocation) details for a feature flag environment.                                                                                                                                                                     |
| attributes         | created_at [*required*]                      | date-time | The timestamp when the targeting rule allocation was created.                                                                                                                                                                           |
| attributes         | environment_ids [*required*]                 | [string]  | Environment IDs associated with this targeting rule allocation.                                                                                                                                                                         |
| attributes         | experiment_id                                | string    | The experiment ID linked to this targeting rule allocation.                                                                                                                                                                             |
| attributes         | exposure_schedule                            | object    | Progressive release details for a targeting rule allocation.                                                                                                                                                                            |
| exposure_schedule  | absolute_start_time                          | date-time | The absolute UTC start time for this schedule.                                                                                                                                                                                          |
| exposure_schedule  | allocation_id [*required*]                   | uuid      | The unique identifier (UUID) of the targeting rule allocation this progressive rollout belongs to. This is not the allocation key that SDKs report in evaluation results and exposure events.                                           |
| exposure_schedule  | control_variant_id                           | string    | The control variant ID used for experiment comparisons.                                                                                                                                                                                 |
| exposure_schedule  | created_at [*required*]                      | date-time | The timestamp when the schedule was created.                                                                                                                                                                                            |
| exposure_schedule  | guardrail_triggered_action                   | string    | Last guardrail action triggered for this schedule.                                                                                                                                                                                      |
| exposure_schedule  | guardrail_triggers [*required*]              | [object]  | Guardrail trigger records for this schedule.                                                                                                                                                                                            |
| guardrail_triggers | allocation_exposure_schedule_id [*required*] | uuid      | The progressive rollout ID this trigger belongs to.                                                                                                                                                                                     |
| guardrail_triggers | created_at [*required*]                      | date-time | The timestamp when this trigger was created.                                                                                                                                                                                            |
| guardrail_triggers | flagging_variant_id [*required*]             | uuid      | The variant ID that triggered this event.                                                                                                                                                                                               |
| guardrail_triggers | id [*required*]                              | uuid      | The unique identifier of the guardrail trigger.                                                                                                                                                                                         |
| guardrail_triggers | metric_id [*required*]                       | string    | The metric ID associated with the trigger.                                                                                                                                                                                              |
| guardrail_triggers | triggered_action [*required*]                | string    | The action that was triggered.                                                                                                                                                                                                          |
| guardrail_triggers | updated_at [*required*]                      | date-time | The timestamp when this trigger was last updated.                                                                                                                                                                                       |
| exposure_schedule  | id                                           | uuid      | The unique identifier of the progressive rollout.                                                                                                                                                                                       |
| exposure_schedule  | rollout_options [*required*]                 | object    | Applied progression options for a progressive rollout.                                                                                                                                                                                  |
| rollout_options    | autostart [*required*]                       | boolean   | Whether the schedule starts automatically.                                                                                                                                                                                              |
| rollout_options    | selection_interval_ms [*required*]           | int64     | Interval in milliseconds for uniform interval strategies.                                                                                                                                                                               |
| rollout_options    | strategy [*required*]                        | enum      | The progression strategy used by a progressive rollout. Allowed enum values: `UNIFORM_INTERVALS`, `NO_ROLLOUT`.                                                                                                                         |
| exposure_schedule  | rollout_steps [*required*]                   | [object]  | Ordered progression steps for exposure.                                                                                                                                                                                                 |
| rollout_steps      | allocation_exposure_schedule_id [*required*] | uuid      | The progressive rollout ID this step belongs to.                                                                                                                                                                                        |
| rollout_steps      | created_at [*required*]                      | date-time | The timestamp when the progression step was created.                                                                                                                                                                                    |
| rollout_steps      | exposure_ratio [*required*]                  | double    | The exposure ratio for this step.                                                                                                                                                                                                       |
| rollout_steps      | grouped_step_index [*required*]              | int64     | Logical index grouping related steps.                                                                                                                                                                                                   |
| rollout_steps      | id [*required*]                              | uuid      | The unique identifier of the progression step.                                                                                                                                                                                          |
| rollout_steps      | interval_ms                                  | int64     | Step duration in milliseconds.                                                                                                                                                                                                          |
| rollout_steps      | is_pause_record [*required*]                 | boolean   | Whether this step represents a pause record.                                                                                                                                                                                            |
| rollout_steps      | order_position [*required*]                  | int64     | Sort order for the progression step.                                                                                                                                                                                                    |
| rollout_steps      | updated_at [*required*]                      | date-time | The timestamp when the progression step was last updated.                                                                                                                                                                               |
| exposure_schedule  | updated_at [*required*]                      | date-time | The timestamp when the schedule was last updated.                                                                                                                                                                                       |
| attributes         | guardrail_metrics [*required*]               | [object]  | Guardrail metrics associated with this targeting rule allocation.                                                                                                                                                                       |
| guardrail_metrics  | metric_id [*required*]                       | string    | The metric ID to monitor.                                                                                                                                                                                                               |
| guardrail_metrics  | trigger_action [*required*]                  | enum      | Action to perform when a guardrail threshold is triggered. Allowed enum values: `PAUSE`, `ABORT`.                                                                                                                                       |
| guardrail_metrics  | triggered_by                                 | string    | The signal or system that triggered the action.                                                                                                                                                                                         |
| attributes         | id                                           | uuid      | The unique identifier of the targeting rule allocation. Use this ID with the allocation management endpoints, such as `/api/v2/allocations/{allocation_id}`. It is not included in SDK evaluation results or exposure events.           |
| attributes         | key [*required*]                             | string    | The unique key of the targeting rule allocation. SDKs report this key in flag evaluation results and exposure events to indicate which targeting rule assigned the variant. Use it to match evaluation or experiment data to this rule. |
| attributes         | name [*required*]                            | string    | The display name of the targeting rule.                                                                                                                                                                                                 |
| attributes         | order_position [*required*]                  | int64     | Sort order position within the environment.                                                                                                                                                                                             |
| attributes         | targeting_rules [*required*]                 | [object]  | Conditions associated with this targeting rule allocation.                                                                                                                                                                              |
| targeting_rules    | conditions [*required*]                      | [object]  | Conditions evaluated by this targeting rule.                                                                                                                                                                                            |
| conditions         | attribute                                    | string    | The user or request attribute to evaluate. Omitted for saved-filter references.                                                                                                                                                         |
| conditions         | created_at [*required*]                      | date-time | The timestamp when the condition was created.                                                                                                                                                                                           |
| conditions         | id [*required*]                              | uuid      | The unique identifier of the condition.                                                                                                                                                                                                 |
| conditions         | operator                                     | enum      | The operator used in a targeting condition. Allowed enum values: `LT`, `LTE`, `GT`, `GTE`, `MATCHES`, `NOT_MATCHES`, `ONE_OF`, `NOT_ONE_OF`, `IS_NULL`, `EQUALS`.                                                                       |
| conditions         | saved_filter_id                              | uuid      | The ID of the saved filter referenced by this condition, or null for inline conditions.                                                                                                                                                 |
| conditions         | updated_at [*required*]                      | date-time | The timestamp when the condition was last updated.                                                                                                                                                                                      |
| conditions         | value                                        | [string]  | Values used by the selected operator. Omitted for saved-filter references.                                                                                                                                                              |
| targeting_rules    | created_at [*required*]                      | date-time | The timestamp when the targeting rule was created.                                                                                                                                                                                      |
| targeting_rules    | id [*required*]                              | uuid      | The unique identifier of the targeting rule.                                                                                                                                                                                            |
| targeting_rules    | updated_at [*required*]                      | date-time | The timestamp when the targeting rule was last updated.                                                                                                                                                                                 |
| attributes         | type [*required*]                            | enum      | The type of targeting rule (called allocation in the API model). Allowed enum values: `FEATURE_GATE`, `CANARY`.                                                                                                                         |
| attributes         | updated_at [*required*]                      | date-time | The timestamp when the targeting rule allocation was last updated.                                                                                                                                                                      |
| attributes         | variant_weights [*required*]                 | [object]  | Weighted variant assignments for this targeting rule allocation.                                                                                                                                                                        |
| variant_weights    | created_at                                   | date-time | The timestamp when the variant weight was created.                                                                                                                                                                                      |
| variant_weights    | id                                           | uuid      | Unique identifier of the variant weight assignment.                                                                                                                                                                                     |
| variant_weights    | updated_at                                   | date-time | The timestamp when the variant weight was last updated.                                                                                                                                                                                 |
| variant_weights    | value [*required*]                           | double    | The percentage weight for the variant.                                                                                                                                                                                                  |
| variant_weights    | variant                                      | object    | A variant of a feature flag.                                                                                                                                                                                                            |
| variant            | created_at                                   | date-time | The timestamp when the variant was created.                                                                                                                                                                                             |
| variant            | id [*required*]                              | uuid      | The unique identifier of the variant.                                                                                                                                                                                                   |
| variant            | key [*required*]                             | string    | The unique key of the variant.                                                                                                                                                                                                          |
| variant            | name [*required*]                            | string    | The name of the variant.                                                                                                                                                                                                                |
| variant            | updated_at                                   | date-time | The timestamp when the variant was last updated.                                                                                                                                                                                        |
| variant            | value [*required*]                           | string    | The value of the variant as a string.                                                                                                                                                                                                   |
| variant_weights    | variant_id [*required*]                      | uuid      | The variant ID.                                                                                                                                                                                                                         |
| data               | id [*required*]                              | uuid      | The unique identifier of the targeting rule allocation. Use this ID with the allocation management endpoints, such as `/api/v2/allocations/{allocation_id}`. It is not included in SDK evaluation results or exposure events.           |
| data               | type [*required*]                            | enum      | The resource type. Allowed enum values: `allocations`.                                                                                                                                                                                  |
{% /tab %}

{% tab label="Example" %}
```json
{
  "data": {
    "attributes": {
      "created_at": "2024-01-01T12:00:00Z",
      "environment_ids": [
        "550e8400-e29b-41d4-a716-446655440001"
      ],
      "experiment_id": "550e8400-e29b-41d4-a716-446655440030",
      "exposure_schedule": {
        "absolute_start_time": "2025-06-13T12:00:00Z",
        "allocation_id": "550e8400-e29b-41d4-a716-446655440020",
        "control_variant_id": "550e8400-e29b-41d4-a716-446655440012",
        "created_at": "2024-01-01T12:00:00Z",
        "guardrail_triggered_action": "PAUSE",
        "guardrail_triggers": [
          {
            "allocation_exposure_schedule_id": "550e8400-e29b-41d4-a716-446655440010",
            "created_at": "2024-01-01T12:00:00Z",
            "flagging_variant_id": "550e8400-e29b-41d4-a716-446655440001",
            "id": "550e8400-e29b-41d4-a716-446655440080",
            "metric_id": "metric-error-rate",
            "triggered_action": "PAUSE",
            "updated_at": "2024-01-01T12:00:00Z"
          }
        ],
        "id": "550e8400-e29b-41d4-a716-446655440010",
        "rollout_options": {
          "autostart": false,
          "selection_interval_ms": 3600000,
          "strategy": "UNIFORM_INTERVALS"
        },
        "rollout_steps": [
          {
            "allocation_exposure_schedule_id": "550e8400-e29b-41d4-a716-446655440010",
            "created_at": "2024-01-01T12:00:00Z",
            "exposure_ratio": 0.1,
            "grouped_step_index": 0,
            "id": "550e8400-e29b-41d4-a716-446655440040",
            "interval_ms": 3600000,
            "is_pause_record": false,
            "order_position": 0,
            "updated_at": "2024-01-01T12:00:00Z"
          }
        ],
        "updated_at": "2024-01-01T12:00:00Z"
      },
      "guardrail_metrics": [
        {
          "metric_id": "metric-error-rate",
          "trigger_action": "PAUSE",
          "triggered_by": "guardrail_monitor"
        }
      ],
      "id": "550e8400-e29b-41d4-a716-446655440020",
      "key": "prod-rollout",
      "name": "Production Rollout",
      "order_position": 0,
      "targeting_rules": [
        {
          "conditions": [
            {
              "attribute": "country",
              "created_at": "2024-01-01T12:00:00Z",
              "id": "550e8400-e29b-41d4-a716-446655440070",
              "operator": "ONE_OF",
              "saved_filter_id": "550e8400-e29b-41d4-a716-446655440090",
              "updated_at": "2024-01-01T12:00:00Z",
              "value": [
                "US",
                "CA"
              ]
            }
          ],
          "created_at": "2024-01-01T12:00:00Z",
          "id": "550e8400-e29b-41d4-a716-446655440060",
          "updated_at": "2024-01-01T12:00:00Z"
        }
      ],
      "type": "FEATURE_GATE",
      "updated_at": "2024-01-01T12:00:00Z",
      "variant_weights": [
        {
          "created_at": "2024-01-01T12:00:00Z",
          "id": "59061199-e2ff-46e9-8b40-2193e3b21687",
          "updated_at": "2024-01-01T12:00:00Z",
          "value": 50,
          "variant": {
            "created_at": "2023-01-01T00:00:00Z",
            "id": "550e8400-e29b-41d4-a716-446655440002",
            "key": "variant-abc123",
            "name": "Variant ABC123",
            "updated_at": "2023-01-01T00:00:00Z",
            "value": "true"
          },
          "variant_id": "550e8400-e29b-41d4-a716-446655440001"
        }
      ]
    },
    "id": "550e8400-e29b-41d4-a716-446655440020",
    "type": "allocations"
  }
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="400" %}
Bad Request

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="403" %}
Forbidden

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="404" %}
Not Found

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="409" %}
Conflict

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}

{% tab label="429" %}
Too many requests

{% tabs %}
{% tab label="Model" %}
API error response.

| Field               | Type     | Description       |
| ------------------- | -------- | ----------------- |
| errors [*required*] | [string] | A list of errors. |
{% /tab %}

{% tab label="Example" %}
```json
{
  "errors": [
    "Bad Request"
  ]
}
```
{% /tab %}
{% /tabs %}
{% /tab %}
{% /tabs %}

### Code Example

{% tabs %}
{% tab label="Curl" %}
```bash
# Path parameters
export feature_flag_id="550e8400-e29b-41d4-a716-446655440000"
export environment_id="550e8400-e29b-41d4-a716-446655440001"

# Set your Datadog site and credentials
export DD_SITE="datadoghq.com" # Or us3.datadoghq.com, us5.datadoghq.com, datadoghq.eu, ap1.datadoghq.com, ap2.datadoghq.com, uk1.datadoghq.com, ddog-gov.com, us2.ddog-gov.com
# Use a Personal Access Token or Service Access Token
export DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>"

curl -X POST "https://api.${DD_SITE}/api/v2/feature-flags/${feature_flag_id}/environments/${environment_id}/allocations" \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer ${DD_BEARER_TOKEN}" \
-d @- << EOF
{
  "data": {
    "type": "allocations",
    "attributes": {
      "name": "New targeting rule Example-Feature-Flag",
      "key": "new-targeting-rule-example-feature-flag",
      "targeting_rules": [],
      "variant_weights": [
        {
          "variant_id": "550e8400-e29b-41d4-a716-446655440002",
          "value": 100
        }
      ],
      "guardrail_metrics": [],
      "type": "CANARY"
    }
  }
}
EOF
```
{% /tab %}

{% tab label="Go" %}
```go
// Create allocation for a flag in an environment returns "Created" response

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/DataDog/datadog-api-client-go/v2/api/datadog"
	"github.com/DataDog/datadog-api-client-go/v2/api/datadogV2"
	"github.com/google/uuid"
)

func main() {
	// there is a valid "feature_flag" in the system
	FeatureFlagDataAttributesVariants0ID := uuid.MustParse(os.Getenv("FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID"))
	FeatureFlagDataID := uuid.MustParse(os.Getenv("FEATURE_FLAG_DATA_ID"))

	// there is a valid "environment" in the system
	EnvironmentDataID := uuid.MustParse(os.Getenv("ENVIRONMENT_DATA_ID"))

	body := datadogV2.CreateAllocationsRequest{
		Data: datadogV2.AllocationDataRequest{
			Type: datadogV2.ALLOCATIONDATATYPE_ALLOCATIONS,
			Attributes: datadogV2.UpsertAllocationRequest{
				Name:           "New targeting rule Example-Feature-Flag",
				Key:            "new-targeting-rule-example-feature-flag",
				TargetingRules: []datadogV2.TargetingRuleRequest{},
				VariantWeights: []datadogV2.VariantWeightRequest{
					{
						VariantId: datadog.PtrUUID(FeatureFlagDataAttributesVariants0ID),
						Value:     100,
					},
				},
				GuardrailMetrics: []datadogV2.GuardrailMetricRequest{},
				Type:             datadogV2.ALLOCATIONTYPE_CANARY,
			},
		},
	}
	ctx := datadog.NewDefaultContext(context.Background())
	ctx = context.WithValue(ctx, datadog.ContextAccessToken, os.Getenv("DD_BEARER_TOKEN"))
	configuration := datadog.NewConfiguration()
	apiClient := datadog.NewAPIClient(configuration)
	api := datadogV2.NewFeatureFlagsApi(apiClient)
	resp, r, err := api.CreateAllocationsForFeatureFlagInEnvironment(ctx, FeatureFlagDataID, EnvironmentDataID, body)

	if err != nil {
		fmt.Fprintf(os.Stderr, "Error when calling `FeatureFlagsApi.CreateAllocationsForFeatureFlagInEnvironment`: %v\n", err)
		fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r)
	}

	responseContent, _ := json.MarshalIndent(resp, "", "  ")
	fmt.Fprintf(os.Stdout, "Response from `FeatureFlagsApi.CreateAllocationsForFeatureFlagInEnvironment`:\n%s\n", responseContent)
}
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=go) and then save the example to `main.go` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" go run "main.go"
```
{% /tab %}

{% tab label="Java" %}
```java
// Create allocation for a flag in an environment returns "Created" response

import com.datadog.api.client.ApiClient;
import com.datadog.api.client.ApiException;
import com.datadog.api.client.v2.api.FeatureFlagsApi;
import com.datadog.api.client.v2.model.AllocationDataRequest;
import com.datadog.api.client.v2.model.AllocationDataType;
import com.datadog.api.client.v2.model.AllocationResponse;
import com.datadog.api.client.v2.model.AllocationType;
import com.datadog.api.client.v2.model.CreateAllocationsRequest;
import com.datadog.api.client.v2.model.UpsertAllocationRequest;
import com.datadog.api.client.v2.model.VariantWeightRequest;
import java.util.Collections;
import java.util.UUID;

public class Example {
  public static void main(String[] args) {
    ApiClient defaultClient = ApiClient.getDefaultApiClient();
    defaultClient.setAccessToken(System.getenv("DD_BEARER_TOKEN"));
    FeatureFlagsApi apiInstance = new FeatureFlagsApi(defaultClient);

    // there is a valid "feature_flag" in the system
    UUID FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID = null;
    try {
      FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID =
          UUID.fromString(System.getenv("FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID"));
    } catch (IllegalArgumentException e) {
      System.err.println("Error parsing UUID: " + e.getMessage());
    }
    UUID FEATURE_FLAG_DATA_ID = null;
    try {
      FEATURE_FLAG_DATA_ID = UUID.fromString(System.getenv("FEATURE_FLAG_DATA_ID"));
    } catch (IllegalArgumentException e) {
      System.err.println("Error parsing UUID: " + e.getMessage());
    }

    // there is a valid "environment" in the system
    UUID ENVIRONMENT_DATA_ID = null;
    try {
      ENVIRONMENT_DATA_ID = UUID.fromString(System.getenv("ENVIRONMENT_DATA_ID"));
    } catch (IllegalArgumentException e) {
      System.err.println("Error parsing UUID: " + e.getMessage());
    }

    CreateAllocationsRequest body =
        new CreateAllocationsRequest()
            .data(
                new AllocationDataRequest()
                    .type(AllocationDataType.ALLOCATIONS)
                    .attributes(
                        new UpsertAllocationRequest()
                            .name("New targeting rule Example-Feature-Flag")
                            .key("new-targeting-rule-example-feature-flag")
                            .variantWeights(
                                Collections.singletonList(
                                    new VariantWeightRequest()
                                        .variantId(FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID)
                                        .value(100.0)))
                            .type(AllocationType.CANARY)));

    try {
      AllocationResponse result =
          apiInstance.createAllocationsForFeatureFlagInEnvironment(
              FEATURE_FLAG_DATA_ID, ENVIRONMENT_DATA_ID, body);
      System.out.println(result);
    } catch (ApiException e) {
      System.err.println(
          "Exception when calling FeatureFlagsApi#createAllocationsForFeatureFlagInEnvironment");
      System.err.println("Status code: " + e.getCode());
      System.err.println("Reason: " + e.getResponseBody());
      System.err.println("Response headers: " + e.getResponseHeaders());
      e.printStackTrace();
    }
  }
}
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=java) and then save the example to `Example.java` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" java "Example.java"
```
{% /tab %}

{% tab label="Python" %}
```python
"""
Create allocation for a flag in an environment returns "Created" response
"""

from os import environ
from datadog_api_client import ApiClient, Configuration
from datadog_api_client.v2.api.feature_flags_api import FeatureFlagsApi
from datadog_api_client.v2.model.allocation_data_request import AllocationDataRequest
from datadog_api_client.v2.model.allocation_data_type import AllocationDataType
from datadog_api_client.v2.model.allocation_type import AllocationType
from datadog_api_client.v2.model.create_allocations_request import CreateAllocationsRequest
from datadog_api_client.v2.model.upsert_allocation_request import UpsertAllocationRequest
from datadog_api_client.v2.model.variant_weight_request import VariantWeightRequest

# there is a valid "feature_flag" in the system
FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID = environ["FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID"]
FEATURE_FLAG_DATA_ID = environ["FEATURE_FLAG_DATA_ID"]

# there is a valid "environment" in the system
ENVIRONMENT_DATA_ID = environ["ENVIRONMENT_DATA_ID"]

body = CreateAllocationsRequest(
    data=AllocationDataRequest(
        type=AllocationDataType.ALLOCATIONS,
        attributes=UpsertAllocationRequest(
            name="New targeting rule Example-Feature-Flag",
            key="new-targeting-rule-example-feature-flag",
            targeting_rules=[],
            variant_weights=[
                VariantWeightRequest(
                    variant_id=FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID,
                    value=100.0,
                ),
            ],
            guardrail_metrics=[],
            type=AllocationType.CANARY,
        ),
    ),
)

configuration = Configuration()
configuration.access_token = environ["DD_BEARER_TOKEN"]
with ApiClient(configuration) as api_client:
    api_instance = FeatureFlagsApi(api_client)
    response = api_instance.create_allocations_for_feature_flag_in_environment(
        feature_flag_id=FEATURE_FLAG_DATA_ID, environment_id=ENVIRONMENT_DATA_ID, body=body
    )

    print(response)
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=python) and then save the example to `example.py` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" python3 "example.py"
```
{% /tab %}

{% tab label="Ruby" %}
```ruby
# Create allocation for a flag in an environment returns "Created" response

require "datadog_api_client"
DatadogAPIClient.configure do |config|
  config.access_token = ENV["DD_BEARER_TOKEN"]
end
api_instance = DatadogAPIClient::V2::FeatureFlagsAPI.new

# there is a valid "feature_flag" in the system
FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID = ENV["FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID"]
FEATURE_FLAG_DATA_ID = ENV["FEATURE_FLAG_DATA_ID"]

# there is a valid "environment" in the system
ENVIRONMENT_DATA_ID = ENV["ENVIRONMENT_DATA_ID"]

body = DatadogAPIClient::V2::CreateAllocationsRequest.new({
  data: DatadogAPIClient::V2::AllocationDataRequest.new({
    type: DatadogAPIClient::V2::AllocationDataType::ALLOCATIONS,
    attributes: DatadogAPIClient::V2::UpsertAllocationRequest.new({
      name: "New targeting rule Example-Feature-Flag",
      key: "new-targeting-rule-example-feature-flag",
      targeting_rules: [],
      variant_weights: [
        DatadogAPIClient::V2::VariantWeightRequest.new({
          variant_id: FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID,
          value: 100,
        }),
      ],
      guardrail_metrics: [],
      type: DatadogAPIClient::V2::AllocationType::CANARY,
    }),
  }),
})
p api_instance.create_allocations_for_feature_flag_in_environment(FEATURE_FLAG_DATA_ID, ENVIRONMENT_DATA_ID, body)
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=ruby) and then save the example to `example.rb` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" ruby "example.rb"
```
{% /tab %}

{% tab label="Rust" %}
```rust
// Create allocation for a flag in an environment returns "Created" response
use datadog_api_client::datadog;
use datadog_api_client::datadogV2::api_feature_flags::FeatureFlagsAPI;
use datadog_api_client::datadogV2::model::AllocationDataRequest;
use datadog_api_client::datadogV2::model::AllocationDataType;
use datadog_api_client::datadogV2::model::AllocationType;
use datadog_api_client::datadogV2::model::CreateAllocationsRequest;
use datadog_api_client::datadogV2::model::UpsertAllocationRequest;
use datadog_api_client::datadogV2::model::VariantWeightRequest;

#[tokio::main]
async fn main() {
    // there is a valid "feature_flag" in the system
    let feature_flag_data_attributes_variants_0_id = uuid::Uuid::parse_str(
        &std::env::var("FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID").unwrap(),
    )
    .expect("Invalid UUID");
    let feature_flag_data_id =
        uuid::Uuid::parse_str(&std::env::var("FEATURE_FLAG_DATA_ID").unwrap())
            .expect("Invalid UUID");

    // there is a valid "environment" in the system
    let environment_data_id = uuid::Uuid::parse_str(&std::env::var("ENVIRONMENT_DATA_ID").unwrap())
        .expect("Invalid UUID");
    let body = CreateAllocationsRequest::new(AllocationDataRequest::new(
        UpsertAllocationRequest::new(
            "new-targeting-rule-example-feature-flag".to_string(),
            "New targeting rule Example-Feature-Flag".to_string(),
            AllocationType::CANARY,
        )
        .guardrail_metrics(vec![])
        .targeting_rules(vec![])
        .variant_weights(vec![VariantWeightRequest::new(100.0)
            .variant_id(feature_flag_data_attributes_variants_0_id.clone())]),
        AllocationDataType::ALLOCATIONS,
    ));
    let configuration = datadog::Configuration::new();
    let api = FeatureFlagsAPI::with_config(configuration);
    let resp = api
        .create_allocations_for_feature_flag_in_environment(
            feature_flag_data_id.clone(),
            environment_data_id.clone(),
            body,
        )
        .await;
    if let Ok(value) = resp {
        println!("{:#?}", value);
    } else {
        println!("{:#?}", resp.unwrap_err());
    }
}
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=rust) and then save the example to `src/main.rs` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_API_KEY="<DD_API_KEY>" DD_APP_KEY="<DD_APP_KEY>" cargo run
```
{% /tab %}

{% tab label="TypeScript" %}
```typescript
/**
 * Create allocation for a flag in an environment returns "Created" response
 */

import { client, v2 } from "@datadog/datadog-api-client";

const configuration = client.createConfiguration({
  authMethods: {
    AuthZ: {
      accessToken: process.env.DD_BEARER_TOKEN as string,
    },
  },
});
const apiInstance = new v2.FeatureFlagsApi(configuration);

// there is a valid "feature_flag" in the system
const FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID = process.env
  .FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID as string;
const FEATURE_FLAG_DATA_ID = process.env.FEATURE_FLAG_DATA_ID as string;

// there is a valid "environment" in the system
const ENVIRONMENT_DATA_ID = process.env.ENVIRONMENT_DATA_ID as string;

const params: v2.FeatureFlagsApiCreateAllocationsForFeatureFlagInEnvironmentRequest =
  {
    body: {
      data: {
        type: "allocations",
        attributes: {
          name: "New targeting rule Example-Feature-Flag",
          key: "new-targeting-rule-example-feature-flag",
          targetingRules: [],
          variantWeights: [
            {
              variantId: FEATURE_FLAG_DATA_ATTRIBUTES_VARIANTS_0_ID,
              value: 100,
            },
          ],
          guardrailMetrics: [],
          type: "CANARY",
        },
      },
    },
    featureFlagId: FEATURE_FLAG_DATA_ID,
    environmentId: ENVIRONMENT_DATA_ID,
  };

apiInstance
  .createAllocationsForFeatureFlagInEnvironment(params)
  .then((data: v2.AllocationResponse) => {
    console.log(
      "API called successfully. Returned data: " + JSON.stringify(data)
    );
  })
  .catch((error: any) => console.error(error));
```

#### Instructions

First [install the library and its dependencies](https://docs.datadoghq.com/api/latest.md?code-lang=typescript) and then save the example to `example.ts` and run following commands:

```bash
DD_SITE="datadoghq.com" DD_BEARER_TOKEN="<PERSONAL_ACCESS_TOKEN OR SERVICE_ACCESS_TOKEN>" npx tsx "example.ts"
```
{% /tab %}
{% /tabs %}
