# v2 (latest)

### Overview

The Decision API is a RESTful API that serves as the engine behind Flagship. It is published on Amazon API Gateway and distributed in eight regions with collocated AWS Lambda and DynamoDB Global Tables to deliver exceptional performance across the globe.

You can access the Decision API endpoints to trigger visitor assignments according to the targeting criteria you define in the Flagship dashboard and receive responses with flag, campaign, and variation details.

Implementing the Decision API directly in your application lets you and your team fine-tune each call and digest every response without any additional layers between Flagship and your applications.

The Decision API is language-agnostic by design, meaning you can use Flagship even if your stack includes a variety of programming languages, or if you would like to experiment with more specialized languages or frameworks for which we don't yet offer a dedicated SDK.

If you'd rather use an SDK with preconfigured methods to implement the Decision API, you can see the full list of available languages and learn more about SDK-specific features [here](/server-side/sdks.md).

We have language bindings in Shell (Curl) and Javascript (ES6). You can toggle between programming languages by using the tabs above each code example.

Feel free to [contact us](mailto:product.feedback@abtasty.com?subject=Flagship%20Developer%20Documentation) if you have any questions regarding this documentation.

### Authentication

Decision API resources are authenticated with an API key. This version of the Decision API requires the API Key to be sent in the following HTTP header:

`x-api-key: YOUR_API_KEY`

