NAV

Introduction

The Nosto API documentation is a knowledge base for any developer who wants to go beyond the regular Nosto implementation. From our server-to-server API to our Javascript API, you will find an extensive set of resources to cover the most common e-commerce related use cases.

These APIs are not for implementing Nosto but for extending an existing implementation. To implement Nosto, please visit our Installation Guide.

To discover how to use all Nosto features, study our best practices and read the most frequently asked questions, you can visit our Support Center.

Nosto recommendations API is designed to extend Nosto recommendations outside of on-site context.

Many of the use cases vary from embedding recommendatios to newsletters, serving recommendations to landing pages to streamlining experience of adding personalized recommendations to stores running on top of various E-commerce platforms.

Available APIs

Nosto provides following APIs:

API Use case Requires authentication
JavaScript For more demanding on-site implementations (e.g. Single Page Applications). No
Products For product updates Yes
Recommendations for Emails Display recommendations as part of an email. Yes
Point of Sale purchases For tracking purchases from physical points of sales Yes

Endpoint

Web APIs are accessed via https://api.nosto.com address.

Authentication

// Example only available in Shell
// Example only available in Shell
# In shell, you can just pass the correct authorization header with each request.
curl -X GET --user :NOSTO_API_TOKEN https://api.nosto.com/recommendations?elements=example-nosto-slot-div-id

Authentication with the API is done by using HTTP Basic Auth. You authenticate by using your API key as the password, username can be left empty.

You can see your API keys in the Nosto Backend under account settings. API key is always tied to a single store in your account. You should keep your API key secret and delete it immediately if you think someone untrusted might have had access to it.

All API requests must be done by using HTTPS. If you happen to call the interface via HTTP using a valid API key, that API key will be invalidated immediately and a notice of the event sent to the owner of the account.

HTTP Header Value
Authorization Basic :NOSTO_API_TOKEN

Token types

You can get token values from authentication tokens page under your Nosto Account.

Token type Description
API_REC  Token for Recommendations API
API_PRODUCTS  Token for Products API

Blacklist

Blacklists email addresses. Blacklisting an email address means the recipient will not receive any Triggered Emails.

Examples of Triggered Emails that the merchant can configure are: Abandoned Cart Emails, Order Followup and Miss You Email.

Add email addresses to blacklist

Example of the request body. Individual email addresses are separated by a newline.

john.doe@example.org
jill.doe@example.org
curl ­https://api.nosto.com/v1/email/blacklist?op=add
    -X POST ­­
    --user :<token> ­­
    data­binary @blacklist.txt 

The above command returns JSON structured like this:

    {
        "message" : "2/2 emails were added to blacklist",
        "type":"OK"
    }

Adds email address(es) to blacklist.

Method Endpoint
POST https://api.nosto.com/v1/email/blacklist?op=add

Requests body can contain one or more email addresses. Email addresses are separated by newline.

Query parameters

Parameter Required Description
op required Specifies the operation. Always add.
type optional If defined, email address(es) will be blacklisted for a given Triggered Email type. If omitted, given address(es) will be blacklisted for all known types. Possible values: missyou, abandonedcart or orderfollowup. To blacklist by multiple types, specify one type parameter per Triggered Email type. For example, type=missyou&type=abandonedcart will blacklist given emails for We Miss You and Abandoned Cart emails.

Remove email addresses from blacklist

Example of the request body. Individual email addresses are separated by a newline.

john.doe@example.org
jill.doe@example.org
curl ­https://api.nosto.com/v1/email/blacklist?op=remove
    -X POST ­­
    --user :<token> ­­
    data­binary @blacklist.txt 

The above command returns JSON structured like this:

{
    "message":"2/2 emails were removed from blacklist",
    "type":"OK"
}

Removes email address(es) from blacklist.

Method Endpoint
POST https://api.nosto.com/v1/email/blacklist?op=remove

Query parameters

Parameter Required Description
op required Specifies the operation. Always remove.
type optional If defined, removes email address(es) from blacklist of a given Triggered Email type. If omitted, given address(es) will be removed from blacklist of all known types. Possible values: missyou, abandonedcart or orderfollowup. To remove address(es) from blacklist of multiple types, specify one type parameter per Triggered Email type. For example, type=missyou&type=abandonedcart will remove given email address(es) from blacklist of We Miss You and Abandoned Cart emails.

Requests body can contain one or more email addresses. Email addresses are separated by newline.

Redaction

The Redaction API allows you remove all personally identifiable information associated with a customer. An API_EMAIL token is required for accessing the following endpoints

All requests to these endpoints are asynchronous and simply enqueue the email address for redaction. It may take up to 24 hours for the redaction process to complete. If the email address is found, a notification email (informing you about the redaction) will be sent once the process has completed.

Note: Exercise caution when using the Redaction APIs as redaction is an irreversible process.

Redacting by email

Redacts all personally identifiable information (PII) associated with an email address.

curl ­https://api.nosto.com/v1/customers/redact/{email}
    -X DELETE ­­
    --user :<token>

Redacts all PII for a given customer

Method Endpoint
DELETE https://api.nosto.com/v1/customers/redact/{email}

Consent

The Consent API allows you to change a customer’s marketing opt-in permission. An API_EMAIL token is required for accessing the following endpoints.

Grant marketing opt-in for email

Sets the opt-in permission for the specified email address to true. The customer associated with this email address will be whitelisted for email remarketing.

curl ­https://api.nosto.com/v1/customers/consent/{email}/true
    -X POST ­­
    --user :<token>

Opts in the given email address for email remarketing

Method Endpoint
DELETE https://api.nosto.com/v1/customers/consent/true

Remove marketing opt-in for email

Sets the opt-in permission for the specified email address to false. The customer associated with this email address will not receive any email remarketing.

curl ­https://api.nosto.com/v1/customers/consent/{email}/false
    -X POST ­­
    --user :<token>

Opts out the given email address for email remarketing

Method Endpoint
DELETE https://api.nosto.com/v1/customers/consent/false

Recommendations for Emails

Request will invoke a recommendation slot which has a recommendation template that is responsible of the recommendations markup for the response.

Get personalized recommendations

