Send Docs Feedback

Recommendations tutorial

This tutorial is to support existing Insights customers. Insights is not available for new sign-ups.

This tutorial, based on the Recommendations sample app, illustrates how you can use prediction data from an Insights model to make product recommendations to mobile app users. The app integrates Insights predictive modeling with the Apigee data store, exposing the result to client apps through an API.

Using Insights-generated prediction data to improve the experience for a client app's users is one way to make an app adaptive. With the data, you can adapt a client app with features based on changing user and market characteristics.

Recommendations are a way to suggest products to customers based on the kinds on data you've collected about what customers are interested in. The following example shows suggestions for someone who's purchased a particular kind of camera:

This tutorial includes the following sections:

  1. Overview
  2. Data
  3. Customer journey
  4. Predictive model
  5. Recommendations API
  6. Next steps

About the Recommendations app you're building

In the Recommendations application you build here, a retail client app retrieves product lists and information specific to a user. The app’s particular value -- recommendations based on the user's activity -- comes from behind-the-scenes predictive analytics from the user’s activity history data. Predictions for the user’s likely purchases comes from what they’ve bought (or been interested in) in the past. You generate that data by telling Apigee Insights which pieces of user histories to consider.

This tutorial shows you how the app works and how to build it on your own so you can adapt and extend it. In this tutorial, you'll create new source code files using code from the Insights sample GitHub repository. If you're familiar with GitHub, you can clone the repository containing the Recommendations app source code. If you're not familiar with GitHub, you can download code as described in the tutorial.

Overview

What you'll need

In this introductory tutorial, you’ll use technologies such as JavaScript (on Node.js), R script (a language for statistical modeling), and JSON. The tutorial includes all of the code you’ll need, so you won’t need to write any. If you’re unfamiliar with those technologies, you can use the code to learn how the pieces fit together.

You’ll also need to have access to the following resources and Apigee products. Details on how to access or install (on your client) these capabilities are provided in the tutorial:

  • Apigee Insights -- A platform for performing journey analytics and predictive analytics using very large amounts of data about actors (such as customers) and their behavior.
  • R and RStudio -- The R language is used by many data scientists for statistical analysis. You’ll use the R language in the RStudio IDE to create a predictive model from data, then make recommendations based on the results.
  • Apigee API BaaS -- A cloud-based backend-as-a-service (BaaS). In particular, you’ll be using the data store to hold data you return to the client app.
  • Apigee-127 -- A toolkit for building APIs on Node.js on your laptop. With a little JavaScript and a text file for configuration, you’ll expose an API that clients can use to retrieve product recommendations.
  • Node.js -- A platform for writing server-side JavaScript. You install this in order to install Apigee-127.
  • GitHub -- A source code repository. You don’t need to have a GitHub account, but you’ll be going to GitHub in a browser to get code for the tutorial.

App architecture

This tutorial walks you through assembling the Recommendations sample app in the Insights samples GitHub project. It’s an abbreviated view of how you’d build an adaptive app from Insights analysis results.

The diagram below maps out the app’s pieces and the flow of data among them. The order is more or less how they’re presented in this tutorial.

  1. Browse data. You start using Insights by importing event and profile data. You can browse the data in the Insights console.

    Events from across multiple datasets are merged into a sequential stream. These are correlated with users (from profile data) to create a picture of user activity.

    For this tutorial, the data’s already there, included with a new Insights account.

  2. Visualize event paths. For a picture of past user behavior, you visualize event paths. This gives you a picture of the customer journey you can explore and export user data from.

    Visualization takes merged, sequential event data and presents it as paths you can expand. So for a path ending with a purchase, you can see what user events preceded.

  3. Predictive model. Using the R language and the Insights R SDK, you build a predictive model from the imported data.

    R is a language used by many to perform statistical analysis. Here, you use it to configure a predictive model that finds user event patterns leading to a purchase.

    For this tutorial, the model’s already built and included for you. You can use it to get the score data you need.

  4. As you refine your model, its score data is saved in Insights.

    If you create multiple scores through modeling with R, they’re all saved in Insights for access later. You can view information about them in the Insights console.

  5. Export predictive model scores. You export predictive model scores to a data store for use in making recommendations.

    Predictive modeling results in scores that predict a user’s propensity to purchase certain products. This is a great place to start for making product recommendations. By exporting the score data to API BaaS, you make it available to mobile apps.

  6. Add product data. You add product data for detail behind the score data.

    To the API BaaS application, you add data about products behind the scores you exported. That way, apps can display more product information associated with recommendations.

  7. Provide an API. You provide an API for accessing scores and product data from client applications.

    With an API layer built with Apigee-127, you can process raw data from API BaaS into something an app can use.

  8. Make calls to the API. You make calls to the API for recommendations.

