This page outlines the steps you must take before using Recommendations AI.
Set up your project
You must create a Google Cloud project in order to access Recommendations AI. To set up a project, follow these steps:
Go to the Google Cloud console Manage resources page.
On the drop-down at the top of the page, select the organization in which you want to create a project.
Click Create Project.
In the New Project window that appears, enter a project name and select a billing account as applicable.
If you want to add the project to a folder, enter the folder name in the Location box.
When you're finished entering new project details, click Create.
Enable the Recommendation Engine API for your Google Cloud project.
ENABLE THE RECOMMENDATION ENGINE API
Click the ENABLE button in the Google Cloud console to enable the API.
Set up authentication for your application
You must set up both of the following authentication methods to access the Recommendations AI API:
Service Account - Applications use a service account to authenticate calls to the product catalog item APIs.
API Key - Applications use an API key for calls to user event logging and recommendation prediction APIs.
Create a service account
Go to the Google Cloud console Credentials page.
Select the project that you are creating credentials for (the project may already be selected).
Click Create credentials and then select Service account key.
Fill in the following fields:
Field Value Service account New service account Service account name enter a name for your service account Role Service Accounts > Service Account Token Creator
Recommendations AI > Recommendations AI EditorKey type JSON Click Create to create the service account.
The JSON file that contains the public/private key for the new service account is automatically downloaded to your computer. This JSON file is the only copy of the key for your service account. Be sure to store it in a secure location. The JSON key file must be stored in a location that is accessible from your application (see your-service-account-json-key-file in Authenticating using a service account (OAuth 2.0).
Add the service account to your local environment
If you want to make calls to the Recommendations AI
by using the cURL
command-line tool, you'll need to make your service account
available in your local environment. cURL
uses the
gcloud auth application-default print-access-token
command to obtain an access token for your service account
using the Google Cloud SDK. To download and install
the SDK, see Cloud SDK. If you are
using the Cloud Shell, the SDK is already installed.
The GOOGLE_APPLICATION_CREDENTIALS
environment variable will not
persist if you close down your command window. To make sure that the variable
is set to the path to your service account file when you open a new command
window, set the value in an initialization shell script.
export GOOGLE_APPLICATION_CREDENTIALS=path-to-service-account-json-key-file
Create an API key
Go to the Google Cloud console Credentials page.
In the project drop-down at the top of the Google Cloud console page, select your project (the project may already be selected).
Click Create credentials and then select API key. Do not add any referrer restrictions. Some user privacy settings are known to not pass the referrer url.
- Take note of the generated API key, which you will use when calling user event logging and recommendation prediction APIs
For increased security, add an HTTP restriction to your API Key to restrict access to the Recommendations AI service at
https://recommendationengine.googleapis.com/*
.
Register an API key for predict calls
API keys are the fastest and easiest way to provide authentication when you make a call to the predict method. However, if you also use API keys for other API calls, such as logging user events, the API key is embedded in your website, which means it is visible to your users. Because predictions include PII (personally identifiable information) and incur charges, Recommendations AI provides an extra layer of security for prediction calls by requiring you to register any API keys you use for calls to the predict method. You can register up to 20 keys per project.
Create an API key specifically for predict calls by following the instructions in Create an API key.
Register the key, using the predictionApiKeyRegistration.create method:
curl -X POST \ -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \ -H "Content-Type: application/json; charset=utf-8" \ --data "{ "predictionApiKeyRegistration": { "apiKey": 'apiKey' } }" "https://recommendationengine.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/catalogs/default_catalog/eventStores/default_event_store/predictionApiKeyRegistrations"
After you have registered an API key for prediction, you can see it in the Recommendations AI Dashboard page.
Examples
Authenticating using a service account (OAuth 2.0)
Here is a Java example of OAuth 2.0 authentication using a service account. More detailed instructions can be found in the authentication documentation. Google has client libraries in 7 languages that you can use to implement OAuth2 authentication in your application. If you prefer to implement the HTTP/REST directly, follow the REST authentication instructions.
In the example, replace your-service-account-json-key-file with the path to the JSON key file for your service account.
// Simple Java example of using Google Cloud OAuth client library. // // Please see here for the list of libraries in different languages: // https://developers.google.com/identity/protocols/OAuth2#libraries // // The following example depends on the Google API client library. // // Maven: // <dependency> // <groupId>com.google.api-client</groupId> // <artifactId>google-api-client</artifactId> // <version>1.22.0</version> // </dependency> import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.GenericUrl; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestFactory; import com.google.api.client.http.HttpResponse; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.json.JsonHttpContent; import com.google.api.client.json.GenericJson; import com.google.api.client.json.jackson2.JacksonFactory; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class RecommendationEngineApiSample { public static final String CREATE_CATALOG_ITEM_URL = "https://recommendationengine.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/catalogs/default_catalog/catalogItems"; public static GoogleCredential authorize() throws Exception { return GoogleCredential.fromStream(new FileInputStream("your-service-account-json-key-file")) .createScoped(Collections.singleton("https://www.googleapis.com/auth/cloud-platform")) .setExpirationTimeMilliseconds(new Long(3600 * 1000));; } // Build an example catalog item. public static GenericJson getCatalogItem() { List<Object> categories = new ArrayList<Object>(); categories.add(new GenericJson().set("categories", Arrays.asList("Electronics", "Computers"))); categories.add(new GenericJson().set("categories", Arrays.asList("Laptops"))); return new GenericJson() .set("id", "123") .set("title", "Sample Laptop") .set("description", "Indisputably the most fantastic laptop ever created.") .set("category_hierarchies", categories) .set("language_code", "en") .set( "product_metadata", new GenericJson() .set( "exact_price", new GenericJson().set("original_price", 1000.00).set("display_price", 800.00)) .set("currency_code", "USD") .set("stock_status", "IN_STOCK") .set("available_quantity", 1219)); } public static void main(String[] args) { try { GoogleCredential credential = RecommendationEngineApiSample.authorize(); HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); HttpRequestFactory requestFactory = httpTransport.createRequestFactory(); HttpRequest request = requestFactory.buildPostRequest(new GenericUrl(CREATE_CATALOG_ITEM_URL), new JsonHttpContent(new JacksonFactory(), RecommendationEngineApiSample.getCatalogItem())); credential.initialize(request); HttpResponse response = request.execute(); System.out.println("Response content: " + response.parseAsString()); } catch (Exception e) { e.printStackTrace(); } } }
Authenticating using an API key
Here is an example of authenticating using an API key from the command line
using the curl
command. Replace api-key with the API key that
you created in the previous section.
URL="https://recommendationengine.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/catalogs/default_catalog/eventStores/default_event_store/userEvents:write?key=api-key" DATA='{ "user_attributes": { ... }, "user_event_detail": { ... } }' echo $URL curl -H 'Content-Type: application/json' -X POST -d "${DATA}" $URL