Single address: Get recommendations from ’example-nosto-slot-div-id’ slot for example@example.org email:

curl "https://api.nosto.com/recommendations/email?elements=example-nosto-slot-div-id&emails=example@example.org"
  -X "GET"
  --user :API_REC
// Example only available in shell
// Example only available in shell

The above command returns JSON structured like this:

{ 
  "example@example.org" : {
        "example-nosto-slot-div-id" : "...html..."   
  }
}

Multiple addresses: Get recommendations from ’example-nosto-slot-div-id’ slot for example@example.org and example+1@example.org email:

curl "https://api.nosto.com/recommendations/email?elements=example-nosto-slot-div-id&emails=example@example.org,example+1@example.org"
    -X "GET"
    --user :API_REC

// Example only available in shell
// Example only available in shell

The above command returns JSON structured like this:

{ 
  "example@example.org" : {
        "example-nosto-slot-div-id" : "...html..."   
  },
  "example+1@example.org" : {
        "example-nosto-slot-div-id" : "...html..."   
  }
}

Retrieve recommendations for given email addresses.

Method Endpoint
GET https://api.nosto.com/recommendations/email

Required query parameters

Parameter Description
elements Specifies the recommendation slot. Matches to recommendation slot DIV ID. Comma separated list of slot IDs.
emails Recipient email address(es). Parameter can contain one or more email addresses. Comma separated list of email addresses

Supported algorithms

Algorithm Description
Personalized Recommendations Recommendation displays visitors the items they viewed or added to their cart, but did not buy. Read more
Browsing history Displays visitor’s product browsing history in a linear order. Read more
Browsing history related Displays new products related to a visitor’s recent browsing history, excluding products a visitor has already browsed, by comparing visitor’s browsing history to similar profiles. Read more

Get generic recommendations

Single recommendation slot: Retrieve recommendations for 'nosto-div-id' slot.

curl "https://api.nosto.com/recommendations?elements=nosto-div-id" 
    --user :REPLACE_WITH_API_TOKEN 
    -X "GET" 

Retrieve non-personalized recommendations like Best Sellers & Trending Products.

Method Endpoint
GET https://api.nosto.com/recommendations
<?php
function nostoCurl($url, $nostoToken)
{
    $ch = curl_init();
    $curlOptions = array(
        CURLOPT_HTTPHEADER => array(
            'Authorization: Basic ' . base64_encode(':' . $nostoToken)
        ),
        CURLOPT_URL => $url,
        CURLOPT_HEADER => true,
        CURLOPT_FRESH_CONNECT => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_FORBID_REUSE => true,
        CURLOPT_TIMEOUT => 60
    );
    curl_setopt_array($ch, $curlOptions);
    $response = curl_exec($ch);
    curl_close($ch);
    return $response;
}

$testResponse = nostoCurl(
    'https://api.nosto.com/recommendations?elements=api-slot-example',
    'REPLACE_WITH_API_REC_TOKEN'
);
?>

The above command returns JSON structured like this:

{ 
  "nosto-div-id" : "...html..."
}

Multiple recommendation slots: Retrieve recommendations for 'nosto-div-id-1' and 'nosto-div-id-2' slots.

curl "https://api.nosto.com/recommendations?elements=nosto-div-id" 
    --user :REPLACE_WITH_API_TOKEN 
    -X "GET" 

The above command returns JSON structured like this:

{ 
  "nosto-div-id-1" : "...html...",
  "nosto-div-id-2" : "...html..."
}

Query Parameters

Parameter Description
elements Nosto element IDs that define the used algorithm and layout. Elements are separated by commas.

Optional query parameters

Parameter Description
categories Categories in URL encoded format.

Supported algorithms

Algorithm Description
Best Sellers and Trending Products Best sellers and trending products or top lists in short is a recommendation type based on overall trend data and popularity displaying what is currently “hot and popular” on the online store. Read more

Get cross-sell recommendations

Single product

curl "https://api.nosto.com/recommendations/related\?elements\=api-related\&products\=406" 
    --user :REPLACE_WITH_API_TOKEN
    -X GET  

Response JSON

{
    "api-related" : {
        "406" : ".... markup ...."
    }
}

Multiple products

curl "https://api.nosto.com/recommendations/related\?elements\=api-related\&products\=406,370" 
    --user :REPLACE_WITH_API_TOKEN
    -X GET  

Response JSON

{
    "api-related" : {
        "406" : ".... markup ....",
        "370" : ".... markup ...."
    }
}
Method Endpoint
GET https://api.nosto.com/recommendations/related

Query Parameters

Parameter Description
elements Nosto element IDs that define the used algorithm and layout. Elements are separated by commas.
products Comma separated list of product IDs. API will return products that are related to products in this list.

Supported algorithms

Algorithm Description
Cross-Selling and Up-Selling Displays product recommendations that are related to the product that the visitor is viewing, such as “Customers Who Viewed This Also Viewed.”. Read more

Products

Example of product payload

[
  {
    "url": "http://www.example.com/product/CANOE123",
    "categories": ["/Outdoor/Boats/Canoes", "/Sales/Boats"],
    "description": "This foldable canoe is easy to travel with.",
    "product_id": "CANOE123",
    "name": "ACME Foldable Canoe",
    "image_url": "http://www.example.com/product/images/CANOE123.jpg",
    "price": 1269.99,
    "list_price": 1299.80,
    "price_currency_code": "EUR",
    "availability": "InStock",
    "brand": "ACME",
    "tag1": ["Men"],
    "tag2": ["Foldable"],
    "tag3": ["Brown", "Black", "Orange"],
    "date_published" : "2011-12-31",
    "thumb_url" : "http://www.example.com/product/images/thumb/CANOE123.jpg",
    "variation_id" : "EUR",
    "variations" : {
        "USD" : {
            "price" : 1422.96,
            "price_currency_code" : "USD",
            "availability" : "InStock",
            "list_price" : 1456.17
        },
        "GBP" : {
            "price" : 1003.99,
            "price_currency_code" : "GBP",
            "availability" : "InStock",
            "list_price" : 1026.41
        }
    },
    "google_category" : "Outdoor > Boats > Canoes",
    "gtin" : "canoe123",
    "condition" : "new",
    "age_group" : "adult",
    "gender" : "unisex",
    "inventory_level" : 25,
    "supplier_cost" : 1312.96,
    "review_count" : 20,
    "rating_value" : 3.0,
    "alternate_image_urls" : [
        "http://www.example.com/product/images/image1.jpg",
        "http://www.example.com/product/images/image2.jpg"
        ]
  }
]