With your new API up and running, you can test it with calls from the command line.

Data

When you use Insights, you start with data. In order to get a picture of the paths users have been following (customer journey analytics) or predict what they might be inclined to do in the future (predictive analytics), you work with data you’ve imported. Your Insights account already includes the data you’ll need for this tutorial.

Log in

You can start using Insights from its admin console. Log in to your account at https://accounts.apigee.com/accounts/sign_in

Browse the data

In a web browser, log in to the Insights console. On the Data tab, on the left side of the page, you can browse a list of catalogs. Catalogs group imported datasets to make it easier to select from multiple datasets when you're doing work in Insights.

In the left-hand pane, look inside the RetailDatasets catalog. Insights catalogs contain two kinds of datasets: event and profile datasets.

  • Event datasets -- such as Offer, Purchase, and StoreVisit -- each contain data about a kind of thing users have done, such as make purchases. Each row includes a timestamp and the user ID of the person the event is associated with. Timestamps make it possible for Insights to merge events from different datasets in order of time sequence to discover behavior patterns.
  • Profile datasets contain data about people. This includes a user ID (which connects people with events). It also often includes demographic information such as income level, marital status, and so on.

Click the Purchase dataset in the panel on the left. In the right-hand pane, you’ll see details about how Insights sees the data (such as what kind of dataset it is), and statistics about the content of the data imported.

At the bottom of the page, the Column Statistics tab gives you information about each column in the dataset. The Dataset Preview tab gives you a way to see a sample of the data that was imported.

Customer journey

You can analyze the customer journey from data in the Insights system. The concept of the customer journey is widely used in marketing these days to describe the customer experience. It’s a way to plot customer paths through interactions with a company and its products.

In this section, you’ll use a journey to visualize paths to a purchase.

Visualize a path

In this section, you’ll visualize a path from a journey that’s included with Insights. In this visualization, you’ll get a graphical view of user event paths that end with a purchase.

To visualize paths, you'll use a predefined journey.
  1. In the Insights console, click the Journey tab.
  2. In the list of journeys, find the CustomerJourneyByCategory journey.
  3. Hover your mouse over that journey's row to get the context menu, then click Visualize Path.

    The console displays the Path Visualizer, where you can choose how you want to start visualizing a path: Events, Start Events, End Events, or Choose Your Own.

    • Events -- Choose to visualize paths that begin or end with one of the most commonly occurring events.
    • Start Events -- View paths that start with an event that most often starts a path.
    • End Events -- View paths that end with an event that most often ends a path.
    • Choose Your Own -- From all events, choose the one that starts or ends the paths you're interested in seeing.
  4. Click the Choose Your Own box.
  5. Under Select Event, in the top dropdown, click Purchase.
  6. In the Select Value dropdown, click Purchase-Clothing.

    Here, you’re choosing the event value you want at the end of the path. So you’ll be visualizing events paths leading to clothing purchases.

  7. In the Select Event dialog, click Go Backwards in time, then click OK.

    The console displays boxes for each of the events that occur most often at the end of user paths. In other words, according to the data range included in the journey, paths most often end with these events. The numbers in each box show how many times that event occurs at the end of event paths followed by users.

    The stack of events that appear at the left are those that most often chronologically precede the Purchase event. In the top event, the number tells you that this particular StoreVisit > Purchase sequence occurs 813 times in the data selected for the journey you’re visualizing here.

  8. In the left-hand stack, click the left arrow for the StoreVisit (Clothing) event. You might need to click and drag one of the boxes to the right to make room.

    What you’re looking at are paths that Insights identified by merging events from across datasets, ordering them chronologically. The WebsiteVisit, StoreVisit, and Purchase events in the path highlighted below fall into this path because they most often occur in chronological order before a purchase.

  9. Click the leftmost box in the path.

    The popup shows details about the highlighted path that begins (chronologically) with this event and ends with Purchase (Clothing). For example, it shows that the path occurs 120 times in the data analyzed, making up 4.46 percent of the paths. The numbers for the PurchasePrice and ReturnPrice are sums for those event attributes across this path. In other words, in this path of three events, the purchase price total across its 120 occurrences is $143,091.

