Techdocs
  • Introduction
  • Implementing Nosto
    • Implement on your website
      • Manual Tagging - Essentials
        • Setting up your account
        • Adding the Nosto Script
        • Adding the Cart Tagging
        • Adding the Customer information
        • Adding the Product Tagging
          • Default Product Tagging
          • Basic Tagging
        • Adding the Category/Brand Tagging
        • Adding the Search Tagging
        • Adding the Order Tagging
        • Defining Nosto placements
        • Tagging your page types
      • Advanced Usage
        • Extending tagging with SKUs
        • Adding support for multi-currency
        • Adding support for customer group pricing
      • FAQ
    • Implement on native mobile
    • Implement on a physical store
    • Implement Search & Categories
      • Using Search Templates
        • Using Search Templates
        • Implementing Search page
        • Implementing Autocomplete
        • Implementing Category pages
        • Testing & deployment
        • FAQ
      • Using the API
        • Use the Search & Categories API
        • Implement Search results page
        • Implement Autocomplete
        • Implement Category pages
        • FAQ
      • Using the JavaScript Library
        • Implement Autocomplete using the Nosto Autocomplete library
          • Installation
          • Initialization
            • Render results
            • Submit search
          • Create Autocomplete template
          • Further reading
    • Check your setup
    • Template customization
      • Starting points
      • Styling
      • Scripting
  • APIs
    • GraphQL
      • The Playground
      • Using the API
      • Testing and Debugging
      • Using Mutations
        • Updating Products
        • Updating Categories
        • Updating Identities
        • GraphQL: Onsite Sessions
        • Working with Orders
          • GraphQL: Placing Orders
          • GraphQL: Updating Order Statuses
      • Using Queries
        • Querying Products
        • Querying Identities
        • Querying Orders
        • Querying Recommendations
        • Querying Segments
        • Querying Search
        • Querying Category Merchandising Products (CM 1.0)
      • For iOS & Android
      • For Headless
    • REST
      • GDPR
        • Redacting customer data
        • Initiating data takeouts
      • Customers
        • Blacklisting Customers
        • Toggling marketing consent
      • Products
        • Updating Products
        • Discontinuing Products
        • Recrawling Products
      • Other
        • Updating Rates
    • Frontend
      • Session API
        • Terminology
        • Setting up
        • Managing Sessions
        • Handling Placements
        • Tracking Events
        • Leveraging Features
        • Record Attribution
        • Advanced Usage
          • Supporting opt-out and do-not-track
          • Using external session identifiers
          • Adding support for multi-currency
          • Adding support for customer group pricing
        • Parameterless Attribution
        • FAQ
      • JS API
        • Initializing Nosto
        • Recommendations
          • Loading Recommendations
          • Recommendation Callbacks
          • Setting up dynamic filtering
          • Sending Product-View Events
          • Sending Add to Cart-Events
        • Popups
          • Listing Popup Campaigns
          • Opening a Popup
          • Enabling & Disabling Popups
          • Popup Callbacks
        • Advanced Usage
          • Sending email addresses to Nosto
          • Manually segmenting users
          • Dynamically sending the cart content
          • Sending Customer Information
        • Record Attribution
      • Open Source
        • Nosto JS
        • Search JS
        • Nosto React
        • Web Components
          • Loading Web components
  • User Generated Content
    • UGC Techdocs
  • 3rd party data integrations
    • Shopify
    • Magento 2
    • Magento
    • BigCommerce
    • Shopware 6
    • Shopware 5
    • Prestashop
    • Salesforce
    • PHP-SDK
Powered by GitBook
On this page
  • Playground and API reference
  • Authentication
  • Making requests
  • API endpoint
  • Account ID
  • Request example
  • Response example
  • Error handling
  • Error response
  • Partial response
  • Session params
  • Using variables
  • Query
  • Variables
  • Analytics

Was this helpful?

Export as PDF
  1. Implementing Nosto
  2. Implement Search & Categories
  3. Using the API

Use the Search & Categories API

PreviousUsing the APINextImplement Search results page

Last updated 9 months ago

Was this helpful?

Not all of Nosto's functionality is available for pure GraphQL API integrations. The following features require Using the JavaScript Library:

  • Analytics

  • Segmentation

  • A/B testing

  • Debug toolbar

Both Search and Categories are built on the same technical foundation and use the same API and product data. For simplicity, we will just refer to Search API in the following documentation.

Playground and API reference

Use the to try out search queries and browse API reference.

It provides:

  1. - you can see field types and inspect what fields are needed for a search request.

  2. - you can see return field types with descriptions.

  3. Send requests to the search engine and preview the response.

Authentication

In the majority of cases, authentication is not a requirement for using search APIs. However in rare case may need to:

  • Access sensitive data- all sensitive data is restricted for public access (e.g. sorting by & returning sales).

  • Return all documents - public access require to specify search query, category ID or category path to avoid returning all documents.

Note: Keep your API key secret and do not expose it to the frontend!

HTTP Header
Value

Authorization

Bearer SEARCH_KEY

Making requests

API endpoint

Search use different API endpoint than other Nosto queries: https://search.nosto.com/v1/graphql

Account ID

All requests require an account ID, which can be found in the top-right corner of the Admin dashboard, under the shop name.

Request example