Products API allows updating and inserting product data without issuing re-crawl requests to the product pages. API supports both synchronous and asynchronous modes.

Requests are asynchronous by default. Change between mode requires a change in the API request URL.

Required headers

Header Value
Content-Type: application/json;charset=UTF-8

Products in multiple currencies

Same product with different currency is called a variant in Nosto parlance. These variants have individual IDs and have hierachy.

The variation ID of the main product, with EUR price, in the example is defined in the variation_id field. Variation id of the main product is EUR. The variation IDs of the USD and GBP prices (USD and GBP respectively) are defined as keys of the variations JSON object, not as additional variation_id fields.

Create product

# Create a file with payload from previous example and pass the name of the file
# after '@' character.

curl "https://api.nosto.com/v1/products/create"
     --user :API_PRODUCT  
     -X POST
     -v
     -q
     --header "Content-Type: application/json;charset=UTF-8"
     --data-binary '@createProductpayload.json'

Create products. Create does not update and trying to re-create existing product will result into an error.

Method Endpoint
POST https://api.nosto.com/v1/products/create

Payload

Requests body can contain one or more products. Data formats in the payload follow the structure and specification of Nosto tagging for product guide.

Thumbnails

Discontinue product

Discontinue products with ID123 and 342.

curl "https://api.nosto.com/v1/products/discontinue"
     --user :API_PRODUCT  
     -X POST
     -v
     -q
     --header "Content-Type: application/json;charset=UTF-8"
     --data-binary '@discontinuePayload.json'

discontinuePayload.json

[
    "123",
    "342"
]

Mark product discontinued. Discontinued means that products will never show up in recommendations.

Method Endpoint
POST https://api.nosto.com/v1/products/discontinue

Payload

Request body defines one or more products that will be marked discontinued.

Upsert product

Update or insert products 123and 342

curl "https://api.nosto.com/v1/products/upsert"
     --user :API_PRODUCT  
     -X POST
     -v
     -q
     --header "Content-Type: application/json;charset=UTF-8"
     --data-binary '@updateProductsPayload.json'

updateProductsPayload.json payload without price variations

[
    {
        "url" : "http://shop.example.com/product/123",
        "product_id" : "123",
        "name" : "Example product 123",
        "image_url" : "http://cdn.example.com/product_123.jpg",
        "price_currency_code" : "EUR",
        "availability" : "InStock",
        "categories" : ["sale/summer", "shirts"],
        "description" : "Example description",
        "price" : 12.34,
        "list_price" : 12.34,
        "brand" : "Example Brand",
        "tag1" : ["red", "green"],
        "tag2" : ["women"],
        "tag3" : ["Foldable"],
        "date_published" : "2013-­04-­23",
        "google_category" : "shirts",
        "gtin" : "123",
        "condition" : "new",
        "age_group" : "adult",
        "gender" : "unisex",
        "inventory_level" : 25,
        "supplier_cost" : 1312.96
    },
    {
        "url" : "http://shop.example.com/product/342",
        "product_id" : "342",
        "name" : "Example product 342",
        "image_url" : "http://cdn.example.com/product_342.jpg",
        "price_currency_code" : "EUR",
        "availability" : "OutOfStock",
        "categories" : ["sale/summer", "shirts"],
        "description" : "Another example description",
        "price" : 12.34,
        "list_price" : 12.34,
        "brand" : "Example Brand",
        "tag1" : ["red", "green"],
        "tag2" : ["women"],
        "tag3" : ["Foldable"],
        "date_published" : "2013-­04-­23",
        "google_category" : "shirts",
        "gtin" : "342",
        "condition" : "new",
        "age_group" : "adult",
        "gender" : "unisex",
        "inventory_level" : 25,
        "supplier_cost" : 1312.96
    }
]

Update product payload for products with multiple price variations.

[
    {
        "url" : "http://shop.example.com/product/123",
        "product_id" : "123",
        "name" : "Example product 123",
        "image_url" : "http://cdn.example.com/product_123.jpg",
        "price_currency_code" : "EUR",
        "availability" : "InStock",
        "categories" : ["sale/summer", "shirts"],
        "description" : "Example description",
        "price" : 10.00,
        "list_price" : 12.34,
        "brand" : "Example Brand",
        "tag1" : ["red", "green"],
        "tag2" : ["women"],
        "tag3" : ["Foldable"],
        "date_published" : "2013-­04-­23",
        "variation_id" : "EUR_1",
            "variations" : {
                "USD_2": {
                "price_currency_code" : "USD",
                "availability" : "InStock",
                "price" : 12.00,
                "list_price" : 15.67
            },
            "GBP_3": {
                "price_currency_code" : "GBP",
                "availability" : "OutOfStock",
                "price" : 20.00,
                "list_price" : 21.99
            }
        },
        "google_category" : "shirts",
        "gtin" : "example123",
        "condition" : "new",
        "age_group" : "adult",
        "gender" : "unisex",
        "inventory_level" : 25,
        "supplier_cost" : 1312.96
    }
]

Updates or create. Updates existing product. If the product does not exist product is created. Endpoint operates in asynchronous mode.

Method Endpoint
POST https://api.nosto.com/v1/products/upsert

Payload

Requests body can contain one or more products. Data formats in the payload follow the structure and specification of Nosto tagging for product guide.

Product Thumbnails

Update product

Updates products from updateProductsPayload.json (you can use the contents from upsert example).

curl "https://api.nosto.com/v1/products/update"
     --user :API_PRODUCT  
     -X POST
     -v
     -q
     --header "Content-Type: application/json;charset=UTF-8"
     --data-binary '@updateProductsPayload.json'

Updates the product (if it exists), otherwise product is skipped. Action only updates product information, product image are not updated.

Method Endpoint
PUT https://api.nosto.com/v1/products/update