Predictive model

To make recommendations, the Recommendations application uses data generated from a predictive analytics model. In predictive analytics, historical data is used to figure out how likely something is to happen in the future. The goal of this model is to figure out how likely customers are to buy a product. The prediction score for each customer is used to proactively recommend those products to them within an app.

Developing a predictive model is usually an iterative process. You start with a model you think might be useful, try it with data, then adjust the model iteratively until it looks likely to predict reliably. One result of the model in this tutorial is a list of scores, one per product per user.

+--------+---------------------------------+---------+
|  user  |              node               |  score  |
+========+=================================+=========+
| 1e+06  | DowntownHungarianDownComforter  |  10.25  |
+--------+---------------------------------+---------+
| 1e+06  |   SuperiorGrandGourmetBasket    |  9.474  |
+--------+---------------------------------+---------+
| 1e+06  |          TimeSteveJobs          |  7.948  |
+--------+---------------------------------+---------+
| 1e+06  |   LondonFogHeritageTrenchCoat   |  7.664  |
+--------+---------------------------------+---------+
| 1e+06  |       CanonPowerShotSX501       |  6.99   |
+--------+---------------------------------+---------+
| 1e+06  |  CrystalPeelMicrodermabrasion   |  6.741  |
+--------+---------------------------------+---------+
| 1e+06  |     SmoothFitnessTreadmill      |  6.428  |
+--------+---------------------------------+---------+
| 1e+06  |     Mobil1SyntheticMotorOil     |  6.372  |
+--------+---------------------------------+---------+
| 1e+06  | WhirlpoolSidebySideRefrigerator |  5.981  |
+--------+---------------------------------+---------+
| 1e+06  |       SkipHopZooBackpack        |  4.785  |
+--------+---------------------------------+---------+

In addition to a sample dataset catalog, your Insights account includes a sample predictive model, score for the model, and model report. You can view information about the model on the Insights console Prediction tab.

When processing a predictive model, Insights merges data about events, correlates them with people, then identifies patterns leading to the outcome you specify. You set which event data to use by using an R script from your computer that configures and runs the model on the server. The output is a set of scores showing each user’s propensity to purchase each product.

The higher the score, the greater that user’s propensity to buy the product. So, in a model that is capable of producing very high scores, the 10 products with the highest scores are good bets to recommend.

With Insights, the model itself is produced on the server, but you configure and run it from a development machine. To create the model, you’ll use the RStudio IDE to edit code in the R scripting language. The R language is used by many data scientists for statistical analysis. It includes features to generate graphical elements, such as by plotting the results of analysis.

To work with the Insights server, you’ll use the Insights R SDK. It includes an R package that exposes insights predictive capabilities to R users.

Install R and RStudio

You’ll use the RStudio IDE to run your R code. RStudio is an open-source IDE for programming in R. You’ll need to install R first.

  1. If you haven’t already, install R.

    It’s best if you have the latest version; Apigee Insights requires version 2.9.0 or later.

    1. Visit the R download page.
    2. Click the link for your platform, then follow the instruction for your specific version to install R.
  2. If you don't have it, install RStudio.
    1. Visit the RStudio download page.
    2. Under the list of installers, find the version that’s right for your platform and use its link to download the installer.
    3. Run the installer to install RStudio.

Install sources and dependencies

To work with Insights predictive models, you'll need to install the Insights R package and a few dependencies it requires. You won't need to create the model here because the model you need was included when you set up your Insights account. But the model R code is provided so you can adapt it and experiment.

