🎉 Try the public beta of the new docs site at algolia.com/doc-beta! 🎉
API reference / Recommend API

This page documents the Algolia Recommend REST API. However, it’s strongly recommend to use Algolia’s official API clients, libraries, and integrations to build your recommendations implementation.

Algolia has developed API clients and libraries for interacting with Algolia recommend. These advanced wrappers handle errors, and enforce the best search practices and optimal use of Algolia Recommend. Everything you can do with the REST API can be done using the API clients and libraries. They’re all open source, and the code is available on GitHub.

You should only use the Recommend REST API to develop new API clients. There’s no SLA if you use the REST API directly.

API clients

PHP
JavaScript
Python
CSharp
Java
Scala
Kotlin

Frontend libraries

JavaScript

Hosts

The REST API lets your interact directly with Algolia from anything that can send an HTTP request. All API access must use HTTPS.

The primary host is {Application-ID}-dsn.algolia.net. The *-dsn host guarantees high availability through automatic load balancing and also leverages Algolia’s Distributed Search Network (if you subscribed that option).

In order to guarantee a very high availability, it’s recommended to implement a retry strategy for all API calls on the following fallback hosts: {Application-ID}-1.algolianet.com, {Application-ID}-2.algolianet.com, {Application-ID}-3.algolianet.com. (Note that the domain is different because it’s hosted on another DNS provider, for better redundancy.) It’s best to shuffle (randomize) the list of fallback hosts at init time to ensure load balancing across clients. All API clients implement this retry strategy.

The Application-ID variable can be found in your dashboard.

Format

The entire API uses JSON encoded in UTF-8.

The body of POST and PUT requests must be a JSON object and their Content-Type header should be set to application/json; charset=UTF-8.

The body of responses is always a JSON object, and their content type is always application/json; charset=UTF-8.

Parameters

Unless otherwise stated, you must pass parameters:

  • in the URL’s query string for GET and DELETE requests
  • in the request’s body for PUT and POST requests

You must URL-encode parameters passed in the URL using the UTF-8 encoding for non-ASCII characters. The plus character (+) is interpreted as a space, so it’s an alternative to %20.

Authentication

To authenticate, you need to pass the following HTTP headers:

  • X-Algolia-Application-Id identifies which Algolia application you’re accessing
  • X-Algolia-API-Key authenticates endpoint access

The X-Algolia-API-Key needs to have the search ACL.

For JavaScript usage, Algolia supports Cross-Origin Resource Sharing (CORS), so that you can use these headers in conjunction with XMLHttpRequest.

Error handling

The HTTP status code indicates whether a request succeeded or failed. A 2xx status code indicates success, whereas a 4xx status code indicates failure.

When a request fails, the response body is still JSON with contains a message field containing a description of the error, which you can inspect for debugging. For example, trying to retrieve recommendations with an invalid API key returns the message:

1
2
3
{
  "message": "Invalid Application-Id or API-Key"
}

Endpoints

Quick reference

Verb Path Method

POST

/1/indexes/*/recommendations

Get Recommendations

POST

/1/indexes/{indexName}/{model}/recommend/rules/batch

Batch Recommend Rules

GET

/1/indexes/{indexName}/{model}/recommend/rules/{objectID}

Get Recommend Rule

DELETE

/1/indexes/{indexName}/{model}/recommend/rules/{objectID}

Delete Recommend Rule

POST

/1/indexes/{indexName}/{model}/recommend/rules/search

Search Recommend Rules

GET

/1/indexes/{indexName}/{model}/task/{taskID}

Get a Recommend task's status

Get Recommendations

A

Path: /1/indexes/*/recommendations
HTTP Verb: POST
Required API Key: any key with the search ACL

Description:

Returns recommendations for a specific model.

Parameters:

Parameter Description
requests
type: array
Required

A list of recommendation requests to execute.

requests âž” request object

A single recommendation request. The body schema depends on the targeted model. The following parameters are common to all models.

Parameter Description
indexName
type: string
Required

Name of the index to target.

model
type: string
Required

The recommendation model to use, one of:

  • related-products
  • bought-together
  • trending-items
  • trending-facets
threshold
type: number
Required

Any recommendation with a score strictly lower than threshold doesn’t appear in the results. The value must be between 0 and 100.

maxRecommendations
type: number
default: 0
Optional

The number of recommendations to retrieve. Depending on the available recommendations and the other request parameters, the actual number of hits may be lower than that. If maxRecommendations isn’t provided or set to 0, all matching recommendations are returned, and no fallback request is performed.