Payload

Requests body can contain one or more products. Data formats in the payload follow the structure and specification of Nosto tagging for product guide.

Product Thumbnails

Errors

Invalid payload which is missing required name field.

[
  {
    "product_id" : "1",
    "price_currency_code" : "EUR",
    "availability" : "InStock",
    "categories" : ["sale/summer", "shirts"],
    "description" : "Example description",
    "list_price" : 12.34,
    "brand" : "Example Brand",
    "tag1" : ["red", "green"],
    "tag2" : ["women"],
    "tag3" : ["Foldable"],
    "date_published" : "2013-04-23",
    "price" : 10.23
  }
]

Error message for the previous payload

{
    "type": "has_errors",
    "message": "Failed to upsert some products; see errors",
    "errors": [
        {
            "productId": "1",
            "errors": "name field is missing (name), "
        }
    ]
}

Products API is verbose as it can when it comes to errors. Response will try to tell what field id(s) of the products with errors. Note that we typically respond with 200, even if some products might have errors. Please always check the response for possible products with invalid information.

Invalid payload

Products API will always respond. In case of missing fields or fields with invalid content the error message will try to tell where the problem is.

Exchange Rates

Example of exchange rates setting payload

{
  "rates": {
    "GBP": {
      "rate": 0.77,
      "price_currency_code": "GBP"
    },
    "EUR": {
      "rate": 0.91,
      "price_currency_code": "EUR"
    }
  },
  "valid_until": "2015-02-27T12:00:00Z"
}
# You can test the exchange rates API with curl.
curl "https://api.nosto.com/exchangerates"
    --user :NOSTO_API_TOKEN 
    -X POST 
    -v
    --header 'Content-Type: application/json;charset=UTF-8' 
    --data '{"rates": {"GBP": {"rate": 0.77, "price_currency_code": "GBP"}, "EUR": {"rate": 0.91, "price_currency_code": "EUR"}}, "valid_until": "2015-02-27T12:00:00Z"}' 

Exchange rates API let you setup API calls between your system and Nosto to inform our services about the exchange rates currently in use on your website. The exchange rates must be included as a JSON message and an HTTPS request must be executed.

In the json example, 0.77 is the exchange rate to get the price value in British pound from US Dollar and 0.91 is the exchange rate to get the price in Euro from US Dollar.

The valid_until entry defines the expiring date. When the expiring date is reached, the exchange rates won’t by applied anymore and prices will be hidden for all the secondary currencies. This is a security process to prevent displaying outdated prices. When Nosto recommendations are loaded, exchange rates are dynamically applied to the price variable in use in the recommendation templates. The variable is $!product.price.

Required headers

Header Value
Content-Type: application/json;charset=UTF-8

Error responses

HTTP Error Code Meaning
400 Bad Request – Bad request syntax, extra parameters or missing parameters.
401 Unauthorized – API key missing or invalid.
404 Not Found – The requested item doesn’t exist.
409 Conflict – The request failed because of a conflicting condition (for example trying to create an account with an existing account id).
500 Server error – Our servers are experiencing some problem.

Errors are in following JSON format

{ 
    "type":"unauthorized", 
    "message":"Invalid API Token" 
}

Nosto API always responds with a JSON payload, even for errors. The JSON object in error response has following fields:

Error type Descriptions
bad_request Request was missing parameters or had bad parameters, message will tell more information about the problem
unauthorized Invalid API Token
not_found Requested item doesn’t exist
server_error API servers are experiencing some problem

JavaScript

If you are implementing Nosto, please visit our Installation Guide. This Javascript API is used to extend an existing Nosto installation.

When to use the Nosto JavaScript API

In most implementations there isn’t any need to use the Nosto JavaScript API and the normal tagging implementation approach will work best and it’s the easiest to implement. Typically calling the API should be approached only after the normal tagging implementation has been done and now needs to be extended with something that doesn’t come out of the box.

The JavaScript API is useful mostly in cases where the store is doing something dynamic and not reloading the page. For example showing recommendations in a product quick view, that opens the product in a css overlay via Ajax. Another case is when the whole store is implemented as a single page application.

Prerequisites for using the Nosto Javascript API

# Example only in JavaScript
// Example only in JavaScript

Check that JavaScript API is available

nostojs(function(api){ console.log("API is functional"); });

Initialise Nosto Javascript API Stub

//Create a stub called nostojs to access Nosto JS API
(function(){
 var name="nostojs";
 window[name]=window[name]||function(cb){(window[name].q=window[name].q||[]).push(cb);};
})();
//Your code using the Nosto JS API
//...

JavaScript API works only in on-site context. Using the API does not require authentication but requires that Nosto embed script is included.

Nosto embed script needs to be recent enough. The easiest way to check that you are using a recent version enough, is to view your site’s html source and make sure it includes the text nostojs.init. In case that is there you are using the version that supports the Nosto Javascript API.

If you are using Nosto with a async script tag (AKA Direct Include), then you must add a javascript stub as an inline script block before you call the Nosto Javascript API (see the Javascript examples). You do not need to call nostojs.init() when using Direct Include.

Using the stub ensures that your code will be executed correctly even if you call the Nosto JS API before the Nosto script has loaded.

Initialize Nosto

Function is responsible of initializing Nosto. Note that this function is not available in nostojs object when using Direct Include. Nosto is initialized automatically when using Direct Include and you can simply omit this part when using Direct Include.

# Example only in JavaScript
// Example only in JavaScript
nostojs.init("nostoAccountId");
Parameter name Type  Description
account string  Nosto account
options object
optional
Option object to configure initialisation.

Parameter - options

Field name Type  Description
disableAutoLoad boolean Disable Nosto script auto-load
# Example only in JavaScript
// Example only in JavaScript
nostojs.init("nostoAccountId", {disableAutoLoad:true});

To delay Nosto recommendation loading, set disableAutoLoad to true.

Loading Nosto recommendations manually

By default Nosto loads the recommendations as soon as the site’s DOM is readable. In some use cases Nosto needs to be loaded manually. This is done by using a manual call

# Example only in JavaScript
// Example only in JavaScript
nostojs(function(api){
  api.loadRecommendations();
});