To get all of this -- scripts, Insights R package, and dependencies -- you can simply run an R script included with the samples.

  1. Start RStudio.
  2. In RStudio, create a new project and call it purchase-predict.

    You might find it useful to create the project in a directory you will use just for R code.

  3. Create a new R script in the new project by clicking File > New File > R Script.
  4. Go the following URL in the Insights samples repository and copy the file's contents.

    https://github.com/apigee/insights-samples/blob/master/cookbook/main.R

  5. In RStudio, paste the copied content into the script you created.
  6. Save the new file as main.R.

    main.R contains script that does the following.

    • Gets and installs the Insights R package.
    • Gets and installs dependency R packages.
    • Gets the sample code you'll need.
  7. Restart R by clicking Session > Restart R.
  8. With main.R in the RStudio editor, run the code by clicking the Source button above the code editor.

    After you've run main.R, your project should include the files and packages listed in the following screen shots from RStudio:

    Files:

    Packages:

After main.R has finished running, it should have opened the insights-connection-config file it downloaded. In the next section, you'll use that file to set connection parameters for working with the Insights server.

Run the R script to plot a predictive model’s report

Using a simple R script, you can get data and charts for predictive models already created on the server. Here, you’ll run a script that gets data from a model, score, and report included with your Insights account.

The script retrieves the data, prints summary output about it to the RStudio console, and plots charts that describe the underlying data.

When you’re creating models, charts are a useful alternative to looking at raw data. In the case of a predictive model, a chart can show you how effective a model is likely to be in predicting positive results.

You’ll use code from the tutorial sample’s git project to create a model.

  1. In RStudio, in the purchase-predict project you created, open insights-connection-config if it isn't already open.
  2. In the config file, edit the parameters to include your own connection information.

    Change the org and user params to your username (they should be the same value). Change the password param to your Insights password. Leave the host param as is.

    {
      "org":"your-insights-org-name",
      "user":"your-insights-username",
      "password":"your-insights-account-password",
      "host":"https://insights.apigee.net/api"
    }
  3. Save the config file.
  4. Open purchase-predict-plots.R, which was downloaded when you ran main.R.
  5. Run the script by clicking the Source button above the code window.

    The script will run to the end, streaming tables to RStudio's console window. R code like the following stream function prints the summary tables. To see its output again, put a cursor in the stream function such as the following, then click the Run button.

    cScore$stream(10)

    Table output for the first 10 scores for the first user looks something like the following. The table shows user IDs (user) mapped to a product (node) and the score for the user’s propensity to buy the product (a higher number means more likely).

    The user ID is shown in scientific notation (though you won’t need to translate it in order to use it). This table sorts users first to last numerically by ID. So the first 10 results are all the same user -- here, ID 1000000.

    +--------+---------------------------------+---------+
    |  user  |              node               |  score  |
    +========+=================================+=========+
    | 1e+06  | DowntownHungarianDownComforter  |  10.25  |
    +--------+---------------------------------+---------+
    | 1e+06  |   SuperiorGrandGourmetBasket    |  9.474  |
    +--------+---------------------------------+---------+
    | 1e+06  |          TimeSteveJobs          |  7.948  |
    +--------+---------------------------------+---------+
    | 1e+06  |   LondonFogHeritageTrenchCoat   |  7.664  |
    +--------+---------------------------------+---------+
    | 1e+06  |       CanonPowerShotSX501       |  6.99   |
    +--------+---------------------------------+---------+
    | 1e+06  |  CrystalPeelMicrodermabrasion   |  6.741  |
    +--------+---------------------------------+---------+
    | 1e+06  |     SmoothFitnessTreadmill      |  6.428  |
    +--------+---------------------------------+---------+
    | 1e+06  |     Mobil1SyntheticMotorOil     |  6.372  |
    +--------+---------------------------------+---------+
    | 1e+06  | WhirlpoolSidebySideRefrigerator |  5.981  |
    +--------+---------------------------------+---------+
    | 1e+06  |       SkipHopZooBackpack        |  4.785  |
    +--------+---------------------------------+---------+

    The script also prints charts to the RStudio Plots window. After the following lines of code run, three charts are created and displayed in succession in the Plots window.

    # Plot the gain,  lift, and "area under the curve" charts.
    cReport$plot("SkipHopZooBackpack", type="GAIN")
    cReport$plot("SkipHopZooBackpack", type="LIFT")
    cReport$plot("SkipHopZooBackpack", type="AUC")

    The AUC chart was created last, so it should still be visible in the Plots window.

    Click the Plots window’s Back button to view the charts that were created with the preceding lines of code.