{
  indexName: "an index name",
  model: "bought-together",
  threshold: 0,
  maxRecommendations: 10,
  objectID: "an objectID",
  queryParameters: { query parameters },
  fallbackParameters: { query parameters }
}

Fetch recommendations of a specific item. The following parameters are specific to models ‘related-products’ and ‘bought-together’.

Parameter Description
objectID
type: string
Required

The objectID to get recommendations for.

queryParameters
type: key-value mapping
Optional

A key-value mapping of search parameters to filter the recommendations.

fallbackParameters
type: key-value mapping
Optional

A key-value mapping of search parameters to use as fallback when there are no recommendations.

{
  indexName: "an index name",
  model: "trending-items",
  threshold: 0,
  maxRecommendations: 10,
  facetName: "a facet attribute name",
  facetValue: "a facet value",
  queryParameters: { query parameters },
  fallbackParameters: { query parameters }
}

Fetch trending items, either globally or only those matching a specific facet. The following parameters are specific to model ‘trending-items’. If no facet is provided, the query fetches globally trending items.

Parameter Description
facetName
type: string
Optional

The facet attribute to get recommendations for. This parameter must be used along with facetValue.

facetValue
type: string
Optional

The facet value to get recommendations for. This parameter must be used along with facetName.

queryParameters
type: key-value mapping
Optional

A key-value mapping of search parameters to filter the recommendations.

fallbackParameters
type: key-value mapping
Optional

A key-value mapping of search parameters to use as fallback when there are no recommendations.

{
  indexName: "an index name",
  model: "trending-facets",
  threshold: 0,
  maxRecommendations: 10,
  facetName: "a facet attribute name",
}

Fetch trending facet values given a specific facet attribute. The following parameters are specific to model ‘trending-facets’.

Parameter Description
facetName
type: string
Required

The facet attribute to get recommendations for.

Errors:

Example:

