# Get recommendations by campaign

- Operation ID: `PostRecommendationsByCampaignV2`
- HTTP method: `POST`
- Path: `/recommendations/v2/recommend/campaigns`
- [Human-readable API reference](https://hub.synerise.com/api-reference/campaigns#operation/PostRecommendationsByCampaignV2)

## Self-contained OpenAPI method

The fenced document below contains this method's documentation and all of its local references. It is self-contained; no category or master specification fetch is required.

```yaml
openapi: 3.0.0
info:
  title: Synerise Public API
  version: 1.9.5
paths:
  /recommendations/v2/recommend/campaigns:
    post:
      summary: Get recommendations by campaign
      description: |
        This method allows you to retrieve recommendations based on a campaignID or slug and a context. The context is built based on:

        - campaign ID or slug (one of those is required)
        - profile UUID
        - items (for example, items currently in the basket)
        - item exclusions

        This is the recommended and simplest way to fetch recommendations.

        Before you use this method, you must to create a recommendations campaign in Synerise. All the recommendation filters and parameters will be handled for you automatically according to a campaign's configuration.


        ---

        **API consumers:** <span title="Deprecated">AI API key (legacy)</span>, <a href="/docs/settings/tool/tracking_codes" target="_blank" rel="noopener" title="Pass your tracker key in the request header">Web SDK Tracker</a>, <a href="/api-reference/authorization?tag=Authorization&amp;operationId=profileLogin" target="_blank" rel="noopener">Workspace (Business Profile)</a>

        **API key permission required:** `API_MATERIALIZER_V2_RECOMMEND_CAMPAIGNS_RECOMMENDATIONS_READ`
      operationId: PostRecommendationsByCampaignV2
      security:
        - TrackerKey: []
        - JWT: []
        - BasicAuth: []
      tags:
        - Recommendations
      requestBody:
        content:
          application/json:
            schema:
              allOf:
                - type: object
                  properties:
                    clientUUID:
                      type: string
                      description: |
                        Profile UUID. This parameter is required for these recommendation types:
                          - Personalized
                          - Last seen
                          - Recent interactions
                          - Section
                          - Attribute

                        This parameter can be passed in all recommendations. In recommendations which don't require the customer context, it can still be used to create filters.
                    campaignId:
                      type: string
                      description: Recommendation campaign ID for establishing the context
                    slug:
                      type: string
                      description: Recommendation campaign slug for establishing the context
                - type: object
                  properties:
                    items:
                      type: array
                      description: |
                        An array of item identifiers (`itemId` in the item feed) for the context. This could be, for example, the current basket, or the item that is currently being viewed.  

                        This overrides the `itemsSource` settings of the campaign definition.

                        This parameter can be passed in all recommendations. In recommendations which don't use the context item as part of the recommendation model, the context item can only be used to create filters.

                        Alternatively, you can use the `itemsSource` object to get item IDs from an aggregate or expression. `items` and `itemsSource` can't be used at the same time.
                      items:
                        type: string
                        description: "`itemId` from the item feed"
                    itemsSource:
                      type: object
                      description: |
                        Source of the Item ID or item IDs for the recommendation context.

                        This overrides the `itemsSource` settings of the campaign definition.

                        This parameter can be passed in all recommendations. In recommendations which don't use the context item as part of the recommendation model, the context item can only be used to create filters.

                        The item ID source (aggregate or expression) should return a string or an array of strings. If it returns numerical values, the recommendations engine attempts to convert them into strings while processing the request.

                        Alternatively, you can pass the `itemId` parameter to define context items directly. Only one of these options is allowed at the same time.
                      properties:
                        type:
                          type: string
                          enum:
                            - aggregate
                            - expression
                          description: Type of the items' source.
                        id:
                          type: string
                          description: ID of the items' source (aggregate or expression)
                    itemsExcluded:
                      type: array
                      minItems: 0
                      description: Items (identified by `itemId` in the item feed) that will be excluded from the generated recommendations. For example, items already added to the basket.
                      items:
                        type: string
                        description: Items (identified by `itemId` in the item feed) that will be excluded from the generated recommendations. For example, items already added to the basket.
                    additionalFilters:
                      type: string
                      description: |
                        <hr>
                        <strong>IMPORTANT</strong>:

                        - The `filtersJoiner` attribute is REQUIRED when `additionalFilters` is included. If `filtersJoiner` is missing, the additional filters do not work.  
                        - Do NOT send multiple instances of this parameter.

                        <hr>

                        Additional filters. These are merged with the campaign's own filters according to the logic in `filtersJoiner`.

                        This parameter must include all the additional filters as a single string, for example `additionalFilters=effectivePrice>300 AND effectivePrice<400` (the spaces are required).
                      example: effectivePrice>300 AND effectivePrice<400
                    filtersJoiner:
                      type: string
                      enum:
                        - AND
                        - OR
                        - REPLACE
                      description: |
                        Defines the logic of merging `additionalFilters` with the campaign's existing filters.
                        - `REPLACE` replaces the campaign's filters with your filters.
                        - `AND` matches if both your filters and the campaign filters are met.
                        - `OR` matches if at least one of the filters is met.
                    additionalElasticFilters:
                      type: string
                      description: |
                        <hr>
                        <strong>IMPORTANT</strong>:

                        - The `elasticFiltersJoiner` attribute is REQUIRED when `additionalElasticFilters` is included. If `elasticFiltersJoiner` is missing, the additional filters do not work.  
                        - Do NOT send multiple instances of this parameter.

                        <hr>

                        Additional elastic filters. These are merged with the campaign's own elastic filters according to the logic in `elasticFiltersJoiner`.

                        This parameter must include all the additional filters as a single string, for example `additionalElasticFilters=effectivePrice>300 AND effectivePrice<400` (the spaces are required).
                      example: effectivePrice>300 AND effectivePrice<400
                    elasticFiltersJoiner:
                      type: string
                      enum:
                        - AND
                        - OR
                        - REPLACE
                      description: |
                        Defines the logic of merging `additionalElasticFilters` with the campaign's existing elastic filters.
                        - `REPLACE` replaces the campaign's filters with your filters.
                        - `AND` matches if both your filters and the campaign filters are met.
                        - `OR` matches if at least one of the filters is met.
                    displayAttributes:
                      type: array
                      minItems: 0
                      items:
                        type: string
                      description: An array of item attributes which value will be returned in a recommendation response. The array will be merged together with the configuration of the recommendation.
                    includeContextItems:
                      type: boolean
                      description: When true, the recommendation response will include context items metadata.
                    recommendedItemsFromExternalModel:
                      type: array
                      minItems: 0
                      items:
                        type: array
                        items:
                          type: string
                      description: |
                        Items provided by an external recommendation model to be returned as recommendation results.

                        This parameter is used with campaigns of type "external-items".
                    inventoryContext:
                      description: |
                        Inventory context used to evaluate inventory-related filters and boosting strategies.
                        Can be either a single inventory context or
                        a multi-inventory context (set of channel IDs per inventory).
                      oneOf:
                        - type: object
                          description: |
                            Single inventory context.
                          properties:
                            channelIds:
                              type: array
                              items:
                                type: string
                              description: |
                                List of channel identifiers used to evaluate inventory-related filters and boosting strategies.
                          required:
                            - channelIds
                        - type: object
                          description: |
                            Multi-inventory context where each inventory can have its own set of channel IDs.
                          properties:
                            inventoryCatalogs:
                              type: object
                              additionalProperties:
                                type: object
                                description: |
                                  Context definition for a specific inventory.
                                properties:
                                  channelIds:
                                    type: array
                                    items:
                                      type: string
                                    description: |
                                      List of channel identifiers for this specific inventory.
                              description: |
                                Map of inventory ID to inventory context definition. Each inventory can have its own set of channel IDs.
                          required:
                            - inventoryCatalogs
                    params:
                      type: object
                      example:
                        source: mobile
                      description: Extra parameters that will be added to the `recommendation.generated` event. The total size must not exceed 500 bytes.
                      additionalProperties: true
      responses:
        "200":
          description: Recommendations for the provided context. The response schema depends on your Workspace configuration. The schema below only includes the static elements.
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    type: array
                    description: Recommended items
                    items:
                      type: object
                      properties:
                        itemId:
                          type: string
                          description: Item identifier
                      required:
                        - itemId
                  extras:
                    type: object
                    description: Additional data
                    properties:
                      correlationId:
                        type: string
                        description: Correlation identifier of a recommendation request
                      contextItems:
                        type: array
                        description: A list of context items provided in request
                        items:
                          type: object
                          properties:
                            itemId:
                              type: string
                              description: Item identifier (`itemId` in item catalog)
                          additionalProperties: {}
                          required:
                            - itemId
                      slots:
                        type: array
                        description: A list of slots data
                        items:
                          type: object
                          properties:
                            id:
                              type: integer
                              description: Slot identifier. Matches the index (zero-based numbering) of the slot provided in request
                            name:
                              type: string
                              description: Slot name provided in request
                            itemIds:
                              type: array
                              description: A list of item ids that meet the slot criteria
                              items:
                                type: string
                                description: Item identifier (`itemId` in item catalog)
                            error:
                              type: object
                              description: Error details, if applicable
                              properties:
                                status:
                                  type: integer
                                  description: Status code
                                error:
                                  type: string
                                  description: Summary of the error
                                message:
                                  type: string
                                  description: Description of the problem
                              required:
                                - status
                                - error
                                - message
                          required:
                            - id
                            - itemIds
                    required:
                      - correlationId
                      - slots
        "404":
          description: No recommendations could be generated for the specified campaign and context.
          content:
            application/json:
              schema:
                type: object
                properties:
                  timestamp:
                    type: string
                    format: date-time
                    description: Time when the error occurred
                  status:
                    type: integer
                    description: Status code
                  error:
                    type: string
                    description: Summary of the error
                  message:
                    type: string
                    description: Description of the problem
                  path:
                    type: string
                    description: URL of the requested resource
                required:
                  - timestamp
                  - status
                  - message
        "500":
          description: An error occurred
          content:
            application/json:
              schema:
                type: object
                properties:
                  timestamp:
                    type: string
                    format: date-time
                    description: Time when the error occurred
                  status:
                    type: integer
                    description: Status code
                  error:
                    type: string
                    description: Summary of the error
                  message:
                    type: string
                    description: Description of the problem
                  path:
                    type: string
                    description: URL of the requested resource
                required:
                  - timestamp
                  - status
                  - message
      x-snr-doc-urls:
        - /api-reference/ai-recommendations#tag/Recommendations/operation/PostRecommendationsByCampaignV2
      x-codeSamples:
        - lang: cURL
          label: cURL
          source: |-
            curl --request POST \
              --url https://api.synerise.com/recommendations/v2/recommend/campaigns \
              --header 'Authorization: Basic REPLACE_BASIC_AUTH' \
              --header 'content-type: application/json' \
              --data '{"clientUUID":"string","campaignId":"string","slug":"string","items":["string"],"itemsSource":{"type":"aggregate","id":"string"},"itemsExcluded":["string"],"additionalFilters":"effectivePrice>300 AND effectivePrice<400","filtersJoiner":"AND","additionalElasticFilters":"effectivePrice>300 AND effectivePrice<400","elasticFiltersJoiner":"AND","displayAttributes":["string"],"includeContextItems":true,"recommendedItemsFromExternalModel":[["string"]],"inventoryContext":{"channelIds":["string"]},"params":{"source":"mobile"}}'
        - lang: Python
          label: Python
          source: |-
            import http.client

            conn = http.client.HTTPSConnection("api.synerise.com")

            payload = "{\"clientUUID\":\"string\",\"campaignId\":\"string\",\"slug\":\"string\",\"items\":[\"string\"],\"itemsSource\":{\"type\":\"aggregate\",\"id\":\"string\"},\"itemsExcluded\":[\"string\"],\"additionalFilters\":\"effectivePrice>300 AND effectivePrice<400\",\"filtersJoiner\":\"AND\",\"additionalElasticFilters\":\"effectivePrice>300 AND effectivePrice<400\",\"elasticFiltersJoiner\":\"AND\",\"displayAttributes\":[\"string\"],\"includeContextItems\":true,\"recommendedItemsFromExternalModel\":[[\"string\"]],\"inventoryContext\":{\"channelIds\":[\"string\"]},\"params\":{\"source\":\"mobile\"}}"

            headers = {
                'Authorization': "Basic REPLACE_BASIC_AUTH",
                'content-type': "application/json"
                }

            conn.request("POST", "/recommendations/v2/recommend/campaigns", payload, headers)

            res = conn.getresponse()
            data = res.read()

            print(data.decode("utf-8"))
        - lang: JavaScript
          label: JavaScript
          source: |-
            const data = JSON.stringify({
              "clientUUID": "string",
              "campaignId": "string",
              "slug": "string",
              "items": [
                "string"
              ],
              "itemsSource": {
                "type": "aggregate",
                "id": "string"
              },
              "itemsExcluded": [
                "string"
              ],
              "additionalFilters": "effectivePrice>300 AND effectivePrice<400",
              "filtersJoiner": "AND",
              "additionalElasticFilters": "effectivePrice>300 AND effectivePrice<400",
              "elasticFiltersJoiner": "AND",
              "displayAttributes": [
                "string"
              ],
              "includeContextItems": true,
              "recommendedItemsFromExternalModel": [
                [
                  "string"
                ]
              ],
              "inventoryContext": {
                "channelIds": [
                  "string"
                ]
              },
              "params": {
                "source": "mobile"
              }
            });

            const xhr = new XMLHttpRequest();
            xhr.withCredentials = true;

            xhr.addEventListener("readystatechange", function () {
              if (this.readyState === this.DONE) {
                console.log(this.responseText);
              }
            });

            xhr.open("POST", "https://api.synerise.com/recommendations/v2/recommend/campaigns");
            xhr.setRequestHeader("Authorization", "Basic REPLACE_BASIC_AUTH");
            xhr.setRequestHeader("content-type", "application/json");

            xhr.send(data);
        - lang: Node.js
          label: Node.js
          source: |-
            const http = require("https");

            const options = {
              "method": "POST",
              "hostname": "api.synerise.com",
              "port": null,
              "path": "/recommendations/v2/recommend/campaigns",
              "headers": {
                "Authorization": "Basic REPLACE_BASIC_AUTH",
                "content-type": "application/json"
              }
            };

            const req = http.request(options, function (res) {
              const chunks = [];

              res.on("data", function (chunk) {
                chunks.push(chunk);
              });

              res.on("end", function () {
                const body = Buffer.concat(chunks);
                console.log(body.toString());
              });
            });

            req.write(JSON.stringify({
              clientUUID: 'string',
              campaignId: 'string',
              slug: 'string',
              items: ['string'],
              itemsSource: {type: 'aggregate', id: 'string'},
              itemsExcluded: ['string'],
              additionalFilters: 'effectivePrice>300 AND effectivePrice<400',
              filtersJoiner: 'AND',
              additionalElasticFilters: 'effectivePrice>300 AND effectivePrice<400',
              elasticFiltersJoiner: 'AND',
              displayAttributes: ['string'],
              includeContextItems: true,
              recommendedItemsFromExternalModel: [['string']],
              inventoryContext: {channelIds: ['string']},
              params: {source: 'mobile'}
            }));
            req.end();
        - lang: PHP
          label: PHP
          source: |-
            <?php

            $request = new HttpRequest();
            $request->setUrl('https://api.synerise.com/recommendations/v2/recommend/campaigns');
            $request->setMethod(HTTP_METH_POST);

            $request->setHeaders([
              'Authorization' => 'Basic REPLACE_BASIC_AUTH',
              'content-type' => 'application/json'
            ]);

            $request->setBody('{"clientUUID":"string","campaignId":"string","slug":"string","items":["string"],"itemsSource":{"type":"aggregate","id":"string"},"itemsExcluded":["string"],"additionalFilters":"effectivePrice>300 AND effectivePrice<400","filtersJoiner":"AND","additionalElasticFilters":"effectivePrice>300 AND effectivePrice<400","elasticFiltersJoiner":"AND","displayAttributes":["string"],"includeContextItems":true,"recommendedItemsFromExternalModel":[["string"]],"inventoryContext":{"channelIds":["string"]},"params":{"source":"mobile"}}');

            try {
              $response = $request->send();

              echo $response->getBody();
            } catch (HttpException $ex) {
              echo $ex;
            }
        - lang: Java
          label: Java
          source: |-
            HttpResponse<String> response = Unirest.post("https://api.synerise.com/recommendations/v2/recommend/campaigns")
              .header("Authorization", "Basic REPLACE_BASIC_AUTH")
              .header("content-type", "application/json")
              .body("{\"clientUUID\":\"string\",\"campaignId\":\"string\",\"slug\":\"string\",\"items\":[\"string\"],\"itemsSource\":{\"type\":\"aggregate\",\"id\":\"string\"},\"itemsExcluded\":[\"string\"],\"additionalFilters\":\"effectivePrice>300 AND effectivePrice<400\",\"filtersJoiner\":\"AND\",\"additionalElasticFilters\":\"effectivePrice>300 AND effectivePrice<400\",\"elasticFiltersJoiner\":\"AND\",\"displayAttributes\":[\"string\"],\"includeContextItems\":true,\"recommendedItemsFromExternalModel\":[[\"string\"]],\"inventoryContext\":{\"channelIds\":[\"string\"]},\"params\":{\"source\":\"mobile\"}}")
              .asString();
servers:
  - url: https://api.synerise.com
    description: Microsoft Azure EU
  - url: https://api.azu.synerise.com
    description: Microsoft Azure USA
  - url: https://api.geb.synerise.com
    description: Google Cloud Platform
tags:
  - name: Recommendations
components:
  securitySchemes:
    TrackerKey:
      type: apiKey
      in: query
      name: token
      description: |
        Authentication by tracker key sent in a `token` query parameter. This can be the same key as used in the tracking code of the website. For details, see:

        - [Creating tracking codes](https://hub.synerise.com/developers/web/installation-and-configuration/#creating-a-tracking-code)
        - [Authenticating API requests with the tracker key](https://hub.synerise.com/developers/api/api-authorization/client-login/#tracker-key-authentication)
    JWT:
      type: http
      scheme: bearer
      description: |
        Synerise uses [JSON Web Token (JWT)](https://jwt.io/) as the authorization method.

        The token is generated by the *auth/login* endpoints.

        You need to include it in the `Authorization` header of your requests, with a `Bearer` prefix.


        By default, the token is valid for **one week** (see [workspace settings](https://hub.synerise.com/docs/settings/tool/iam-for-apps/general/#jwt-lifetime)).  
        You can request a refreshed key for the session by using the *auth/refresh* endpoint **before** the current token expires.


        You can verify your JWT signature by using the [public key](https://api.synerise.com/v4/public.pem).


        See Developer Guides on JWT API authentication for:
        - [profiles](https://hub.synerise.com/developers/api/api-authorization/client-login/);
        - [workspaces](https://hub.synerise.com/developers/api/api-authorization/workspace-login/#api-authentication-with-jwt);
        - [users](https://hub.synerise.com/developers/api/api-authorization/user-login/).
    BasicAuth:
      type: http
      scheme: basic
      description: |
        Basic authentication with login (workspace GUID) and password (workspace API key) encoded with Base64 and sent in the `Authorization` header. **Must be enabled in the settings of the API key**.

        <span style="color:red">This is less secure than JWTs.</span> Limit the API key permissions to only those that you need. Consider API key rotation and other security measures.

        You can still use JWTs from the same API key when basic authentication is enabled.

        For details, see ["Workspace authentication"](https://hub.synerise.com/jwt-or-basic/#basic-api-authentication-with-api-keys).
```
