SDK JS-Client

Introduction

The Search JS-Client allows you to call an Inbenta API endpoint quickly and easily with javascript.

Note: All examples shown are set in a Production environment.

Setup

Steps to follow:

  1. Integration

    Include the Inbenta Search SDK script somewhere in your page:

     <script src="https://sdk.inbenta.io/search/<version>/inbenta-search-client.js"></script>
  2. Creation

    Next, create a new client instance. To do so, you will need a Domain Key and and API Key. Alternatively, you will need your API Key (public key) and either an API secret or an access token. See Finding your API credentials in the Help Center to obtain your credentials.

    The following example shows a creation using a domain key. For more information, see the Authorization section.

      var client = InbentaSearchClient.createFromDomainKey('<your_Domain_Key>', '<your_API_Key>');
  3. Use client

    client.search('toys').then(function(results) {
        console.log(results[0]);
    });

Example

The following code provides an example of how to do a search query using SDK Client.

<!doctype html>
<html lang="en">
<head>
    <script src="https://sdk.inbenta.io/search/<version>/inbenta-search-client.js"></script>
</head>
<body>
  <script type="text/javascript">
    var domainKey = '<your_Domain_Key>';
    var apiKey = 'BVkiK9F7inLwEBEIUVrfpJhpOfjIfj8PyTVCiKu9WUs=';
    var client = InbentaSearchClient.createFromDomainKey(<your_Domain_Key>, <your_API_Key>);
    client.search('toys').then(function(results) {
        console.log(results[0]);
    });
  </script>
</body>

Versions

When you set up the SDK for your Inbenta product, you need to specify the version like this:

<script src="https://sdk.inbenta.io/search/<version>/inbenta-search-client.js"></script>

Versions are written in MAJOR.MINOR.PATCH format.

Important:

  • Do NOT cache or store these files, otherwise you will not benefit from bug fixing and minor upgrades.
  • Inbenta strongly recommends that you use a MAJOR.MINOR.PATCH version.

Examples

  • If only MAJOR is set, this script will use the highest available MINOR version. <script src="https://sdk.inbenta.io/search/1/inbenta-search-sdk.js"></script>
  • If MAJOR.MINOR are set, this script will use the highest available PATCH version. <script src="https://sdk.inbenta.io/search/1.2/inbenta-search-sdk.js"></script>
  • If you specify the full version, only this exact version will be used. <script src="https://sdk.inbenta.io/search/1.2.3/inbenta-search-sdk.js"></script>

Client Creation explanation

Create a new SDK instance. You will need your API Key and either an API secret or an access token.

Contact Inbenta to receive your API Key and your secret.

Important: We strongly recommend generating the access token on the server side. You should never publish your API secret on your site, or someone might take it and use it.

Create SDK instance with accessToken:

var client = InbentaSearchClient.createFromAccessToken(accessToken: String, apiKey: String, config: Object);

Configuration

The following table shows the available InbentaSearchSDK parameters:

Name Type Default Description 
userType integer 0 Defines the profiles identifier from the Search App's knowledge base. It uses an x-inbenta-user-type header to make API requests. For more information about this header, see the API Routes.
environment string production Defines the source environment from the Search App's knowledge base. It will be used as x-inbenta-env header. Possible values:
  • production (default): This environment logs the data for the reports displayed in the Inbenta dashboards and retrieves the contents/categories published in live.
  • preproduction: This environment does not log any data and retrieves the contents/categories published in live.
  • development: This environment does not log any data and retrieves the contents/categories published in edit.
For more information about this header, see the API Routes.
apiURL string null Defines the URL of the search endpoint. If defined, it avoids the initial request to /apis for the sole purpose of getting the URL of the search endpoint when creating the Client using createFromAccessToken.
expirationTime integer null Defines the Unix timestamp when the token should expire. If defined, it avoids the initial request to /refreshToken when creating the Client using createFromAccessToken.
autoRefresh boolean true Defines whether or not the client gets a new token when the current one expires. If set to false, the client does not automatically call /refreshToken or /auth when the token expires.

Methods

The following methods are available in the client:

Method Description
autocompleterData() Value for dynamic settings marked as autocompletable, or visible in the autocompleter. This can be done in the Knowledge Management App, from Settings > Dynamic.
generateSession() Creates a sessionToken (returns a promise).
hasSession() Whether or not the session is started.
hasError() Whether or not there is an authentication error.
isReady() Whether or not the client is ready, meaning, it has authenticated and retrieved the api endpoint correctly.
getAccessToken() Current access token.
getExpiration() Client's access token expiration period.
refreshAccessToken() Refresh the accessToken and receive a new access token (returns a promise).
setSession(sessionToken: String) Set up a session token into the client to track events (returns a promise).
setUserInfo(data: Object) Register specific user information for later analysis.
search(query: String, options: Object) Searches a single query with different options (returns a promise). More information here.
searches(requests: RequestOptions[]) Does multiple requests with different options (returns a promise). More information here.
trackEvent(event: String, data: Object) Tracks an event. More information here.

Handling Errors

Click here to see a list of Inbenta error codes.

// Search example
client.search('toys', [
  {
    filters: ['color:red', 'year:2017'],
    attributes: ['name', 'color', 'year']
  }
]).then(function (results) {
  console.log(results[0]);
}).catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

Managing authentication errors

The JS-Client launches an event when something goes wrong during the authentication process, or when the refreshToken request fails.

The name of the event is error. You can catch it easily like this:

client.on('error', function (error) {
    if (error.response.status === 403 ) {
       console.log('Error : ' + error.response.data.message);
    }
})