A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
curl -X POST https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/*/recommendations \
     -H 'Content-Type: application/json' \
     -H 'X-Algolia-Api-Key: ${API_KEY_WITH_SEARCH_ACL}' \
     -H 'X-Algolia-Application-ID: ${APPLICATION_ID}' \
     -d '{
       "requests": [
         {
           "indexName": "index1",
           "model": "related-products",
           "objectID": "objectID1",
           "threshold": 0
         }
       ]
     }'

Response:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
{
  "results": [
    {
      "hits": [
        {
          "objectID": "objectID1",
          "_score": 0.42
          // ...
        },
        {
          "objectID": "objectID2",
          "_score": 0.21
          // ...
        }
        //...
      ],
      "nbHits": 42
    }
    // ...
  ]
}

Batch Recommend Rules

A

Path: /1/indexes/{indexName}/{model}/recommend/rules/batch
HTTP Verb: POST
Required API Key: any key with the editSettings ACL

Description:

Create or update a batch of Recommend Rules.

Each Recommend Rule is created or updated, depending on whether a Recommend Rule with the same objectID already exists. You may also specify true for clearExistingRules, in which case the batch will atomically replace all the existing Recommend Rules.

Recommend Rules are similar to Search Rules, except that the conditions and consequences apply to a source item instead of a query. The main differences are the following:

  • Conditions pattern and anchoring are unavailable.
  • Condition filters triggers if the source item matches the specified filters.
  • Condition filters accepts numeric filters.
  • Consequence params only covers filtering parameters.
  • Consequence automaticFacetFilters doesn’t require a facet value placeholder (it tries to match the data source item’s attributes instead).

Parameters:

Parameter Description
indexName
type: string
Required

Index name

model
type: string
Required

Model name

clearExistingRules
type: boolean
default: false
Optional

Use as a URL query string, not in the body. When true, existing Rules are cleared before adding this batch. When false, existing Rules are kept.

Rules
type: list of rule
Optional

A list of rule objects.

[
  {
    objectID: objectID,
    condition: condition,
    consequence: consequence
  }
]

Rules âž” rule

Parameter Description
objectID
type: string
Required

Unique identifier for the Rule (format: [A-Za-z0-9_-]+).

condition
type: condition
Optional

Condition that should apply to activate a Rule. When the condition isn’t provided or is empty, the Rule is active for all requests to the relevant index and model.

{
  "context": context,
  "filters": filters
}
conditions
type: list of conditions
Optional

A list of conditions that should apply to activate a Rule. The Rule matches if at least one condition matches. You can use up to 10 conditions per Rule.

Filters can also be used as conditions.

[
  {
    "context": context,
    "filters": filters
  }
]
consequence
type: consequence
Required

Consequence of the Rule (this can’t be an empty value).

description
type: string
Optional

This field is intended for Rule management purposes, in particular to ease searching for Rules and presenting them to human readers. It’s not interpreted by the API.

enabled
type: boolean
default: true
Optional

Whether the Rule is enabled. Disabled Rules remain in the index but aren’t applied at query time.

validity
type: list of timeRange
Optional

By default, Rules are permanently valid. When validity periods are specified, the Rule applies only during those periods; it’s ignored the rest of the time. The list must not be empty.

Rules âž” rule âž” condition

Parameter Description
context
type: string
Optional

Rule context (format: [A-Za-z0-9_-]+). When specified, the Rule is only applied when the same context is specified at query time (using the ruleContexts parameter). When absent, the Rule is generic and always applies (provided that its other conditions are met).

filters
type: string
Optional

When specified, the Rule is only applied when the source item matches the filters. The syntax is a subset of filters. Filters for Recommend Rules don’t support negation (NOT) and filter scoring.

Rules âž” rule âž” consequence

Parameter Description
params
type: params
Optional

Additional search parameters. In Recommend Rules, only filters and parameters affecting the filters are allowed: numericFilters, tagFilters, facetFilters, filters, optionalTagFilters, optionalFacetFilters, optionalFilters, automaticFacetFilters, automaticOptionalFacetFilters, sumOrFiltersScores.

{
  "automaticFacetFilters": automaticFacetFilters,
  "automaticOptionalFacetFilters": automaticOptionalFacetFilters
}
promote
type: list
Optional

Objects to promote as hits. Each object must contain the following fields: objectID or objectIDs, position.

By default, you can promote up to 30 items per rule.

{
  "objectID": objectID,
  "objectIDs": objectIDs,
  "position": position
}
hide
type: list
Optional

Objects to hide from hits. Each object must contain an objectID field.

By default, you can hide up to 50 items per rule.

{
  "objectID": objectID
}
userData
type: object
Optional

A custom JSON object to append to the userData array in the response. This object isn’t interpreted by the API. It’s limited to 1kB of minified JSON.

Rules âž” rule âž” consequence âž” params

Parameter Description
automaticFacetFilters
type: list of automaticFacetFilter
Optional

Names of facets to which automatic filtering must be applied. This consequence is ignored if a facet name doesn’t match the source item. You can specify a score for each facet name: facetName1\<score=5\>, facetName2\<score=1\>.

automaticOptionalFacetFilters
type: object
Optional

The same syntax as automaticFacetFilters, but the engine treats the filters as optional. Behaves like optionalFilters.

Rules âž” rule âž” consequence âž” promote-params

Parameter Description
objectID
type: string
true (unless using objectIDs)

Unique identifier of the object to promote.

objectIDs
type: string[]
true (unless using objectID)

An array of unique identifiers of the objects to promote.

position
type: integer
Required

The position to promote the objects to (zero-based). If you pass objectIDs, the objects are placed at this position as a group. For example, if you pass four objectIDs to position 0, the objects take the first four positions.

Rules âž” rule âž” consequence âž” hide

Parameter Description
objectID
type: string
Required

Unique identifier of the object to hide.

Rules âž” rule âž” validity âž” timeRange

Parameter Description
from
type: integer
Required

Lower bound of the time range (Unix timestamp).

until
type: integer
Required

Upper bound of the time range (Unix timestamp).

Rules âž” rule âž” consequence âž” params âž” automaticFacetFilter

Parameter Description
facet
type: string
Required

Attribute to filter on. This must match a facet in the source item.

score
type: integer
default: 1
Optional

The score for the filter. Typically used for optional or disjunctive filters.

disjunctive
type: boolean
default: false
Optional

Whether the filter is disjunctive (true) or conjunctive (false). If the filter applies multiple times because the attribute contains multiple values, the multiple occurrences are combined with an AND operator by default (conjunctive mode). If the filter is specified as disjunctive, however, multiple occurrences are combined with an OR operator.

negative
type: boolean
default: false
Optional

Whether the match is inverted (true) or not (false).

Example:

A

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/${indexName}/${model}/recommend/rules/batch" \
    --data-binary '[
      {
        "objectID": "a-recommend-rule-id",
        "condition": {
          "filters": "onSale:true"
        },
        "consequence": {
          "userData": {
            "url": "https://website.com/great-sales"
          }
        }
      },
      {
        "objectID": "a-second-recommend-rule-id",
        "consequence": {
          "params": {
            "promote": [
              {
                "objectID": "alwaysTopRecommendation",
                "position": 0
              }
            ]
          }
        }
      }
    ]'

Response:

1
2
3
4
{
  "taskID": 247427180002,
  "updatedAt": "2021-06-04T08:24:55.069Z"
}

Get Recommend Rule

A

Path: /1/indexes/{indexName}/{model}/recommend/rules/{objectID}
HTTP Verb: GET
Required API Key: any key with the settings ACL

Description:

Return the Recommend Rule with the specified objectID.

objectID isn’t a reference to an Algolia record: it’s the unique identifier for a Recommend Rules object.

Parameters:

Parameter Description
indexName
type: string
Required

Index name

model
type: string
Required

Model name

objectID
type: string
Required

Unique identifier of the rule to retrieve

Example:

A

1
2
3
4
curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/${indexName}/${model}/recommend/rules/${objectID}"

Response:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
  "objectID": "RecommendRuleID",
  "condition": {
    "context": "mobile"
  },
  "consequence": {
    "params": {
      "promote": [
        {
          "objectID": "myProductID",
          "position": 0
        }
      ]
    }
  }
}

Delete Recommend Rule

A

Path: /1/indexes/{indexName}/{model}/recommend/rules/{objectID}
HTTP Verb: DELETE
Required API Key: any key with the editSettings ACL

Description:

Delete the Recommend rule with the specified Rule objectID.

objectID isn’t a reference to an Algolia record: it’s the unique identifier for a Recommend Rules object.

Parameters:

Parameter Description
indexName
type: string
Required

Index name

model
type: string
Required

Model name

objectID
type: string
Required

Unique identifier of the rule to delete

Example:

A

1
2
3
4
curl -X DELETE \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/${indexName}/${model}/recommend/rules/${objectID}"

Response:

1
2
3
4
{
  "taskID": 249200944000,
  "updatedAt": "2021-06-04T08:35:58.984Z"
}

Search Recommend Rules

A

Path: /1/indexes/{indexName}/{model}/recommend/rules/search
HTTP Verb: POST
Required API Key: any key with the settings ACL

Description:

Search for Recommend Rules.

Parameters:

Parameter Description
indexName
type: string
Required

Index name

model
type: string
Required

Model name

query
type: string
default: ""
Optional

Full text query.

context
type: string
default: Any context
Optional

Restricts matches to contextual rules with a specific context (exact match).

page
type: integer
default: 0
Optional

Requested page (zero-based).

hitsPerPage
type: integer
default: 20
Optional

Number of hits retrieved per page. Accepted range: [1, 1000].

enabled
type: boolean
default: none
Optional

When specified, restricts matches to rules with a specific enabled status. When absent, retrieves all the rules, regardless of their enabled status.

requestOptions
type: key-value mapping
default: No request options
Optional

A mapping of requestOptions to send along with the request.

Example:

A

1
2
3
4
5
curl -X POST \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}.algolia.net/1/indexes/${indexName}/${model}/recommend/rules/search" \
    --data-binary '{"query": "world"}'

Response:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
{
  "hits": [
    {
      "_metadata": {
          "lastUpdate": 0
      },
      "consequence": {
        "userData": {
          "hello": "world"
        }
      },
      "enabled": true,
      "objectID": "myRuleID",
      "_highlightResult": {
        "consequence": {
          "userData": {
            "hello": {
              "value": "<b>world</b>",
              "matchLevel": "full",
              "fullyHighlighted": true,
              "matchedWords": [
                "world"
              ]
            }
          }
        }
      }
    }
  ],
  "nbHits": 1,
  "page": 0,
  "nbPages": 1
}

Get a Recommend task’s status

A

Path: /1/indexes/{indexName}/{model}/task/{taskID}
HTTP Verb: GET
Required API Key: any key with the editSettings ACL

Description:

Check the current status of a given Recommend task. taskID is a numeric value (up to 64 bits).

The response exposes the field status. Its value is published if the task has been processed, notPublished otherwise.

Parameters:

Parameter Description
indexName
type: string
Required

Index name

model
type: string
Required

Model name

taskID
type: string
Required

taskID of the indexing task to wait for.

Example:

A

1
2
3
4
5
curl -X GET \
     -H "X-Algolia-API-Key: ${API_KEY}" \
     -H "X-Algolia-Application-Id: ${APPLICATION_ID}" \
    "https://${APPLICATION_ID}-dsn.algolia.net/1/indexes/${indexName}/${model}/task/${taskID}

Response:

1
2
3
{
  "status": "published"
}
Did you find this page helpful?