curl -X POST 'https://search.nosto.com/v1/graphql' \
-H 'Content-Type: application/json' \
-d @- << EOF
{
  "query": "query (\$query: String) { search (accountId: \"YOUR_ACCOUNT_ID\", query: \$query) { products { hits { name } total } } }",
  "variables": {
    "query": "green"
  }
}
EOF

Replace YOUR_ACCOUNT_ID with your account id retrieved from the Nosto dashboard.

fetch('https://search.nosto.com/v1/graphql', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    query: `query ($query: String) {
      search (accountId: "YOUR_ACCOUNT_ID", query: $query) {
        products {
          hits {
            name
          }
          total
        }
      }
    }`,
    variables: {
      query: "green"
    },
  }),
})
  .then((res) => res.json())
  .then((result) => console.log(result))

Replace YOUR_ACCOUNT_ID with your account id retrieved from the Nosto dashboard.

$ch = curl_init();

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
curl_setopt($ch, CURLOPT_URL, "https://search.nosto.com/v1/graphql");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json"));
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode(array(
    "query" => <<<EOT
        query (\$query: String) {
            search (accountId: "YOUR_ACCOUNT_ID", query: \$query) {
                products {
                hits {
                    name
                }
                total
                }
            }
        }
    EOT,
    "variables" => array(
        "query" => "green"
    )
)));

$result = curl_exec($ch);
var_dump($result);

Replace YOUR_ACCOUNT_ID with your account id retrieved from the Nosto dashboard.

import requests

r = requests.post(
    "https://search.nosto.com/v1/graphql",
    headers={
        "Content-Type": "application/json"
    },
    json={
        "query": """query ($query: String) {
            search (accountId: "YOUR_ACCOUNT_ID", query: $query) {
                products {
                hits {
                    name
                }
                total
                }
            }
        }""",
        "variables": {
            "query": "green"
        }
    }
)
print(r.json())

Replace YOUR_ACCOUNT_ID with your account id retrieved from the Nosto dashboard.

Response example

Upon a successful request, the API will return a 200 status code response, which includes the search data:

{
  "data": {
    "search": {
      "products": {
        "hits": [
          {
            "name": "My Product",
          }
        ],
        "total": 1
      }
    }
  }
}

Error handling

Error response

API returns a list of errors with explanations. These errors should be logged internally and not displayed to the end user. Instead, display a general message, such as Search is unavailable at the moment, please try again. This approach ensures that no sensitive information is leaked to the end user.

{
  "data": {
    ...
  },
  "errors": [
    {
      "message": "Error explanation"
    }
  ]
}

Partial response

The API may return some errors even when data is returned. This means that some parts of the response may be missing, but you should still display the available data instead of showing an error to the user. These errors should be logged internally for future reference and troubleshooting.

Session params

For features like personalised results and user segments to function effectively, the search function needs access to the user's session information from the front-end.

nostojs(api => {
    api.getSearchSessionParams().then(response => {
        console.log(response);
    });
});
<script>
    nostojs(api => {
        api.getSearchSessionParams().then(response => {
            document.cookie = `nostoSearchSessionParams=${encodeURIComponent(JSON.stringify(response))};`;
        });
    })
</script>

Using variables

Query

query (
  $query: String,
  $products: InputSearchProducts,
  $sessionParams: InputSearchQuery
) {
  search(
    accountId: "YOUR_ACCOUNT_ID"
    query: $query
    products: $products,
    sessionParams: $sessionParams
  ) {
    query
    products {
      hits {
        productId
        url
        name
        imageUrl
        thumbUrl
        brand
        availability
        price
        listPrice
        customFields {
          key
          value
        }
        skus {
          name
          customFields {
            key
            value
          }
        }
      }
      facets {
        ... on SearchTermsFacet {
          id
          field
          type
          name
          data {
            value
            count
            selected
          }
        }
        ... on SearchStatsFacet {
          id
          field
          type
          name
          min
          max
        }
      }
      total
      size
      from
      fuzzy
    }
  }
}

To optimize search speed and reduce network load, select only the necessary data when performing a search query.

Variables

Variables should encompass all dynamic query data because it is the most efficient method to pass data, and data is automatically escaped to prevent injection attacks. Avoid generating dynamic queries, as they can lead to security issues if user input is not properly escaped.

{
  "query": "red",
  "products": {
    "size": 5
  },
  "sessionParams": {}
}

Analytics

with API_SEARCH Role is available on dashboard settings page

When integrating Search you have the option to directly access the API, or you can use our existing that provides most of the required functionality out of the box.

JS API includes full-featured with tracking support.

It's possible to get search session data using the :

The results of this function should be passed to search query parameter. In case search is called from backend, it should pass this data to backend (e.g. using ).

It's also possible to save session data to on page load:

In the search application, you should use variables instead of hardcoded arguments to pass search data. This means that filters, sort, size, and 'from' options should be passed in the 'products' variable. For a full list of available options, please see the .

To analyze user behavior you need to implement tracking. This can be achieved using our . You need to implement the following methods:

to track search form submissions

Search API Playground
Search request schema
Search result schema
Authentication Token
Search JavaScript library
search function
JS API
sessionParams
form data
cookies
reference
JavaScript library
recordSearchSubmit
https://my.nosto.com