> ## Documentation Index
> Fetch the complete documentation index at: https://algolia.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Retrieve a rule

> Retrieves a Recommend rule that you previously created in the Algolia dashboard.

**Required ACL:** `settings`


## OpenAPI

````yaml specs/recommend.yml get /1/indexes/{indexName}/{model}/recommend/rules/{objectID}
openapi: 3.1.0
info:
  title: Recommend API
  summary: >-
    The Recommend API lets you retrieve recommendations from one of Algolia's AI
    recommendation models that you previously trained on your data
  description: >
    ## Client libraries


    Use Algolia's API clients and libraries to reliably integrate Algolia's APIs
    with your apps.

    The official API clients are covered by Algolia's [Service Level
    Agreement](https://www.algolia.com/policies/sla).


    For more information, see [Algolia's
    ecosystem](https://www.algolia.com/doc/libraries).


    ## Base URLs


    Base URLs for the Recommend API:


    - `https://{APPLICATION_ID}.algolia.net`

    - `https://{APPLICATION_ID}-dsn.algolia.net`.
      If your subscription includes a [Distributed Search Network](https://dashboard.algolia.com/infra),
      this ensures that requests are sent to servers closest to users.

    Both URLs provide high availability by distributing requests with load
    balancing.


    **All requests must use HTTPS.**


    ## Retry strategy


    To guarantee a high availability, implement a retry strategy for all API
    requests using the URLs of your servers as fallbacks:


    - `https://{APPLICATION_ID}-1.algolianet.com`

    - `https://{APPLICATION_ID}-2.algolianet.com`

    - `https://{APPLICATION_ID}-3.algolianet.com`


    These URLs use a different DNS provider than the primary URLs.

    Randomize this list to ensure an even load across the three servers.


    All Algolia API clients implement this retry strategy.


    ## Authentication


    Add these headers to authenticate requests:


    - `x-algolia-application-id`. Your Algolia application ID.

    - `x-algolia-api-key`. An API key with the necessary permissions to make the
    request.
      The required access control list (ACL) to make a request is listed in each endpoint's reference.

    You can find your application ID and API key in the [Algolia
    dashboard](https://dashboard.algolia.com/account/api-keys).


    ## Request format


    Request bodies must be JSON objects.


    ## Response status and errors


    The Recommend API returns JSON responses.

    Since JSON doesn't guarantee any specific ordering, don't rely on the order
    of attributes in the API response.


    Successful responses return `2xx` statuses. Client errors return `4xx`
    statuses. Server errors return `5xx` statuses.

    Error responses have a `message` property with more information.


    ## Version


    The current version of the Recommend API is version 1, indicated by the
    `/1/` in each endpoint's URL.
  version: 1.0.0
servers:
  - url: https://{appId}.algolia.net
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-1.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-2.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-3.algolianet.com
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
  - url: https://{appId}-dsn.algolia.net
    variables:
      appId:
        default: ALGOLIA_APPLICATION_ID
security:
  - appId: []
    apiKey: []
tags:
  - name: recommendations
    x-displayName: Recommendations
    description: >-
      Retrieve recommendations from a pre-trained AI model. You can train models
      in the [Algolia dashboard](https://dashboard.algolia.com/recommend).
    externalDocs:
      url: https://www.algolia.com/doc/guides/algolia-recommend/overview
      description: Algolia Recommend.
  - name: rules
    x-displayName: Rules
    description: Curate your recommendations with rules, which are _if_-_then_ statements.
    externalDocs:
      url: https://www.algolia.com/doc/guides/algolia-recommend/how-to/rules
      description: Recommend Rules.
paths:
  /1/indexes/{indexName}/{model}/recommend/rules/{objectID}:
    get:
      tags:
        - rules
      summary: Retrieve a rule
      description: >-
        Retrieves a Recommend rule that you previously created in the Algolia
        dashboard.
      operationId: getRecommendRule
      parameters:
        - $ref: '#/components/parameters/IndexName'
        - $ref: '#/components/parameters/Models'
        - $ref: '#/components/parameters/ObjectID'
      responses:
        '200':
          description: OK
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/RecommendRule'
        '400':
          $ref: '#/components/responses/BadRequest'
        '402':
          $ref: '#/components/responses/FeatureNotEnabled'
        '403':
          $ref: '#/components/responses/MethodNotAllowed'
        '404':
          $ref: '#/components/responses/IndexNotFound'
      x-codeSamples:
        - lang: csharp
          label: C#
          source: |-
            // Initialize the client
            var client = new RecommendClient(
              new RecommendConfig("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY")
            );

            // Call the API
            var response = await client.GetRecommendRuleAsync(
              "<YOUR_INDEX_NAME>",
              Enum.Parse<RecommendModels>("RelatedProducts"),
              "objectID"
            );

            // print the response
            Console.WriteLine(response);
        - lang: dart
          label: Dart
          source: |-
            // Initialize the client
            final client = RecommendClient(
                appId: 'ALGOLIA_APPLICATION_ID', apiKey: 'ALGOLIA_API_KEY');

            // Call the API
            final response = await client.getRecommendRule(
              indexName: "<YOUR_INDEX_NAME>",
              model: RecommendModels.fromJson("related-products"),
              objectID: "objectID",
            );

            // print the response
            print(response);
        - lang: go
          label: Go
          source: >-
            // Initialize the client

            client, err := recommend.NewClient("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY")

            if err != nil {
              // The client can fail to initialize if you pass an invalid parameter.
              panic(err)
            }


            // Call the API

            response, err :=
            client.GetRecommendRule(client.NewApiGetRecommendRuleRequest(
              "<YOUR_INDEX_NAME>", recommend.RecommendModels("related-products"), "objectID"))
            if err != nil {
              // handle the eventual error
              panic(err)
            }



            // print the response

            print(response)
        - lang: java
          label: Java
          source: >-
            // Initialize the client

            RecommendClient client = new
            RecommendClient("ALGOLIA_APPLICATION_ID", "ALGOLIA_API_KEY");


            // Call the API

            RecommendRule response =
            client.getRecommendRule("<YOUR_INDEX_NAME>",
            RecommendModels.RELATED_PRODUCTS, "objectID");


            // print the response

            System.out.println(response);
        - lang: javascript
          label: JavaScript
          source: >-
            // Initialize the client

            const client = algoliasearch('ALGOLIA_APPLICATION_ID',
            'ALGOLIA_API_KEY').initRecommend();


            // Call the API

            const response = await client.getRecommendRule({
              indexName: 'indexName',
              model: 'related-products',
              objectID: 'objectID',
            });



            // print the response

            console.log(response);
        - lang: kotlin
          label: Kotlin
          source: >-
            // Initialize the client

            val client = RecommendClient(appId = "ALGOLIA_APPLICATION_ID",
            apiKey = "ALGOLIA_API_KEY")


            // Call the API

            var response =
              client.getRecommendRule(
                indexName = "<YOUR_INDEX_NAME>",
                model = RecommendModels.entries.first { it.value == "related-products" },
                objectID = "objectID",
              )


            // print the response

            println(response)
        - lang: php
          label: PHP
          source: >-
            // Initialize the client

            $client = RecommendClient::create('ALGOLIA_APPLICATION_ID',
            'ALGOLIA_API_KEY');


            // Call the API

            $response = $client->getRecommendRule(
                '<YOUR_INDEX_NAME>',
                'related-products',
                'objectID',
            );



            // print the response

            var_dump($response);
        - lang: python
          label: Python
          source: >-
            # Initialize the client

            # In an asynchronous context, you can use RecommendClient instead,
            which exposes the exact same methods.

            client = RecommendClientSync("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY")


            # Call the API

            response = client.get_recommend_rule(
                index_name="<YOUR_INDEX_NAME>",
                model="related-products",
                object_id="objectID",
            )



            # print the response

            print(response)
        - lang: ruby
          label: Ruby
          source: >-
            # Initialize the client

            client = Algolia::RecommendClient.create("ALGOLIA_APPLICATION_ID",
            "ALGOLIA_API_KEY")


            # Call the API

            response = client.get_recommend_rule("<YOUR_INDEX_NAME>",
            "related-products", "objectID")



            # print the response

            puts(response)
        - lang: scala
          label: Scala
          source: >-
            // Initialize the client

            val client = RecommendClient(appId = "ALGOLIA_APPLICATION_ID",
            apiKey = "ALGOLIA_API_KEY")


            // Call the API

            val response = Await.result(
              client.getRecommendRule(
                indexName = "<YOUR_INDEX_NAME>",
                model = RecommendModels.withName("related-products"),
                objectID = "objectID"
              ),
              Duration(100, "sec")
            )


            // print the response

            println(response)
        - lang: swift
          label: Swift
          source: >-
            // Initialize the client

            let client = try RecommendClient(appID: "ALGOLIA_APPLICATION_ID",
            apiKey: "ALGOLIA_API_KEY")


            // Call the API

            let response = try await client.getRecommendRule(
                indexName: "<YOUR_INDEX_NAME>",
                model: RecommendModels.relatedProducts,
                objectID: "objectID"
            )


            // print the response

            print(response)
        - lang: cURL
          label: curl
          source: |-
            curl --request GET \
              --url https://algolia_application_id.algolia.net/1/indexes/ALGOLIA_INDEX_NAME/related-products/recommend/rules/test-record-123 \
              --header 'accept: application/json' \
              --header 'x-algolia-api-key: ALGOLIA_API_KEY' \
              --header 'x-algolia-application-id: ALGOLIA_APPLICATION_ID'
components:
  parameters:
    IndexName:
      name: indexName
      in: path
      description: Name of the index on which to perform the operation.
      required: true
      schema:
        type: string
        example: ALGOLIA_INDEX_NAME
    Models:
      in: path
      name: model
      required: true
      description: >
        [Recommend
        model](https://www.algolia.com/doc/guides/algolia-recommend/overview/#recommend-models).
      schema:
        $ref: '#/components/schemas/recommendModels'
    ObjectID:
      name: objectID
      in: path
      description: Unique record identifier.
      required: true
      schema:
        $ref: '#/components/schemas/objectID'
  schemas:
    RecommendRule:
      type: object
      description: Recommend rule.
      additionalProperties: false
      properties:
        _metadata:
          title: ruleMetadata
          type: object
          description: Rule metadata.
          properties:
            lastUpdate:
              $ref: '#/components/schemas/updatedAt'
        condition:
          $ref: '#/components/schemas/Condition'
        consequence:
          $ref: '#/components/schemas/Consequence'
        description:
          type: string
          description: >-
            Description of the rule's purpose. This can be helpful for display
            in the Algolia dashboard.
          example: Boost on-sale items
        enabled:
          type: boolean
          default: true
          description: >-
            Indicates whether to enable the rule. If it isn't enabled, it isn't
            applied at query time.
        objectID:
          $ref: '#/components/schemas/ruleID'
        validity:
          type: array
          description: Time periods when the rule is active.
          items:
            $ref: '#/components/schemas/timeRange'
    recommendModels:
      type: string
      enum:
        - related-products
        - bought-together
        - trending-facets
        - trending-items
    objectID:
      type: string
      description: Unique record identifier.
      example: test-record-123
    updatedAt:
      type: string
      example: '2023-07-04T12:49:15Z'
      description: Date and time when the object was updated, in RFC 3339 format.
    Condition:
      type: object
      description: |
        Condition that triggers the rule.
        If not specified, the rule is triggered for all recommendations.
      properties:
        context:
          $ref: '#/components/schemas/context'
        filters:
          $ref: '#/components/schemas/filters'
    Consequence:
      type: object
      description: Effect of the rule.
      properties:
        hide:
          $ref: '#/components/schemas/HideConsequence'
        params:
          $ref: '#/components/schemas/ParamsConsequence'
        promote:
          $ref: '#/components/schemas/PromoteConsequence'
    ruleID:
      title: objectID
      type: string
      description: Unique identifier of a rule object.
    timeRange:
      type: object
      additionalProperties: false
      properties:
        from:
          type: integer
          format: int64
          description: >-
            Timestamp when the rule should start to be active, measured in
            seconds since the Unix epoch.
        until:
          type: integer
          format: int64
          description: >-
            Timestamp when the rule should stop to be active, measured in
            seconds since the Unix epoch.
    ErrorBase:
      description: Error.
      type: object
      x-keep-model: true
      additionalProperties: true
      properties:
        message:
          type: string
          example: Invalid Application-Id or API-Key
    context:
      type: string
      pattern: '[A-Za-z0-9_-]+'
      description: >
        An additional restriction that only triggers the rule, when the search
        has the same value as `ruleContexts` parameter.

        For example, if `context: mobile`, the rule is only triggered when the
        search request has a matching `ruleContexts: mobile`.

        A rule context must only contain alphanumeric characters.
      example: mobile
    filters:
      type: string
      description: >
        Filter expression to only include items that match the filter criteria
        in the response.


        You can use these filter expressions:


        - **Numeric filters.** `<facet> <op> <number>`, where `<op>` is one of
        `<`, `<=`, `=`, `!=`, `>`, `>=`.

        - **Ranges.** `<facet>:<lower> TO <upper>`, where `<lower>` and
        `<upper>` are the lower and upper limits of the range (inclusive).

        - **Facet filters.** `<facet>:<value>`, where `<facet>` is a facet
        attribute (case-sensitive) and `<value>` a facet value.

        - **Tag filters.** `_tags:<value>` or just `<value>` (case-sensitive).

        - **Boolean filters.** `<facet>: true | false`.


        You can combine filters with `AND`, `OR`, and `NOT` operators with the
        following restrictions:


        - You can only combine filters of the same type with `OR`.
          **Not supported:** `facet:value OR num > 3`.
        - You can't use `NOT` with combinations of filters.
          **Not supported:** `NOT(facet:value OR facet:value)`
        - You can't combine conjunctions (`AND`) with `OR`.
          **Not supported:** `facet:value OR (facet:value AND facet:value)`

        Use quotes if the facet attribute name or facet value contains spaces,
        keywords (`OR`, `AND`, `NOT`), or quotes.

        If a facet attribute is an array, the filter matches if it matches at
        least one element of the array.


        For more information, see
        [Filters](https://www.algolia.com/doc/guides/managing-results/refine-results/filtering).
      example: (category:Book OR category:Ebook) AND _tags:published
      x-categories:
        - Filtering
    HideConsequence:
      type: array
      description: Exclude items from recommendations.
      minItems: 1
      items:
        $ref: '#/components/schemas/HideConsequenceObject'
    ParamsConsequence:
      type: object
      description: Filter or boost recommendations matching a facet filter.
      properties:
        automaticFacetFilters:
          type: array
          description: >-
            Filter recommendations that match or don't match the same
            `facet:facet_value` combination as the viewed item.
          items:
            $ref: '#/components/schemas/AutoFacetFilter'
        filters:
          $ref: '#/components/schemas/filters'
        optionalFilters:
          type: array
          description: >
            Filters to promote or demote records in the search results.


            Optional filters work like facet filters, but they don't exclude
            records from the search results.

            Records that match the optional filter rank before records that
            don't match.

            Matches with higher weights (`<score=N>`) rank before matches with
            lower weights.

            If you're using a negative filter `facet:-value`, matching records
            rank after records that don't match.
          items:
            type: string
          example:
            - category:books<score=1>
            - category:-movies<score=1>
    PromoteConsequence:
      type: array
      description: Place items at specific positions in the list of recommendations.
      minItems: 1
      items:
        $ref: '#/components/schemas/PromoteConsequenceObject'
    HideConsequenceObject:
      type: object
      description: Object ID of the recommendation you want to exclude.
      properties:
        objectID:
          $ref: '#/components/schemas/objectID'
    AutoFacetFilter:
      type: object
      description: >-
        Facet attribute. Only recommendations with the same value (or only
        recommendations with a different value) as the original viewed item are
        included.
      properties:
        facet:
          type: string
          description: Facet attribute.
        negative:
          type: boolean
          description: >
            Whether the filter is negative.

            If true, recommendations must not have the same value for the
            `facet` attribute.

            If false, recommendations must have the same value for the `facet`
            attribute.
    PromoteConsequenceObject:
      type: object
      description: Object ID and position of the recommendation you want to pin.
      properties:
        objectID:
          $ref: '#/components/schemas/objectID'
        position:
          type: integer
          description: Index in the list of recommendations where to place this item.
          minimum: 0
  responses:
    BadRequest:
      description: Bad request or request arguments.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    FeatureNotEnabled:
      description: This feature is not enabled on your Algolia account.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    MethodNotAllowed:
      description: Method not allowed with this API key.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
    IndexNotFound:
      description: Index not found.
      content:
        application/json:
          schema:
            $ref: '#/components/schemas/ErrorBase'
  securitySchemes:
    appId:
      type: apiKey
      in: header
      name: x-algolia-application-id
      description: Your Algolia application ID.
    apiKey:
      type: apiKey
      in: header
      name: x-algolia-api-key
      description: >
        Your Algolia API key with the necessary permissions to make the request.

        Permissions are controlled through access control lists (ACL) and access
        restrictions.

        The required ACL to make a request is listed in each endpoint's
        reference.

````