Refreshing page recommendations

Use api.loadRecommendations() to refresh page recommendations. The call refreshes the recommendations on the page and reports a new page view or product view if the page’s DOM contains the product tagging. Which recommendations to update will be searched from the page DOM by finding all elements where the class is “nosto_element” and then getting their id attributes.

The call accepts an optional parameter, but in most cases that parameter is not required. Add the optional parameter only if the reason to reload new recommendations is the result of clicking an existing recommendation and some new product was loaded. A typical use case where this would be the case is when a recommendation has a quick view button that dynamically loads a new product into a css overlay with ajax.

# Example only in JavaScript
// Example only in JavaScript

Refreshes the recommendations on the page and reports a new page view or product view if the page’s DOM contains the product tagging. Which recommendations to update will be searched from the page DOM by finding all elements where the class is “nosto_element” and then getting their id attributes.

nostojs(function(api) {
  api.loadRecommendations();
});

When a product page view is initiated from Nosto element, notify Nosto so that recommendation click is tracked correctly.

nostojs(function(api) {
  api.loadRecommendations({markNostoElementClicked: "nosto­categorypg­1"});
});
Parameter name Type  Description
options object
optional
Option object to configure loadRecommendations() call.

Parameter - options

Field name Type  Description
markNostoElementClicked string Use when you want to report a new product page view and attribute it as resulting from a click on the given Nosto recommendation div id.

Sending customer information

# Example only in JavaScript
// Example only in JavaScript
// Push customer information to current visit, if not present in tagging
nostojs(function(api) {
  api.customer({ email:"jane.doe@example.com", first_name:"Jane", last_name:"Doe", marketing_permission: true });
});

Use api.customer() function to send information about the current customer to Nosto. After the information is sent, current visit is updated with latest details.

Field name Type Description
email string Email address
first_name string First name
last_name string Last name
marketing_permission boolean Marketing permission to send marketing emails. Field alias: newsletter

Typical situation when manual update is needed if your site handles login with AJAX compared to regular implementation where login requires a page load and the following page includes customer tagging.

Sending add to cart events to Nosto from “add to cart” click handler function

To support AJAX implementation of add to cart functionality inside product recommendations, the on-click handler of the add to cart button needs notify Nosto that a product was added to cart from a Nosto recommendation. The api call is only for informing Nosto about the attribution (that the product was added from the recommendation), normal cart tagging should be used to tell Nosto the user’s cart contents.

Field name Type Description
productId string The Product ID of the product that was added to the cart
divId string  Recommendation slot’s divId where the add to cart button was clicked
# Example only in JavaScript
// Example only in JavaScript
// use case: recommendation with add to cart button, call from button's clickhandler.
// Sets the attribution that the given product was added to cart from a Nosto recommendation. 
// Note: This call does not update the shopping cart information itself, that should 
// be done through the cart tagging which tells Nosto the current items in the cart.
nostojs(function(api){
  api.recommendedProductAddedToCart("productId1", "nosto-categorypage-1");
});

Sending a product view events to Nosto

# Example only in JavaScript
// Example only in JavaScript
nostojs(function(api){
   var request = api.createRecommendationRequest();
   request.addEvent('vp', "productId3");
   request.loadRecommendations();
});

The example above creates a new request, adds view product event for productId3 and sends the event to Nosto. Since the request did not specify any recommendation slots, this request only submits view event to Nosto. Below is a bit more complex example which makes use of other aspects of the Nosto request to achieve different behaviour.

Updating shopping cart information

# Example only in JavaScript
// Example only in JavaScript

Call will read the page’s tagging information again and send it to Nosto. If the shopping cart information is tagged on the page, it will also update the visitor’s shopping cart.

nostojs(function(api){
  api.sendTagging();
});
# Example only in JavaScript
// Example only in JavaScript

In case you want to update Nosto about only a small part of the page, you can also include the root element’s ID as a parameter to the call:

nostojs(function(api){
  api.sendTagging("smallcart");
});

Some stores user AJAX to load their shopping cart information. In these cases the normal way how Nosto reads the shopping cart information might not work because the shopping cart is not available on the page when Nosto is reading the tagging from the page.

To make sure Nosto works with your AJAX shopping cart, include the Nosto cart tagging to your dynamically loaded shopping cart element and execute the following script after the element has loaded:

Parameter Type  Description
divId string : optional  Id of the div containing information to extract.

Pop-ups

# Example only in JavaScript
// Example only in JavaScript
nostojs(function(api) {
  var arrayOfPopupCampaigns = api.popupCampaigns();

  // arrayOfPopupCampaigns = [
  //   { id: "campaignId", name: "campaignName", type: "triggerType" },
  //   ...
  // ];

  var popupCampaignId = arrayOfPopupCampaigns[0].id;

  api.openPopup(popupCampaignId);

  // or

  var popupOptions = {
    // Effects corresponding to the ones in the admin UI
    effects: {
      overlayOpacity: 0.8,
      fadeInDelayMs: 300
    },
    preview: false
  };
  api.openPopup(popupCampaignId, popupOptions);  
});

You can open up a Nosto behavioral pop-up by calling the api.openPopup() function. The first argument of the function is the ID of the popup campaign whose pop-up you want to show. The pop-up campaigns, including the pop-up templates themselves, are created in the Nosto Administration UI

Please note that some campaigns have active trigger types and can be opened automatically. If you want to use only the api.openPopup() call to open pop-ups, please create the respective campaigns using the JavaScript API pop-up trigger type.

You can also give a second, optional argument to the api.openPopup() function. The second argument is an object with the following fields:

Field Type Description
effects object Describes the effects that should be used displaying the pop-up. If given, overrides the effects set up for the campaign in the Nosto Administration. See below for the description of the effects object.
preview boolean If true, an actual discount coupon won’t be given and the pop-up display won’t count in the analytics. Use this to preview the pop-up on your site.

The effects object:

Field Type Default in new API campaigns Description
overlayOpacity number 0.8 How opaque, or non-transparent, the background should look like when showing the pop-up. Value can range from 0.0 to 1.0
fadeInDelayMs number 0 How many milliseconds to take to fade in the pop-up.