Recommendations API

In this section, you’ll create a RESTful API that client apps can use to retrieve product recommendations. This is where you take the modeling work in Insights and put it to use in an app.

Clients will be able to get recommendations through an endpoint like the following, which will provide recommendations for user_id:

http://<hostname>:<port>/customers/<user_id>/recommendations

To keep things simple, the API you’re going to build will just get product recommendations from the API BaaS data store. But with some JavaScript, you could enhance the API to support client apps with more features.

In the following steps, you’ll put together these pieces:

  • Score and product data in API BaaS. You’ll export score data from Insights to API BaaS, then add product data.
  • Node.js and dependencies. Node.js is a platform for server functionality in JavaScript. It’s easily installed on your computer.
  • Apigee-127, a toolkit for building APIs locally on your laptop. You install Apigee-127 as a Node.js module.
  • An Apigee-127 project. A project gives you a place to put API pieces as you’re coding.

Exporting Score Data to API BaaS

Here, you’ll export score data from Insights to API BaaS, a Cassandra-based data store for fast access from apps. From API BaaS, your score data will be available to the recommendations API you’ll create.

You’ll need your API BaaS org name, client ID, and client secret. These are all available from the overview page of your API BaaS console.

  1. In a browser, go to the Insights console, then click the Prediction tab.
  2. In another browser window or tab, go to the API BaaS console for your Apigee account.

    For example, visit https://apigee.com/appservices and log in with your API BaaS credentials.

  3. In the Insights console Prediction tab, hover the mouse pointer over the RecommendationsModelScore, then click the context menu .
  4. In the context menu, click Export to API BaaS.
  5. In the Export to API BaaS dialog box, enter the following values:
    Setting Value
    Name of the Collection recommendationscores
    Data Connector Name UserGrid
    BaaS URL https://api.usergrid.com
    BaaS Org Name <Your API BaaS org name>
    BaaS App Name sandbox
    Client ID <Client ID value>
    Client Secret <Client secret value>

  6. Click Export.

    It might take 30 minutes for the export to finish. You will see the export job appear in the job list on the Jobs tab. Click Refresh to refresh the list.

    After the export finishes, you should see the recommendationscores collection show up in the API BaaS console.

    While you wait for the export to finish, you can move on to the following next steps in the tutorial (be sure to come back here):

  7. After your scores have been exported, go to the API BaaS console and select the Sandbox application to view your exported scores. In the left-hand pane, click Data, then click recommendationscores.

Add product data to API BaaS

You’ll need product data to go with recommendations. Putting that data in API BaaS makes it available for client requests from the API you’ll create.

You’ll import data as JSON available from the recommendations sample repository.

  1. View the contents of the products.json file by visiting the sample repository at the following URL:

    https://github.com/apigee/insights-samples/blob/master/apps/recommendations-app/data/products.json

  2. Copy the contents of this file and paste them into an empty text file.
  3. Save the new file as products.json.

    You can save the file anywhere you like as long as you can get at it later. You won’t need the file -- just the contents.

  4. Go to the API BaaS console for your Apigee account.

    For example, visit https://apigee.com/appservices and log in with your API BaaS credentials.

  5. In the API BaaS admin console, at the top left, make sure you have the Sandbox application selected from the dropdown.
  6. In the panel at the left, click Data.
  7. Under Collections, click the New collection button.
  8. In the Create new collection dialog, enter products, then click Create.
  9. Under Collections, click the name of the new collection.
  10. At the right, click the Create option, then paste the contents of the products.json file into the JSON Body box.
  11. Click Validate JSON to make sure that the JSON is well-formed. Fix errors if there are any.
  12. Click Run Query to create API BaaS entities in the data store from the JSON.