You can access your API Key in the [Flagship Platform](https://app.flagship.io/), inside Parameters / Environment & Security

{% hint style="info" %}
📘 API throttling

The API endpoint /campaigns is limited to a certain amount of calls:

* 200req/s with a temporary burst of 600req/s

If you were to have more call than planned, you will received a 429 error, enabling the default behavior for your users.

Want a higher limitation? Nothing is impossible 😉 Contact your dedicated account manager or our [support](mailto:support@flagship.io?subject=More%20API%20Quota).
{% endhint %}

### Flagship endpoints

#### Campaigns

**Run all campaign assignments**

This endpoint retrieves all the campaigns that correspond to the specified user and context attributes.

By default, the API will send a `CAMPAIGN` hit to Flagship for each campaign in the response to notify the report that the `visitor_id` has been assigned to it.

```javascript
const response = await axios.post(
  "https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns",
  {
    visitor_id: "YOUR_VISITOR_ID",
    context: {
      "YOUR KEY": "YOUR VALUE",
    },
    visitor_consent: true,
    decision_group: null,
  },
  {
    headers: { "x-api-key": "YOUR_API_KEY" },
  }
);
```

```shell
curl -X POST \
  https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
        "visitor_id": "YOUR_VISITOR_ID",
        "context": {
            "YOUR KEY": "YOUR VALUE"
        },
        "decision_group": null
    }'
```

The above command returns JSON structured as follows:

```json
{
  "visitorId": "YOUR_VISITOR_ID",
  "campaigns": [
    {
      "id": "<CAMPAIGN_ID>",
      "variationGroupId": "<VARIATION_GROUP_ID>",
      "variation": {
        "id": "<VARIATION_ID>",
        "modifications": {
          "type": "JSON",
          "value": {
            "key": "value"
          }
        }
      }
    }
  ]
}
```

**HTTP Request**

```
POST https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns
```

**Route Parameters**

| Parameter       | Required | Default | Description                                                                                                                                         |
| --------------- | -------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| ENVIRONMENT\_ID | yes      |         | Identifies your account and environment (preprod or prod). Check your Flagship dashboard to [**find this ID**](docs:getting-started-with-flagship). |

**Query Parameters**

| Parameter | Required | Default | Description                                                                                                                  |
| --------- | -------- | ------- | ---------------------------------------------------------------------------------------------------------------------------- |
| mode      | no       | normal  | Specifies the format of the response body used by Flagship to return your campaign information. [**See description**](#mode) |

**Body Parameters**

| Parameter        | Type    | Required | Default | Description                                                                                                                                                                                                                                              |
| ---------------- | ------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitor\_id      | string  | yes      |         | Unique identifier for the application user or website visitor. This can be an ID from your database or a session ID. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#visitor-id)                               |
| anonymous\_id    | string  | no       | empty   | Identifier for the application user or website visitor when the visitor is anonymous. This can be a session ID for instance. [**Learn more**](#experience-continuity)                                                                                    |
| context          | object  | no       | empty   | JSON object of key-value pairs describing the user and device context. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#user-context)                                                                           |
| visitor\_consent | boolean | no       | true    | Determines if your visitor has consented or not to your GDPR rules. [**See description**](#visitor-consent)                                                                                                                                              |
| trigger\_hit     | boolean | no       | true    | Determines whether a `CAMPAIGN` hit should be automatically sent to Flagship for each campaign targeting the user. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/universal-collect-documentation/README.md#campaign-activation) |
| decision\_group  | string  | no       | empty   | If specified, users that match the targeting will be affected to a unique variation ID per decision group. [**See description**](#decision-group)                                                                                                        |

{% hint style="info" %}
📘

The `visitor_id` should be a unique identifier for your application user or website visitor. Using a consistent `visitor_id` is what guarantees that a visitor will see the same variation of a campaign across sessions and clients.
{% endhint %}

**Response Parameters**

This API endpoint returns a Campaign response JSON object. [**See campaign response model**](#campaign)

| Parameter           | type   | Description                                                                                                                                                     |
| ------------------- | ------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorId           | string | The visitor ID as you sent it in the request (only if `mode=normal` or `mode=full`).                                                                            |
| campaigns           | array  | An array of all the campaigns to which the user is assigned (only if `mode=normal` or `mode=full`). [**See Campaign response model**](#campaign)                |
| campaignsVariation  | array  | An array of campaign IDs and the assigned variation ID (only if `mode=simple` or `mode=full`). [**See Campaign Variation response model**](#campaign-variation) |
| mergedModifications | object | A key-value object of all the merged modifications of the campaign (only if `mode=simple` or `mode=full`).                                                      |

**Run a single campaign assignment**

This endpoint retrieves the assignment of your visitor ID with a specific context (key-value pairs) to the specified campaign ID.

By default, the API will send a `CAMPAIGN` hit to Flagship for each campaign in the response to trigger [campaign assignment events](https://github.com/flagship-io/Gitbook/blob/main/docs/universal-collect-documentation/README.md#campaign-activation) for the `visitor_id`.

```javascript
const response = await axios.post(
  "https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns/<CAMPAIGN_ID>",
  {
    visitor_id: "YOUR_VISITOR_ID",
    context: {
      "YOUR KEY": "YOUR VALUE",
    },
    // Warning: use this parameter for GDPR compliance. See #visitor-consent for details
    visitor_consent: true,
    // Optional: see #decision-groups for details
    decision_group: null,
  },
  {
    headers: { "x-api-key": "YOUR_API_KEY" },
  }
);
```

```shell
curl -X POST \
  https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns/<CAMPAIGN_ID> \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
        "visitor_id": "YOUR_VISITOR_ID",
        "context": {
            "YOUR KEY": "YOUR VALUE"
        },
        // Optional: see #decision-groups for details
        "decision_group": null
    }'
```

The above command returns JSON structured like this:

```json
{
  "id": "<CAMPAIGN_ID>",
  "variationGroupId": "<VARIATION_GROUP_ID>",
  "variation": {
    "id": "<VARIATION_ID>",
    "modifications": {
      "type": "JSON",
      "value": {
        "key": "value"
      }
    }
  }
}
```

**HTTP Request**

```
POST https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns/<CAMPAIGN_ID>
```

**Query Parameters**

| Parameter       | Required | Default | Description                                                                                                                                                                                                    |
| --------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ENVIRONMENT\_ID | yes      |         | Identifies your account and environment (preprod or prod). Check your Flagship dashboard to [**find this ID**](https://github.com/flagship-io/Gitbook/blob/main/docs/getting-started-with-flagship/README.md). |
| CAMPAIGN\_ID    | yes      |         | Identifies the campaign for which you want to check the user's assignment. You can use Flagship generated campaign ID or the slug you specified for your campaign.                                             |

**Body Parameters**

| Parameter              | Type    | Required | Default | Description                                                                                                                                                                                                                |
| ---------------------- | ------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitor\_id            | string  | yes      |         | Unique identifier for the application user or website visitor. This can be an ID from your database or a session ID. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#visitor-id) |
| anonymous\_id          | string  | no       | empty   | Identifier for the application user or website visitor when the visitor is anonymous. This can be a session ID for instance. [**Learn more**](#experience-continuity)                                                      |
| context                | object  | no       | empty   | JSON object of key-value pairs describing the user and device context. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#user-context)                                             |
| visitor\_consent       | boolean | no       | true    | Determines if your visitor has consented or not to your GDPR rules. If yes, the context key-value pairs will be saved in your data segments and you will be able to filter on it. [**Learn more**](#visitor-consent)       |
| decision\_group        | string  | no       | empty   | If specified, users that match the targeting will be affected to a unique variation ID per decision group. [**See description**](#decision-group)                                                                          |
| format\_response       | bool    | no       | false   | If set to true, the response of the API call will be formatted according to your modification type. [**See formatted response**](#formatted-campaign)                                                                      |
| default\_redirect\_url | string  | no       | empty   | If specified, the API call will always return a 302 redirect, with the modification redirection if defined, or the `default_redirect_url` if not defined                                                                   |

{% hint style="info" %}
📘

The `visitor_id` should be a unique identifier for your application user or website visitor. Using a consistent `visitor_id` is what guarantees that a visitor will see the same variation of a campaign across sessions and clients.

[**See Experience Continuity**](#experience-continuity) to provide consistency between the anonymous & logged in state of your visitor.
{% endhint %}

**Response Parameters**

This API endpoint returns a Campaign response JSON object. [**See campaign response model**](#campaign)

#### Flags

This endpoint has the same behavior of `/campaigns` (See [**campaign body parameters**](#run-all-campaign-assignments)) endpoint but the response format is different.\
After processing the request, the API returns \*\*the list of flags \*\*with values, campaign, and variation associated.

```shell
curl -X POST \
  https://decision.flagship.io/v2/<ENVIRONMENT_ID>/flags \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
        "visitor_id": "YOUR_VISITOR_ID",
        "context": {
            "YOUR KEY": "YOUR VALUE"
        },
        "decision_group": null
    }'
```

```javascript
const response = await axios.post(
  "https://decision.flagship.io/v2/<ENVIRONMENT_ID>/flags",
  {
    visitor_id: "YOUR_VISITOR_ID",
    context: {
      "YOUR KEY": "YOUR VALUE",
    },
    visitor_consent: true,
    decision_group: null,
  },
  {
    headers: { "x-api-key": "YOUR_API_KEY" },
  }
);
```

The above command returns JSON structured as follows:

```json
{
    "<FLAG_KEY>": {
        "value": "<FLAG_VALUE>",
        "metadata": {
            "campaignId": "<CAMPAIGN_ID>",
          	"campaignName":"<CAMPAIGN_NAME>",
            "slug": null,
            "type": "ab",
            "variationGroupId": "<VARIATION_GROUP_ID>",
          	"variationGroupName":"<VARIATION_GROUP_NAME>",
            "variationId": "<VARIATION_ID>",
          	"variationName":"<VARIATION_NAME>",
            "reference": false
        }
    },
}
```

**HTTP Request**

```
POST https://decision.flagship.io/v2/<ENVIRONMENT_ID>/flags
```

**Route Parameters**

| Parameter       | Required | Default | Description                                                                                                                                                                                                    |
| --------------- | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ENVIRONMENT\_ID | yes      |         | Identifies your account and environment (preprod or prod). Check your Flagship dashboard to [**find this ID**](https://github.com/flagship-io/Gitbook/blob/main/docs/getting-started-with-flagship/README.md). |

**Query Parameters**

| Parameter     | Required | Default | Description                                                                                                        |
| ------------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------ |
| exposeAllKeys | no       | true    | If this parameter is set to true, all flag keys (even flag keys with null values will be returned in the response) |

**Body Parameters**

Body parameters are the same than the `/campaigns` endpoint. See [**campaign body parameters**](#run-all-campaign-assignments).

**Response Parameters**

This API endpoint returns an associative array of flag response JSON object. The key of this array is the flag key. See [**flag**](#flag).

### Campaign activation

This endpoint assigns a user to a variation. It should be used to manually activate a single campaign and variation\
in cases where you choose not to activate them automatically when running campaign assignment. [**See trigger\_hit parameter**](#trigger-hit)

**Example:**

You create a campaign targeting visitors who are on the cart checkout screen of your mobile app.\
At the initialization of your app, you want to get all campaigns and modifications associated with a user.

Since they are not on the basket screen yet, you don't want to assign the user to a variation at this stage. Instead, you would call this endpoint to assign the user to a variation only once they actually belong to the campaign.

```javascript
const response = await axios.post("https://decision.flagship.io/v2/activate", {
  vid: "<YOUR_VISITOR_ID>",
  cid: "<ENVIRONMENT_ID>",
  caid: "<VARIATION_GROUP_ID>",
  vaid: "<VARIATION_ID>",
});
```

```shell
curl -X POST \
  "https://decision.flagship.io/v2/activate" \
  -H 'Content-Type: application/json' \
  -d '{
        "vid": "<YOUR_VISITOR_ID>",
        "cid": "<ENVIRONMENT_ID>",
        "caid": "<VARIATION_GROUP_ID>",
        "vaid": "<VARIATION_ID>"
    }'
```

The above request returns a `204: No Content` HTTP response.

#### HTTP Request

```
POST https://decision.flagship.io/v2/activate
```

#### Body Parameters

| Parameter | Type   | Required | Default | Description                                                                                                                                                                                                                |
| --------- | ------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| vid       | string | yes      | empty   | Unique identifier for the application user or website visitor. This can be an ID from your database or a session ID. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#visitor-id) |
| cid       | string | yes      | empty   | Identifies your account and environment (preprod or prod). Check your Flagship dashboard to [**find this ID**](https://github.com/flagship-io/Gitbook/blob/main/docs/getting-started-with-flagship/README.md).             |
| caid      | string | yes      | empty   | Corresponds to the `variationGroupID` returned by the Decision API. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#variation-group-id)                                          |
| vaid      | string | yes      | empty   | The variation ID of which the user will be affected to. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#variation-id)                                                            |

#### Multiple campaigns activations

It is possible to send multiple campaigns activation in a single http call following this batch format:

```javascript
const response = await axios.post("https://decision.flagship.io/v2/activate", {
  cid: "<ENVIRONMENT_ID>",
  batch: [{
      vid: "<YOUR_VISITOR_ID>",
      caid: "<VARIATION_GROUP_ID>",
      vaid: "<VARIATION_ID>"
    },
    {
      vid: "<YOUR_VISITOR_ID>",
      caid: "<VARIATION_GROUP_ID>",
      vaid: "<VARIATION_ID>",
      qt: 2134
    }
  ]
});
```

| Parameter | Type   | Required | Default | Description                                                                                                                                                                                                    |
| --------- | ------ | -------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| cid       | string | yes      | empty   | Identifies your account and environment (preprod or prod). Check your Flagship dashboard to [**find this ID**](https://github.com/flagship-io/Gitbook/blob/main/docs/getting-started-with-flagship/README.md). |
| batch     | array  | yes      | empty   | Corresponds to the list of campaign to activate.                                                                                                                                                               |

| Parameter | Type    | Required | Default | Description                                                                                                                                                                                                                                                                                 |
| --------- | ------- | -------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| vid       | string  | yes      | empty   | Unique identifier for the application user or website visitor. This can be an ID from your database or a session ID. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#visitor-id)                                                                  |
| caid      | string  | yes      | empty   | Corresponds to the `variationGroupID` returned by the Decision API. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#variation-group-id)                                                                                                           |
| vaid      | string  | yes      | empty   | The variation ID of which the user will be affected to. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#variation-id)                                                                                                                             |
| qt        | integer | no       | 0       | Used to collect offline / latent hits. The value represents the time delta (in milliseconds) between when the hit being reported occurred and the time the hit was sent. The value must be greater than or equal to 0. Values greater than four hours may lead to hits not being processed. |

### Request parameters

#### Visitor Consent

The `visitor_consent` parameter handle if the visitor has accepted or not the GDPR rules.\
If not, all context key-value pairs in the request won't be saved sent in the collect.\
You **must** set this parameter false to be GDPR compliant when your visitor has not validated your rules.\
If not set, the default value is `true`.

#### Decision Group

The `decision_group` requests parameter enables your app to force the same variation assignment for a specific group of visitors.

Example:

* You call the Decision API for a user with `visitor_id=1`, `campaign_id=1`, and `decision_group=VIP_users`. The assigned `variationId` will be selected randomly depending on the chosen [traffic allocation](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#traffic-allocation)) (e.g. `variationId=1234`).
* You call the Decision API for a second user with`visitor_id=2`, `campaign_id=1`, and the same `decision_group=VIP_users`. Because this user belongs to the same `decision_group` as the first, the API will assign them to the same `variationId=1234` instead of a new random variation.

{% hint style="info" %}
📘 Decision Group and variation assignation

A visitor changing from a decision group to another could see his variation assignation changing.

\*\*Ex: \*\*You manage the decision group to be an account\_id. Your visitors have access to several accounts. Changing from an account to another will not display the same level of feature/variations to your end-users as the account might not have the same configuration.
{% endhint %}

#### Trigger Hit

The `trigger_hit` parameter enables your code to automatically trigger the [Universal Collect `CAMPAIGN` hit](https://github.com/flagship-io/Gitbook/blob/main/docs/universal-collect-documentation/README.md#campaign-activation) so that our reporting systems know that the visitor has seen the campaign.

{% hint style="warning" %}
🚧

The `trigger_hit` parameter is set to `true` by default unless you manually set it to `false`.
{% endhint %}

#### Mode

The `mode` query parameter allows you to change to format of the response in which the Decision API returns the campaign information:

**Normal**

`mode=normal` returns the `visitorId` and `campaigns` array with the full campaign information.

For `mode=normal`, the response body will have the following format:

```json
{
  "visitorId": "YOUR_VISITOR_ID",
  "campaigns": [
    {
      "id": "<CAMPAIGN_ID>",
      "variationGroupId": "<VARIATION_GROUP_ID>",
      "variation": {
        "id": "<VARIATION_ID>",
        "modifications": {
          "type": "JSON",
          "value": {
            "key": "value"
          }
        }
      }
    }
  ]
}
```

**Simple**

* `mode=simple` returns two elements:
  * a `campaignsVariation` array of campaignId and associated `variationId` for the visitor
  * a `mergedModifications` object containing all the remote values configured for the campaigns, merged into a single object

For `mode=simple`, the response body will have the following format:

```json
{
  "campaignsVariation": [
    {
      "campaignId": "bk6d4m8r1p60038pr0t0",
      "variationId": "bk6d5dgr1p60071psgb0"
    },
    {
      "campaignId": "bkk5da8cmjcg07ee3sb0",
      "variationId": "bkk5da8cmjcg07ee3scg"
    }
  ],
  "mergedModifications": {
    "Test": true,
    "btn-color": "red",
    "my_text": "Welcome dude",
    "youpitext": "Hello"
  }
}
```

**Full**

* `mode=full` returns all the elements for debugging purposes:
  * the `visitorId`
  * the `campaigns` array containing all the campaign information for this visitor
  * a `campaignsVariation` array of all `campaignId` and associated `variationId` values for the visitor
  * a `mergedModifications` object containing all the remote values configured for the campaigns, merged into a single object

For `mode=full`, the response body will have the following format:

```json
{
  "visitorId": "visitor1234",
  "campaigns": [
    {
      "id": "bk6d4m8r1p60038pr0t0",
      "variationGroupId": "bk6d4m8r1p60038pr0u0",
      "variation": {
        "id": "bk6d5dgr1p60071psgb0",
        "modifications": {
          "type": "JSON",
          "value": {
            "btn-color": "red"
          }
        }
      }
    },
    {
      "id": "bkk5da8cmjcg07ee3sb0",
      "variationGroupId": "bkk5da8cmjcg07ee3sc0",
      "variation": {
        "id": "bkk5da8cmjcg07ee3scg",
        "modifications": {
          "type": "TEXT",
          "value": {
            "youpitext": "Hello AB Tasty!"
          }
        }
      }
    }
  ],
  "campaignsVariation": [
    {
      "campaignId": "bk6d4m8r1p60038pr0t0",
      "variationId": "bk6d5dgr1p60071psgb0"
    },
    {
      "campaignId": "bkk5da8cmjcg07ee3sb0",
      "variationId": "bkk5da8cmjcg07ee3scg"
    }
  ],
  "mergedModifications": {
    "Test": true,
    "btn-color": "red",
    "my_text": "Welcome, dude",
    "youpitext": "Hello"
  }
}
```

### Response models

#### Campaign

| Field name                    | type   | Description                                                                                                                                                                                                                |
| ----------------------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| visitorId                     | string | Unique identifier for the application user or website visitor. This can be an ID from your database or a session ID. [**Learn more**](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#visitor-id) |
| variationGroupId              | string | Corresponds to a [scenario](https://github.com/flagship-io/Gitbook/blob/main/docs/glossary/README.md#scenario) in the Flagship dashboard)                                                                                  |
| variation                     | object | The assigned variation information                                                                                                                                                                                         |
| variation.id                  | string | The affected variation ID                                                                                                                                                                                                  |
| variation.modifications       | object | The variation modifications information                                                                                                                                                                                    |
| variation.modifications.type  | string | The modification type for the campaign (can be NULL, JSON, TEXT, IMAGE, HTML, FLAG, REDIRECT)                                                                                                                              |
| variation.modifications.value | object | The value of the modification                                                                                                                                                                                              |

{% hint style="info" %}
📘

The `variation.modifications.value` field can have the following structure, depending on the modification type:

* **type = 'JSON'**: value is a key-value pair of the JSON modification defined in the platform for the campaign
* **type = 'TEXT'**: value is an object with the structure `{key:'text_key', value:'text_value'}`
* **type = 'IMAGE'**: value is an object with the structure `{key:'image_key', value:'image_value'}`
* **type = 'HTML'**: value is an object with the structure `{key:'html_key', value:'html_value'}`
* **type = 'REDIRECT'**: value is an object with the structure `{key:'redirect_key', value:'redirect_value'}`
* **type = 'FLAG'**: value is an object with the structure `{'flag_name': 'flag_value'}`
  {% endhint %}

#### Campaign Variation

| Field name  | type   | Description                           |
| ----------- | ------ | ------------------------------------- |
| campaignId  | string | Identifies the campaign               |
| variationId | string | The variation ID assigned to the user |

#### Formatted campaign

If you set the `format_response` parameter to true in the campaign request, the Decision API will attempt to return HTTP-formatted content for your campaign modifications.

The formatted content depends on the campaign modification type configured in the Flagship dashboard:

| Modification type | Content-Type     | Status Code | HTTP response body                                              |
| ----------------- | ---------------- | ----------- | --------------------------------------------------------------- |
| JSON              | application/JSON | 200         | The JSON object defined for the campaign                        |
| TEXT              | text/plain       | 200         | The text defined for the campaign                               |
| HTML              | text/HTML        | 200         | The HTML defined the campaign                                   |
| IMAGE             | image            | 200         | The content of the image URL defined for the campaign           |
| REDIRECT          | application/JSON | 302         | The key/value JSON object of the flags defined for the campaign |
| FLAG              | application/JSON | 200         | The key/value JSON object of the flags defined for the campaign |

#### Flag

| Field name                  | type   | Description                                                                    |
| --------------------------- | ------ | ------------------------------------------------------------------------------ |
| value                       | object | Value of the flag, it can be an object, a string, an integer, or a boolean.    |
| metadata                    | object | Metadata of the flag                                                           |
| metadata.campaignId         | string | ID of the campaign associated with this flag                                   |
| metadata.campaignName       | string | Name of the campaign                                                           |
| metadata.slug               | string | Slug of the campaign (if configured in the platform)                           |
| metadata.type               | string | Type of the campaign                                                           |
| metadata.variationGroupId   | string | ID of the variation group associated with this flag                            |
| metadata.variationGroupName | string | Name of the variation group                                                    |
| metadata.variationId        | string | ID of the variation associated with this flag                                  |
| metadata.variationName      | string | Name of the variation                                                          |
| metadata.reference          | string | Indicated if the variation associated is a reference variation of the campaign |

### Experience Continuity

In some situations, you may want experience consistency between an anonymous visitor and an authenticated visitor.

Flagship provides a specific body parameter to specify the anonymous ID and differentiate it from the authenticated ID.

#### Anonymous visitor

When your visitor is considered anonymous (their ID is of type session ID), you can use the `visitor_id` field alone. The Decision API will see your visitor as anonymous.

Their experience will be **consistent as long as they remain anonymous**.

**Code sample**

```shell
curl -X POST \
  https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
        "visitor_id": "{session_id}",
        "context": {
            "YOUR KEY": "YOUR VALUE"
        },
        "visitor_consent": true,
        "decision_group": null
    }'
```

```javascript
fetch("https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns", {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
        'x-api-key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
        visitor_id: "{session_id}",
        context: {
            "YOUR KEY": "YOUR VALUE"
        },
        visitor_consent: true,
        decision_group: null
    })
})
    .then(response => response.json())
    .then(data => console.log(data));
```

```php
<?php

$postFields = [
    "visitor_id" => "{session_id}",
    "context" => [
        "YOUR KEY" => "YOUR VALUE"
    ],
    "visitor_consent" => true,
    "trigger_hit" => true,
    "decision_group" => null
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields, JSON_FORCE_OBJECT));

$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Api-Key: YOUR_API_KEY';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}

curl_close($ch);
```

```csharp
public class Class1
{
    async Task GetMyCampaignsAsync()
    {
        using HttpClient httpClient = new();

        var url = "https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns";
        var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);

        requestMessage.Headers.Add("x-api-key", "YOUR_API_KEY");
        requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var postData = new Dictionary<string, object>
        {
            ["visitorId"] = "{session_id}",
            ["context"] = new Dictionary<string, object> { ["YOUR KEY"] = "YOUR VALUE" },
            ["visitor_consent"] = true,
            ["decision_group"] = null
        };

        var postDatajson = JsonConvert.SerializeObject(postData);


        var stringContent = new StringContent(postDatajson, Encoding.UTF8, "application/json");

        requestMessage.Content = stringContent;

        var response = await httpClient.SendAsync(requestMessage);

    }
}
```

#### Authenticated visitor

Once your visitor has been authenticated and has an authenticated ID (Database ID, profile ID, ...), you call the Decision API again and change the `visitor_id` in the body from the session ID to the authenticated ID.

But in order for the experience to remain the same between anonymous and authenticated, you need to inform the Decision API about the previous anonymous ID of this user.

To do that, you need to fill the `anonymous_id` with the previous ID you had set on `visitor_id` body parameter. The API will internally link the 2 IDs & keep the experience the same.

**Code sample**

```shell
curl -X POST \
  https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns \
  -H 'Content-Type: application/json' \
  -H 'x-api-key: YOUR_API_KEY' \
  -d '{
        "visitor_id": "{new_authenticated_id}",
        "anonymous_id": "{session_id}",
        "context": {
            "YOUR KEY": "YOUR VALUE"
        },
        "visitor_consent": true,
        "decision_group": null
    }'
```

```javascript
fetch("https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns", {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
        'x-api-key': 'YOUR_API_KEY'
    },
    body: JSON.stringify({
        visitor_id: "{new_authenticated_id}",
        anonymous_id: "{session_id}",
        context: {
            "YOUR KEY": "YOUR VALUE"
        },
        visitor_consent: true,
        decision_group: null
    })
})
    .then(response => response.json())
    .then(data => console.log(data));
```

```php
<?php

$postFields = [
    "visitor_id" => "{new_authenticated_id}",
    "anonymous_id" => "{session_id}",
    "context" => [
        "YOUR KEY" => "YOUR VALUE"
    ],
    "visitor_consent" => true,
    "trigger_hit" => true,
    "decision_group" => null
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields, JSON_FORCE_OBJECT));

$headers = [];
$headers[] = 'Content-Type: application/json';
$headers[] = 'X-Api-Key: YOUR_API_KEY';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}

curl_close($ch);
```

```csharp
public class Class1
{
    async Task GetMyCampaignsAsync()
    {
        using HttpClient httpClient = new();

        var url = "https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns";
        var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);

        requestMessage.Headers.Add("x-api-key", "YOUR_API_KEY");
        requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var postData = new Dictionary<string, object>
        {
            ["visitorId"] = "{new_authenticated_id}",
            ["anonymous_id"] = "{session_id}",
            ["context"] = new Dictionary<string, object> { ["YOUR KEY"] = "YOUR VALUE" },
            ["visitor_consent"] = true,
            ["decision_group"] = null
        };

        var postDatajson = JsonConvert.SerializeObject(postData);


        var stringContent = new StringContent(postDatajson, Encoding.UTF8, "application/json");

        requestMessage.Content = stringContent;

        var response = await httpClient.SendAsync(requestMessage);

    }
}
```

#### Visitor activation

If you decide to set `trigger_hit` to false, which means that you want to delay the visitor activation, you need to send both IDs at the activation step.

**Code sample**

```shell
curl -X POST \
  "https://decision.flagship.io/v2/activate" \
  -H 'Content-Type: application/json' \
  -d '{
        "vid": "{new_authenticated_id}",
        "aid": "{session_id}",
        "cid": "<ENVIRONMENT_ID>",
        "caid": "<VARIATION_GROUP_ID>",
        "vaid": "<VARIATION_ID>"
    }'
```

```javascript
fetch("https://decision.flagship.io/v2/activate", {
    method: 'POST',
    headers: {
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        vid: "{new_authenticated_id}",
        aid: "{session_id}",
        cid: "<ENVIRONMENT_ID>",
        caid: "<VARIATION_GROUP_ID>",
        vaid: "<VARIATION_ID>"
    })
})
    .then(response => response.json())
    .then(data => console.log(data));
```

```php
<?php

$postFields = [
    "vid" => "{new_authenticated_id}",
    "aid" => "{session_id}",
    "cid" => "<ENVIRONMENT_ID>",
    "caid" => "<VARIATION_GROUP_ID>",
    "vaid" => "<VARIATION_ID>"
];

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://decision.flagship.io/v2/activate');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($postFields, JSON_FORCE_OBJECT));

$headers = [];
$headers[] = 'Content-Type: application/json';

curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}

curl_close($ch);
```

```csharp
public class Class1
{
    async Task GetMyCampaignsAsync()
    {
        using HttpClient httpClient = new();

        var url = "https://decision.flagship.io/v2/<ENVIRONMENT_ID>/campaigns";
        var requestMessage = new HttpRequestMessage(HttpMethod.Post, url);

        requestMessage.Headers.Add("x-api-key", "YOUR_API_KEY");
        requestMessage.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

        var postData = new Dictionary<string, object>
        {
            ["vid"] = "{new_authenticated_id}",
            ["aid"] = "{session_id}",
            ["cid"] = "<ENVIRONMENT_ID>",
            ["caid"] = "<VARIATION_GROUP_ID>",
            ["vaid"] = "<VARIATION_ID>"
        };

        var postDatajson = JsonConvert.SerializeObject(postData);


        var stringContent = new StringContent(postDatajson, Encoding.UTF8, "application/json");

        requestMessage.Content = stringContent;

        var response = await httpClient.SendAsync(requestMessage);

    }
}
```

#### Send hits to the data collect

Since you're using Experience Continuity with the Decision API only, check the chapter [about triggering event collection.](doc:universal-collect-documentation#experience-continuity)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.abtasty.com/server-side/decision-api/decision-api.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