You can get a list of available pop-up campaigns with the api.popupCampaigns() call. The list will have objects with the following fields:

Field Type Description
id string The pop-up campaign ID
name string The name of the pop-up campaign
type string The trigger type of the pop-up campaign.

Opening and then interacting with the pop-up trigger various callbacks. Please see the Callbacks section below for the available ones.

Popups can also be enabled and disabled in the scope of the page using api.enablePopup(popupCampaignId) and api.disablePopup(popupCampaignId). The original trigger and condition will still be considered, but the enabled flag will be overriden based on the function call.

Callbacks

To register listener to a callback, use api.listen(callbackId, callbackFunction).

# Example only in JavaScript
// Example only in JavaScript

Following code attaches console.log messages to postrender callback.

  nostojs(function(api){
   api.listen("postrender", function(nostoPostRenderEvent) { 
     console.log("Callback");
    });
  });
Parameter name Type  Description
callbackId string  Callback id.
callbackFunction function User provided callback function.

Callback - postrender

# Example only in JavaScript
// Example only in JavaScript

Following script executes at the post-render callback. which is called right after Nosto has responded with recommendations.

nostojs(function(api){
    api.listen('postrender', function(nostoPostRenderEvent){
        console.log(nostoPostRenderEvent.filledElements);
        console.log(nostoPostRenderEvent.unFilledElements); 
    });
});

Post render callback is useful in situations when recommendation markup is rendered client-side (Browser) e.g. with customization that are simpler to handle client-side.

// Extract recommendation 
(function () {
    // Callback which connects to postrender callback
    // loads the raw data from recommendations,
    // and finally converts the data to JSON object.
    function exampleCallHandler(filledElements) {
        // Extract the data from nosto DIV
        var data = document.getElementById("nosto-recommendation-example");
        var jsonObject;
        if (data) {
            jsonObject = JSON.parse(data.textContent);
            ExampleRecommendationDecorator.decorateNostoSlot("nosto- recommendation - example", jsonObject);
        }
    }

    // Register the handler to post render
    nostojs(function (api) {
        api.listen("postrender", function (NostoPostRenderEvent) {
            exampleCallHandler(NostoPostRenderEvent.filledElements);
        });
    });
})();

Called when Nosto has responded and finished recommendation placement.

Field name Type  Description
filledElements array<string> Contains a list of recommendation slots that contain recommendations.
unFilledElements array<string> Contains a list of recommendations slots that did not have get recommendations.

Callback - emailgiven

# Example only in JavaScript
// Example only in JavaScript

Following code attaches console.log messages to emailgiven callback.

nostojs(function(api){
  api.listen("emailgiven", function(emailSubscriptionEvent){
  console.log(emailSubscriptionEvent.email);
  console.log(emailSubscriptionEvent.newsletter);
  });
});

Whenever customer has input their email address into a Nosto behavioral pop-up that asked whether they want to subscribe to an email newsletter.

Field name Type  Description
email string The email address in the user input.
newsletter string Whether the user gave their consent to subscribing to a newsletter. E.g. either the pop­up prompting for the email address input was worded similarly to “Please enter your email address to subscribe to our newsletter:” or there was an explicit checkbox that the user checked to give their consent.

Callback - popupOpened

# Example only in JavaScript
// Example only in JavaScript

The following example outputs the event information about the opened popup to the console.

  api.listen("popupOpened", function(popupEvent) {
    if (popupEvent.error) {
      console.error(popupEvent.error);
    } else {
      console.log(popupEvent.campaignId);
      console.log(popupEvent.type);
    }
  });

The callback will be called whenever a Nosto behavioral pop-up is opened for the first time or failed to be opened. The callback is called in cases in which the pop-up is triggered automatically and in cases where it’s triggered via the openPopup() API call.

Field name Type Description
error string Description of the error in the case the pop-up failed to open. undefined if no error occurred.
campaignId string The pop-up campaign ID. All available IDs can be found through a call to the popupCampaigns() API call.
type string Type of the trigger that opened the pop-up. See the table below.
Pop-up type Description
newCustomer Pop-up is shown to customers during their first session.
exitIntent Pop-up is opened because customer was about to leave the site.
allCustomers Pop-up is shown to all customers.
externalCampaign Pop-up was opened due to a URL query parameter set by an external campaign.
abandonedCart Pop-up was opened because the customer’s email address was unknown, they had items in their shopping cart, and were about to leave the site.
api Pop-up was opened by the openPopup() API call.

Callback - popupRibbonShown

# Example only in JavaScript
// Example only in JavaScript

The following example outputs the event information about the shown pop-up ribbon to the console.

  api.listen("popupRibbonShown", function(ribbonEvent) {
    console.log(ribbonEvent.campaignId);
  });

The customer can minimize a Nosto behavioral pop-up into a ribbon to be shown at the edge of the viewport. The pop-up is also changed to be shown in its minimized ribbon form after a page load is done after a pop-up has been shown.

This callback will be called whenever the ribbon is rendered onto screen after a page load.

Field name Type Description
campaignId string The pop-up campaign ID. All available IDs can be found through a call to the popupCampaigns() API call.

Callback - popupMinimized

# Example only in JavaScript
// Example only in JavaScript

The following example outputs the event information about the minimized pop-up to the console.

  api.listen("popupMinimized", function(popupEvent) {
    console.log(popupEvent.campaignId);
  });

The customer can minimize a Nosto behavioral pop-up into a ribbon to be shown at the edge of the viewport. This callback will be called when the customer clicks the minimize button on the pop-up.

Field name Type Description
campaignId string The pop-up campaign ID. All available IDs can be found through a call to the popupCampaigns() API call.

Callback - popupMaximized

# Example only in JavaScript
// Example only in JavaScript

The following example outputs the event information about the maximized pop-up to the console.

  api.listen("popupMaximized", function(popupEvent) {
    console.log(popupEvent.campaignId);
  });

The customer can minimize a Nosto behavioral pop-up into a ribbon to be shown at the edge of the viewport. When they click on this ribbon, the pop-up will be maximized again to be shown in full size. This callback will be called when the customer clicks the ribbon to maximize the pop-up.