After this has completed, a list of the new entities should appear beneath the Run Query button. Click View Details for one of them to see the values you’ve added.

Set up Apigee-127

Before you can create the recommendations API, you’ll need to install Apigee-127. If you don’t have Node.js, you can install that first. Apigee-127 runs as a module of Node.js.

  1. Install Node.js.

    Apigee-127 is a module of Node.js. If you don’t yet have Node.js installed, you’ll need to install it before adding the Apigee-127 module.

  2. Install Apigee-127.

    Use the link on the Apigee-127 installation page to install the Apigee-127 module into your Node.js installation.

Create the recommendations API

Here, you’ll create a simple API that clients can call to get recommendations. To put the API together a little faster, you’ll copy code from a finished version of the API in GitHub. (You can also simply clone the samples repository to get the files.)

  1. On your local drive, create a directory to hold your Apigee-127 projects.
  2. Open a command prompt, change to the directory you created, then execute the following command (if you're on Mac or Linux, and depending on how you installed Node.js, you might need to prefix this with a sudo command):
    a127 project create recommendations-api

    This creates an Apigee-127 API project called recommendations-api. You’ll edit files here to define your API.

  3. Using a text editor, open package.json at recommendations-api/package.json. Edit the file to add dependencies for the async and usergrid modules (as shown in the following excerpt of the file), then save the file.

    This adds references to modules that the API will need, but which might not have been installed when you created the project.

    {
      "name": "recommendations-api",
      "version": "0.0.1",
      "private": "true",
      "description": "My new Apigee 127 Project",
      "keywords": [],
      "author": "",
      "license": "",
      "main": "app.js",
      "dependencies": {
        "express": "3.x.x",
        "a127-magic": "^0.7.0",
        "async": "^0.9.0",
        "usergrid": "^0.10.9",
        "volos-analytics-apigee": "",
        "volos-analytics-common": "",
    ...more omitted...

    Modules extend Node.js functionality. These are needed by the JavaScript that will be your API’s logic. In particular, the usergrid module gives your code a way to get data from API BaaS (which is based on the Usergrid open source project).

  4. In a command prompt, change to the recommendations-api project directory, then execute the following command:
    npm install

    The npm tool will look at your package.json file, installing referenced modules that aren't yet installed.

  5. In the command prompt, while in the recommendations-api project directory, execute the following command:
    a127 project edit

    This will open a tool for editing Swagger files. You define your API's model (its shape and requirements) in a Swagger file. The file the editor displays is the default swagger.yaml file that was generated when you created the project. You want to replace this with a swagger.yaml file that defines the API you're creating.

  6. Visit the following URL, copy the target file’s contents, then paste them in place of the file displayed in the Swagger editor.

    https://github.com/apigee/insights-samples:q!/blob/master/apps/recommendations-app/recommendations-api/api/swagger/swagger.yaml

    This file defines your API’s model -- its endpoints (as paths), its request parameters and possible responses, as well as acceptable forms for data it consumes and produces. In the file, notice the following path defined:

    /customers/{customer_id}/recommendations

    This is the recommendations API’s endpoint. Under the path definition, you’ll find this line setting the name of the recommendations.js JavaScript file (minus the .js extension) with logic for the API:

    x-swagger-router-controller: recommendations

    Further down, you’ll see this line setting the name of a JavaScript function to be called for GET requests to the recommendations endpoint.

    operationId: getRecommendations

    Now you’ll create a JavaScript file for logic that responds when clients make a request to the endpoint.

  7. In the recommendations-api project directory, create a recommendations.js file at the following location:
    recommendations-api/api/controllers/recommendations.js
  8. Open the recommendations.js file you created.
  9. From the following URL, copy the target file’s contents, then paste them into your recommendations.js file.

    https://github.com/apigee/insights-samples/blob/master/apps/recommendations-app/recommendations-api/api/controllers/recommendations.js

  10. In the recommendations.js file, change the orgName, clientId, and clientSecret so that the params are set to values that correspond to your API BaaS instance.

    You’ll find the param values you need on the overview page of your API BaaS console. The org name is in the upper-left corner of the console. The client ID and secret are near the bottom of the page.

    var client = new usergrid.client({
        URI : 'https://api.usergrid.com',
        orgName: 'your-baas-org-name',
        appName: 'sandbox',
        clientId: 'your-client-ID',
        clientSecret: 'your-client-secret',
        authType:usergrid.AUTH_CLIENT_ID,
        logging: false, //optional - turn on logging, off by default
        buildCurl: true //optional - turn on curl commands, off by default
    });

    This code creates a client object to connect to your API BaaS application. With the connection, the JavaScript can retrieve data from the application in response to client requests.

    Scroll down to see the getRecommendations function that’s mapped to GET recommendations requests.

  11. Save the JavaScript file.
  12. Copy the contents of the file at the following URL:

    https://github.com/apigee/insights-samples/blob/master/apps/recommendations-app/recommendations-api/api/helpers/helper.js

  13. Paste the contents into a helper.js file at the following path in the recommendations-api project:
    recommendations-api/api/helpers/helper.js

    This file provides functions for transforming data retrieved from API BaaS before it’s returned to the client.

  14. Finally, you might need to add some code to update your project in keeping with a recent fix to Apigee-127. If you’ve installed Apigee-127 since January 2015, this is probably unnecessary.
  15. In the project, open the file at the following location:
    recommendations-api/app.js
  16. Replace the contents of the file with the following:
    'use strict';
    var a127 = require('a127-magic');
    var express = require('express');
    var app = express();
    a127.init(function(config) {
        app.use(a127.middleware(config));
        app.listen(process.env.PORT || 10010);
    });

Test the API from the command line

Now that you’ve got the project pieces in place, you can try it out. For a quick and easy test (without having to write a client), you can call the new API from the command line.

First you need to start the Apigee-127 project. Starting the project starts the server that makes the API available.

  1. Open a command prompt and change to the root of the recommendations-api project.
  2. Run the following command (if you're on Mac or Linux, you might need to prefix this with a sudo command:
    a127 project start

    You should see output that looks like the following:

    Starting: /path/to/your/working/directory/recommendations-api/app.js...
    project started here: http://localhost:10010
    project will restart on changes.
    to restart at any time, enter 'rs'
  3. Leaving this prompt open, start another command prompt to use as a client.
  4. In the second prompt window, run the following command to try out your API:
    curl http://localhost:10010/customers/1002128/recommendations

    The API should return JSON representing recommendations for the user whose user ID is 1002128. It will look something like the following. This JSON excerpt shows one result object from an array of JSON objects. Notice that the object is a combination of score data and product data. The data was retrieved from API BaaS and combined by JavaScript in the API you created.

    {
        "entities": [
        {
            "description": "Adapt to take 2 inline with the navigator double kit . From newborn baby to two toddlers: one buggy, loads of years! Slimline at 23",
            "category": 2,
            "CatName": "Baby",
            "discount": 0.12,
            "partNo": "B00FLXBQ6S",
            "photos": [
            {
                "photo": "http://ecx.images-amazon.com/images/I/71kdKZwmVVL._SL600_.jpg"
            },
            {
                "photo": "http://ecx.images-amazon.com/images/I/71BqHwpUNaL._SL600_.jpg"
            }
            ],
            "price": 499.99,
            "rating": 3.8,
            "metadata/path": "/products/45e942aa-0233-11e4-8ece-a911fc7996fa",
            "productName": "NavigatorStoller",
            "scoreType": "recommendationscores",
            "scoreValue": 25.98583771844338,
            "userId": "1002128",
            "status": "current"
        },
        ... more entities ...
        ]
    }

A client app would receive this output and parse it into something to display for the user.

Next steps

Congratulations! You've added a recommendations feature you can use from a client app. Recommendations are an intelligent, data-based way to enrich the user experience and promote sales and adoption. Don't forget that you can find all of the code used for this tutorial in the Insight samples GitHub repository.

If you're familiar with app and API development, but new to big data and predictive analytics, consider using the included retail datasets to develop models for other kinds of predictions (such as predicting store visits). You can also import your own data to Insights, then visualize and build models with it.

 

Help or comments?