Field name Type Description
campaignId string The pop-up campaign ID. All available IDs can be found through a call to the popupCampaigns() API call.

Callback - popupClosed

# Example only in JavaScript
// Example only in JavaScript

The following example outputs the event information about the closed pop-up to the console.

  api.listen("popupClosed", function(popupEvent) {
    console.log(popupEvent.campaignId);
  });

The customer can click a “close permanently” button or link in a Nosto behavioral pop-up to dismiss the pop-up permanently. This callback is called when the customer clicks on that button or link.

Field name Type Description
campaignId string The pop-up campaign ID. All available IDs can be found through a call to the popupCampaigns() API call.

Callback - couponGiven

# Example only in JavaScript
// Example only in JavaScript

The following example outputs the event information about the give coupon to the console.

  api.listen("couponGiven", function(couponEvent) {
    if (couponEvent.error) {
      console.error(couponEvent.error);
    } else {
      console.log(couponEvent.campaignId);
      console.log(couponEvent.couponCode);
      console.log(couponEvent.origin);
    }
  });

The callback will be called when a customer clicks a button inside a Nosto behavioral pop-up to get their discount coupon code.

Field name Type Description
error string Description of the error in the case the coupon was failed to be given. undefined if no error occurred.
campaignId string The pop-up campaign ID. All available IDs can be found through a call to the popupCampaigns() API call.
couponCode string The coupon code given.
origin string Where the coupon code originated from. Always popup.

Callback - sendabandonedcartemail

# Example only in JavaScript
// Example only in JavaScript

The following example outputs the event information about the event to the console.

  api.listen("sendabandonedcartemail", function(sendMailEvent) {
    if (!sendMailEvent.sent) {
      console.error(sendMailEvent.message);
    } else {
      console.log(sendMailEvent.campaignId);
      console.log(sendMailEvent.email);
    }
  });

The callback will be called when a customer clicks a button inside a Nosto abandoned cart pop-up to get an abandoned cart email.

Field name Type Description
sent boolean Whether the email was successfully sent
campaignId string The pop-up campaign ID. All available IDs can be found through a call to the popupCampaigns() API call.
email string Target email address.
message string Error message

Creating requests manually

In addition to API function calls Nosto client API provides a way to create recommendation requests manually. In this approach the caller has to create the request and specify the request content.

Use api.createRecommendationRequest() to create request object. With request API you first create the full request object. Once the object is complete api.loadRecommendations() is used for making the actual HTTP request.

# Example only in JavaScript
// Example only in JavaScript

To create manual requests, first thing is to create a recommendation request object.

nostojs(function(api){
  var request = api.createRecommendationRequest();
});

Following example creates a new request, adds view product event for productId3 and sends the event to Nosto. Request did not specify any recommendation slots, this request only submits view event to Nosto.

nostojs(function(api){
  var request = api.createRecommendationRequest();
  request.addEvent('vp', "productId3");
  request.loadRecommendations(request);
});

Following is a more complex example which submits more information in single request to Nosto.

nostojs(function(api){
   var request = api.createRecommendationRequest();
   request.addElements(["nosto-product-page1", "nosto-product-page2"]);
   //if viewed from nosto element, add element's id as 3rd. parameter
   request.addEvent('vp', "productId3", "nosto-categorypage-1");
   request.addCartItems(["productId1", "productId2"]);
   request.loadRecommendations();
});

Request object API

API function  Description
addEvent(event_type, product_id, slot_reference)  Adds event to Nosto request
addCartItems([product_id_1, ..., product_id_n])  Adds cart items to request
addElements([element_id_1, ..., element_id_n])  Adds recommendation slots to request. Response will include recommendations for these slots.
loadRecommendations() Calls Nosto API

Parameter specifications

Field name Type  Description
event_type string Nosto event type.
product_id_n string Product ID
element_id_n string Element ID matching a slot in Nosto
slot_reference string Recommendation slot reference

Supported event types

Event type Description
vp View product event

Examples

This section is dedicated to show some of the more advanced use cases for JavaScript API in form of examples.

Nosto Backup Recommendation Element

Consider following HTML

<div id="UserHistory" class="nosto_element"></div>
<div id="nostoBackupElement-UserHistory" style="display: none;">
<div id="TopViews" class="nosto_element"></div>

The JavaScript will then be

 <script type="text/javascript">
   // <![CDATA[
   nostojs(function(api){
    api.listen("postrender", function(postRenderElements){
     for(var i=0;i<postRenderElements.unFilledElements.length;i++){ 
      var unfilledElement=postRenderElements.unFilledElements[i]; 
      var backupElement = document.getElementById("nostoBackupElement-"+unfilledElement); 
      if(backupElement){ 
       backupElement.style.display="block"; 
      } 
     } 
    }); 
   });
   // ]]>
  </script>

Using Nosto’s JavaScript API, one can show elements depending on which elements are available. Consider that we want to show the UserHistory element if the user is returning, or the TopList element if the user is new.

A simple way to do this, is to place the TopList element in a hidden <div>, then using the postrender listener, show the TopList element if the UserHistory is not filled.

In this example, all you need is to put the backup element in a hidden div with the id being nostoBackupElement­{NameOfPrimaryElement}.

Point of Sale Purchases

With point of sales (POS) API you can send purchase information to Nosto from your POS systems (typically via POS system backend). Offline purchases can then be taken into account when generating online recommendations (e.g. omit already bought items) or in post-purchase activities like sending triggered emails (such as order follow up).

Identifying & matching customers

For Nosto to be able to connect customer’s purchase data from a physical point of sale with his behavior data from online store there needs to be a customer specific ID (customer reference) which is known by both the POS system and the e-commerce platform serving the online store that has Nosto tagging in place.

Nosto receives customer ID as part of the customer tagging via customer_reference tag (see the tagging guide).

Matching the product catalogs

Like with the customer ID the product IDs or GTINs (Global Trade Item Number) that are sent as part of the purchase items must match with the product IDs or GTINs in Nosto. If the IDs do not match there is no way for Nosto to know how products from the catalog of a physical store should be mapped with the product catalog of the online store.

Send purchase information

Method Endpoint
POST https://api.nosto.com/v1/receipt

Sends purchase information

# Create a file with payload from following example and pass the name of the file
# after '@' character. 

curl "https://api.nosto.com/v1/receipt"
     --user :API_POS
     -X POST
     -v
     -q
     --header "Content-Type: application/json;charset=UTF-8"
     --data-binary '@posPurchaseExample.json'

Example of POS purchase request body

{
  "order" : {
    "info": {
      "order_number": "1445",
      "email": "john.doe@example.com",
      "first_name": "John",
      "customer_identifier" : "14d9912a2b57da27",
      "type" : "order",
      "order_date" : "2016-03-11T07:29:44.028Z"
    },
    "items": [
      {
        "product_id": "2256",
        "name": "Sweater",
        "quantity": 1,
        "unit_price_with_vat": 269,
        "unit_price_without_vat": 209.82,
        "price_currency_code": "EUR",
        "description" : "Comfortable sweater.",
        "gtin" : "3234567890126"
      },
      {
        "product_id": "33224-1",
        "name": "Gray Gloves",
        "quantity": 1,
        "unit_price_with_vat" : 19,
        "unit_price_without_vat" : 14.82,
        "price_currency_code" : "EUR",
        "description" : "Gray gloves.",
        "gtin" : "3001234567892"
      }
    ]
  },
  "meta" : {
    "pos_id" : "1",
    "pos_description" : "Helsinki city center outlet"
  }
}

The order info object

Attributes Type Description
order.info object Order information.
order.info.order_number string Order number.
order.info.email  string Customer’s email address. (optional)
order.info.first_name  string Customer’s first name.
order.info.customer_identifier  string Customer identifier.
order.info.order_date  string Date and time of purchase .

The order items object

Attributes Type Description
items object[]  Order items.
item.product_id string  Item id.
item.name string  Item name.
item.quantity integer  Item quantity.
item.unit_price_with_vat number  Unit price with VAT included. (optional)
item.unit_price_without_vat number  Unit price without VAT.
item.price_currency_code string  Currency code in ISO 4217 format e.g. “EUR”.
item.description string  Item description. (optional)
item.gtin string  Global Trade Item Number. (optional)

The order meta object

Attributes Type Description
meta  object  Information about the point of sales system.
meta.pos_id  string  Point of sales identifier.
meta.pos_description string  Description of the point of sales system.

GraphQL

GraphQL is a query language for APIs. What does this mean for you? Unlike regular SOAP or REST APIs, GraphQL gives you the ultimate flexibility in being able to specify in your API requests specifically what data you need, and get back exactly that.

As a query language, it provides you with a lot of flexibility that most normal APIs will not. Without needing to recreate endpoints, you can provide developers with the same functionality as a bulk endpoint. Your queries will be cleaner and easier to understand by combining multiple queries into one request.

What’s the difference between Nosto’s GraphQL API and the REST API?

The regular API is very well structured and specifically defined. The endpoints have their set requests and responses and that’s what you get whether or not that matches your usage pattern. GraphQL let’s you control all of this so that the way you consume the data matches exactly what you need.

This is both a pro and a con. If your use case does not require all of the data, GraphQL can speed up your requests as we do less work on the server-side to fulfill those requests. Conversely, if you need all of the data in one request, your requests could slow down as we do more work to fulfill these requests.

Should I use GraphQL over the regular API?

Currently you are unable to access the recommender data over the regular REST APIs. If you use-case requires access to the raw recommender data, you will require access to the GraphQL API.

How do I use Nosto’s GraphQL API?

First, you’ll need to create a client and join the beta program. Once you’ve done this, follow our instructions to authenticate against the API. Both GraphQL and the regular API use the same authentication both will be interchangeable inside your app.

After you’ve got your access token, you can start querying the API.

An API_APPS token is required for accessing the following endpoints.

Making Requests

There are a few different ways to make requests into the GraphQL API:

Using client libraries * Sending JSON * Sending raw GraphQL queries * Using client libraries

Client libraries will provide you with the fastest and most comprehensive way to access the API and can assist in handling auth, formatting your requests and your responses.

The Apollo client libraries are available for:

Additional clients are available for:

Sending JSON GraphQL queries

You can send your GraphQL requests as JSON to our API and have it correctly interpolate variables passed into it. To do so, set the Content-Type header to application/json.

Method Endpoint
POST https://api.nosto.com/v1/graphql
curl -0 -v -X POST https://api.nosto.com/v1/graphql \
-u ":<token>" \
-H 'Content-Type: application/json' \
-d @- << EOF
{
  "query": "query { recos (preview: false, image: VERSION_7_200_200) { toplist(hours: 168, sort: BUYS, params: { minProducts: 1 maxProducts: 10 } ) { primary { name productId } } } }"
}
EOF

Sending raw GraphQL queries

If you want to send raw GraphQL queries to the API, you can still do so but you must set the Content-Type header to application/graphql.

Method Endpoint
POST https://api.nosto.com/v1/graphql
curl -0 -v -X POST https://api.nosto.com/v1/graphql \
-u ":<token>" \
-H 'Content-Type: application/graphql' \
-d @- << EOF
query {
  recos (preview: false, image: VERSION_7_200_200) {
    toplist(hours: 168, sort: BUYS, params: {
      minProducts: 1
      maxProducts: 10
    }) {
      primary {
        name
        productId
      }
    }
  }
}
EOF

Best practices

For email service providers (ESP)

Preparing to send emails with Nosto content

Requesting content from 3rd party service, like Nosto, request round trip will impact the time your sending process takes. Adjusting your fetch strategy to your needs will reduce the effect of this impact.

Optimize your templates responsible of rendering API responses.

Note that query cannot exceed than 4096 characters. If it does, the request will fail.

For large user bases

Handling situations when there is no recommendation content available

Request API Access

To get access to our APIs, please log in to your Nosto account at https://my.nosto.com and contact support via chat. When you request API access, please provide following information:

Contact Nosto

If you have any questions or need help in using Nosto API please be in touch with our support. The Best way to contact Nosto support is by logging in to your Nosto account at https://my.nosto.com and contact support via chat.

More details on contacting our support can be found in Nosto support page.