Learn how to surface relevant resources using the Gloo AI Recommendations API.
This tutorial builds a resource recommender on the Gloo AI Recommendations API: publisher-scoped recommendations, snippet previews for richer displays, and discovery across the Gloo affiliate publisher network.Want the concepts first? Read the Concepts guide and Affiliate Recommendations, or the Recommendations lesson in the AI Learning Center.Unlike keyword search, the Recommendations API ranks content by semantic relevance to a user’s query, making it ideal for “You might also like” panels, related-resource sections, and cross-publisher content discovery.
The Recommendations API returns ranked content items from your publisher’s collection or the Gloo affiliate network. It is optimized for recommendation UI patterns, not open-ended search.
What you’ll build
A resource recommender, one endpoint per step:
Step
Endpoint
Purpose
1
POST /ai/v1/data/items/recommendations/base
Publisher-scoped ranked items — metadata only
2
POST /ai/v1/data/items/recommendations/verbose
Publisher-scoped ranked items — includes full snippet text
3
POST /ai/v1/data/affiliates/referenced-items
Cross-publisher discovery from the Gloo affiliate network
Follow along with complete working examples in all 6 languages (JavaScript, TypeScript, Python, PHP, Go, Java). Includes a proxy server and browser-based frontend for each language.
The code snippets in this tutorial are simplified and self-contained —
designed for readability and easy copy-paste. The cookbook
examples
use a modular architecture plus production niceties. Both implement the same
APIs and patterns.
import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import io.github.cdimascio.dotenv.Dotenv;import java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.List;public class Recommendations { static final Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load(); static final String API_KEY = java.util.Objects.requireNonNull(dotenv.get("GLOO_API_KEY"), "Set GLOO_API_KEY in your .env file"); static final String TENANT = dotenv.get("GLOO_TENANT", "your-tenant-name"); static final String COLLECTION = dotenv.get("GLOO_COLLECTION", "GlooProd"); static final String BASE_URL = "https://platform.ai.gloo.com/ai/v1/data/items/recommendations/base"; static final HttpClient http = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(30)).build(); static final Gson gson = new Gson(); static class Req { String query; int item_count; double certainty_threshold; String collection; String tenant; } static class UUID { String ai_title; String item_summary; double certainty; } static class Item { String item_title; List<String> author; List<UUID> uuids; } static List<Item> getRecommendations(String query, int itemCount) throws Exception { Req payload = new Req(); payload.query = query; payload.item_count = itemCount; payload.certainty_threshold = 0.75; payload.collection = COLLECTION; payload.tenant = TENANT; HttpResponse<String> resp = http.send( HttpRequest.newBuilder().uri(URI.create(BASE_URL)) .header("Authorization", "Bearer " + API_KEY) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(gson.toJson(payload))) .timeout(Duration.ofSeconds(60)).build(), HttpResponse.BodyHandlers.ofString()); return gson.fromJson(resp.body(), new TypeToken<List<Item>>() {}.getType()); } public static void main(String[] args) throws Exception { String query = args.length > 0 ? args[0] : "How do I deal with anxiety?"; int itemCount = args.length > 1 ? Integer.parseInt(args[1]) : 5; List<Item> items = getRecommendations(query, itemCount); System.out.printf("Found %d item(s):%n%n", items.size()); for (int i = 0; i < items.size(); i++) { Item item = items.get(i); System.out.printf("--- Item %d ---%n", i + 1); System.out.printf("Title: %s%n", item.item_title != null ? item.item_title : "N/A"); if (item.author != null && !item.author.isEmpty()) System.out.printf("Author: %s%n", String.join(", ", item.author)); if (item.uuids != null && !item.uuids.isEmpty()) { UUID top = item.uuids.get(0); System.out.printf("Relevance: %.0f%%%n", top.certainty * 100); if (top.ai_title != null) System.out.printf("Section: %s%n", top.ai_title); if (top.item_summary != null) System.out.printf("Summary: %s%n", top.item_summary); } System.out.println(); } }}
What you'll see
A successful call returns up to 5 items with metadata such as the title, summary, and relevance score:
Found 3 item(s):--- Item 1 ---Title: Finding True HappinessAuthor: John SmithRelevance: 89%Section: The Path to ContentmentSummary: This article explores the foundations of lasting happiness from a biblical perspective.--- Item 2 ---Title: Overcoming Anxiety and FearAuthor: Jane DoeRelevance: 84%Section: Trusting God in Difficult TimesSummary: Practical guidance on releasing anxiety through prayer and scripture.--- Item 3 ---Title: Peace That Passes UnderstandingAuthor: John SmithRelevance: 81%Section: Philippians 4 AppliedSummary: A study of Philippians 4:6-7 and its application to modern anxiety.
Fields like Summary and Section may not appear for every item: they’re AI-generated during ingestion, so older or minimally processed content may return only Title, Author, and Relevance.
Getting no results? Work through these in order:
Test your query in the Search Playground — if nothing shows there, your content may not be indexed yet.
Try a different query that you know returns results in the Playground.
If the Playground returns results but your code doesn’t, lower certainty_threshold from 0.75 to 0.5 to match the Playground’s default.
Step 2: Recommendations with Snippet Previews
The verbose endpoint adds full snippet text to each result, for preview cards that show a passage alongside the title.The only change from Step 1 is the endpoint URL and reading uuids[0].snippet from the response.
import requests, os, sysfrom dotenv import load_dotenvload_dotenv()API_KEY = os.environ["GLOO_API_KEY"]TENANT = os.getenv("GLOO_TENANT", "your-tenant-name")COLLECTION = os.getenv("GLOO_COLLECTION", "GlooProd")VERBOSE_URL = "https://platform.ai.gloo.com/ai/v1/data/items/recommendations/verbose"def get_verbose(query, item_count=5): r = requests.post( VERBOSE_URL, headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={ "query": query, "item_count": item_count, "certainty_threshold": 0.75, "collection": COLLECTION, "tenant": TENANT, }, timeout=60, ) r.raise_for_status() return r.json()query = sys.argv[1] if len(sys.argv) > 1 else "How do I deal with anxiety?"item_count = int(sys.argv[2]) if len(sys.argv) > 2 else 5items = get_verbose(query, item_count)print(f"Found {len(items)} item(s):\n")for i, item in enumerate(items, 1): print(f"--- Item {i} ---") print(f"Title: {item.get('item_title', 'N/A')}") if item.get("author"): print(f"Author: {', '.join(item['author'])}") if item.get("uuids"): top = item["uuids"][0] print(f"Relevance: {top.get('certainty', 0):.0%}") if top.get("ai_title"): print(f"Section: {top['ai_title']}") if top.get("item_summary"): print(f"Summary: {top['item_summary']}") snippet = top.get("snippet", "") if snippet: print(f"Preview: \"{snippet[:200]}{'...' if len(snippet) > 200 else ''}\"") print()
import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import io.github.cdimascio.dotenv.Dotenv;import java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.List;public class RecommendationsVerbose { static final Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load(); static final String API_KEY = java.util.Objects.requireNonNull(dotenv.get("GLOO_API_KEY"), "Set GLOO_API_KEY in your .env file"); static final String TENANT = dotenv.get("GLOO_TENANT", "your-tenant-name"); static final String COLLECTION = dotenv.get("GLOO_COLLECTION", "GlooProd"); static final String VERBOSE_URL = "https://platform.ai.gloo.com/ai/v1/data/items/recommendations/verbose"; static final HttpClient http = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(30)).build(); static final Gson gson = new Gson(); static class Req { String query; int item_count; double certainty_threshold; String collection; String tenant; } static class UUID { String ai_title; String item_summary; double certainty; String snippet; } static class Item { String item_title; List<String> author; List<UUID> uuids; } static List<Item> getVerbose(String query, int itemCount) throws Exception { Req payload = new Req(); payload.query = query; payload.item_count = itemCount; payload.certainty_threshold = 0.75; payload.collection = COLLECTION; payload.tenant = TENANT; HttpResponse<String> resp = http.send( HttpRequest.newBuilder().uri(URI.create(VERBOSE_URL)) .header("Authorization", "Bearer " + API_KEY) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(gson.toJson(payload))) .timeout(Duration.ofSeconds(60)).build(), HttpResponse.BodyHandlers.ofString()); return gson.fromJson(resp.body(), new TypeToken<List<Item>>() {}.getType()); } public static void main(String[] args) throws Exception { String query = args.length > 0 ? args[0] : "How do I deal with anxiety?"; int itemCount = args.length > 1 ? Integer.parseInt(args[1]) : 5; List<Item> items = getVerbose(query, itemCount); System.out.printf("Found %d item(s):%n%n", items.size()); for (int i = 0; i < items.size(); i++) { Item item = items.get(i); System.out.printf("--- Item %d ---%n", i + 1); System.out.printf("Title: %s%n", item.item_title != null ? item.item_title : "N/A"); if (item.author != null && !item.author.isEmpty()) System.out.printf("Author: %s%n", String.join(", ", item.author)); if (item.uuids != null && !item.uuids.isEmpty()) { UUID top = item.uuids.get(0); System.out.printf("Relevance: %.0f%%%n", top.certainty * 100); if (top.ai_title != null) System.out.printf("Section: %s%n", top.ai_title); if (top.item_summary != null) System.out.printf("Summary: %s%n", top.item_summary); if (top.snippet != null && !top.snippet.isEmpty()) { String preview = top.snippet.length() > 200 ? top.snippet.substring(0, 200) + "..." : top.snippet; System.out.printf("Preview: \"%s\"%n", preview); } } System.out.println(); } }}
What you'll see
Same as Step 1, with a Preview line added for each item:
--- Item 1 ---Title: Finding True HappinessAuthor: John SmithRelevance: 89%Section: The Path to ContentmentSummary: This article explores the foundations of lasting happiness from a biblical perspective.Preview: "True happiness is not found in circumstances but in relationship. The Beatitudes describe a person who is blessed not because of what they have, but because of who..."
Step 3: Affiliate Network Discovery
The affiliate endpoint surfaces content from across the entire Gloo publisher network, not just your own collection. Use it to power “Explore More” sections that introduce users to resources from other publishers.Two key differences from the publisher endpoints:
No collection or tenant in the request — the search spans the full affiliate network
Flat response structure — items have tradition and item_subtitle fields instead of uuids
import requests, os, sysfrom dotenv import load_dotenvload_dotenv()API_KEY = os.environ["GLOO_API_KEY"]AFFILIATES_URL = "https://platform.ai.gloo.com/ai/v1/data/affiliates/referenced-items"def get_affiliates(query, item_count=5): r = requests.post( AFFILIATES_URL, headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"}, json={"query": query, "item_count": item_count, "certainty_threshold": 0.75}, timeout=60, ) r.raise_for_status() return r.json()query = sys.argv[1] if len(sys.argv) > 1 else "How do I deal with anxiety?"item_count = int(sys.argv[2]) if len(sys.argv) > 2 else 5items = get_affiliates(query, item_count)print(f"Found {len(items)} item(s) from across the affiliate network:\n")for i, item in enumerate(items, 1): print(f"--- Item {i} ---") print(f"Title: {item.get('item_title', 'N/A')}") if item.get("author"): print(f"Author: {', '.join(item['author'])}") if item.get("tradition"): print(f"Tradition: {item['tradition']}") if item.get("item_subtitle"): print(f"Subtitle: {item['item_subtitle']}") if item.get("item_url"): print(f"URL: {item['item_url']}") print()
const axios = require('axios');require('dotenv').config();if (!process.env.GLOO_API_KEY) throw new Error('Set GLOO_API_KEY in your environment');const API_KEY = process.env.GLOO_API_KEY;const AFFILIATES_URL = 'https://platform.ai.gloo.com/ai/v1/data/affiliates/referenced-items';async function getAffiliates(query, itemCount = 5) { const { data } = await axios.post( AFFILIATES_URL, { query, item_count: itemCount, certainty_threshold: 0.75 }, { headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' } } ); return data;}(async () => { const query = process.argv[2] || 'How do I deal with anxiety?'; const itemCount = parseInt(process.argv[3]) || 5; const items = await getAffiliates(query, itemCount); console.log(`Found ${items.length} item(s) from across the affiliate network:\n`); items.forEach((item, i) => { console.log(`--- Item ${i + 1} ---`); console.log(`Title: ${item.item_title || 'N/A'}`); if (item.author?.length) console.log(`Author: ${item.author.join(', ')}`); if (item.tradition) console.log(`Tradition: ${item.tradition}`); if (item.item_subtitle) console.log(`Subtitle: ${item.item_subtitle}`); if (item.item_url) console.log(`URL: ${item.item_url}`); console.log(); });})();
import axios from 'axios';import * as dotenv from 'dotenv';dotenv.config();if (!process.env.GLOO_API_KEY) throw new Error('Set GLOO_API_KEY in your environment');const API_KEY = process.env.GLOO_API_KEY;const AFFILIATES_URL = 'https://platform.ai.gloo.com/ai/v1/data/affiliates/referenced-items';interface AffiliateItem { item_title: string; item_subtitle?: string; author: string[]; tradition?: string; item_url?: string;}async function getAffiliates(query: string, itemCount = 5): Promise<AffiliateItem[]> { const { data } = await axios.post<AffiliateItem[]>( AFFILIATES_URL, { query, item_count: itemCount, certainty_threshold: 0.75 }, { headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' } } ); return data;}(async () => { const query = process.argv[2] ?? 'How do I deal with anxiety?'; const itemCount = parseInt(process.argv[3] ?? '5'); const items = await getAffiliates(query, itemCount); console.log(`Found ${items.length} item(s) from across the affiliate network:\n`); items.forEach((item, i) => { console.log(`--- Item ${i + 1} ---`); console.log(`Title: ${item.item_title ?? 'N/A'}`); if (item.author?.length) console.log(`Author: ${item.author.join(', ')}`); if (item.tradition) console.log(`Tradition: ${item.tradition}`); if (item.item_subtitle) console.log(`Subtitle: ${item.item_subtitle}`); if (item.item_url) console.log(`URL: ${item.item_url}`); console.log(); });})();
import com.google.gson.Gson;import com.google.gson.reflect.TypeToken;import io.github.cdimascio.dotenv.Dotenv;import java.net.URI;import java.net.http.*;import java.time.Duration;import java.util.List;public class RecommendationsAffiliates { static final Dotenv dotenv = Dotenv.configure().ignoreIfMissing().load(); static final String API_KEY = java.util.Objects.requireNonNull(dotenv.get("GLOO_API_KEY"), "Set GLOO_API_KEY in your .env file"); static final String AFFILIATES_URL = "https://platform.ai.gloo.com/ai/v1/data/affiliates/referenced-items"; static final HttpClient http = HttpClient.newBuilder() .connectTimeout(Duration.ofSeconds(30)).build(); static final Gson gson = new Gson(); static class Req { String query; int item_count; double certainty_threshold; } static class Item { String item_title; String item_subtitle; List<String> author; String tradition; String item_url; } static List<Item> getAffiliates(String query, int itemCount) throws Exception { Req payload = new Req(); payload.query = query; payload.item_count = itemCount; payload.certainty_threshold = 0.75; HttpResponse<String> resp = http.send( HttpRequest.newBuilder().uri(URI.create(AFFILIATES_URL)) .header("Authorization", "Bearer " + API_KEY) .header("Content-Type", "application/json") .POST(HttpRequest.BodyPublishers.ofString(gson.toJson(payload))) .timeout(Duration.ofSeconds(60)).build(), HttpResponse.BodyHandlers.ofString()); return gson.fromJson(resp.body(), new TypeToken<List<Item>>() {}.getType()); } public static void main(String[] args) throws Exception { String query = args.length > 0 ? args[0] : "How do I deal with anxiety?"; int itemCount = args.length > 1 ? Integer.parseInt(args[1]) : 5; List<Item> items = getAffiliates(query, itemCount); System.out.printf("Found %d item(s) from across the affiliate network:%n%n", items.size()); for (int i = 0; i < items.size(); i++) { Item item = items.get(i); System.out.printf("--- Item %d ---%n", i + 1); System.out.printf("Title: %s%n", item.item_title != null ? item.item_title : "N/A"); if (item.author != null && !item.author.isEmpty()) System.out.printf("Author: %s%n", String.join(", ", item.author)); if (item.tradition != null && !item.tradition.isEmpty()) System.out.printf("Tradition: %s%n", item.tradition); if (item.item_subtitle != null && !item.item_subtitle.isEmpty()) System.out.printf("Subtitle: %s%n", item.item_subtitle); if (item.item_url != null && !item.item_url.isEmpty()) System.out.printf("URL: %s%n", item.item_url); System.out.println(); } }}
What you'll see
Found 3 item(s) from across the affiliate network:--- Item 1 ---Title: Anxiety and the Christian LifeAuthor: Crossway PublishersTradition: EvangelicalSubtitle: Finding Peace in a Worried WorldURL: https://example.com/books/anxiety-and-the-christian-life--- Item 2 ---Title: Cast All Your Anxiety on HimAuthor: Desiring GodTradition: ReformedURL: https://example.com/articles/cast-all-your-anxiety-on-him--- Item 3 ---Title: Freedom from AnxietyAuthor: Focus on the FamilyTradition: EvangelicalURL: https://example.com/faith/freedom-from-anxiety
Complete code
View Complete Code
Clone or browse the complete working examples for all 6 languages (JavaScript,
TypeScript, Python, PHP, Go, Java) with setup instructions, proxy servers, and
a browser-based frontend.
server — Proxy server exposing REST endpoints for the frontend
Run the cookbook examples
Each step has a ready-to-run script in the cookbook. Set up with the Step 1 commands, then run the later steps from the same directory:
1
Publisher recommendations
The cookbook includes a ready-to-run basic search script for each language:
cd recommendations/pythonpython -m venv venv && source venv/bin/activatepip install -r requirements.txtpython recommend_base.py "How do I deal with anxiety?"python recommend_base.py "parenting teenagers" 3
cd recommendations/javascriptnpm installnode recommend-base.js "How do I deal with anxiety?"node recommend-base.js "parenting teenagers" 3
cd recommendations/typescriptnpm installnpx ts-node recommend-base.ts "How do I deal with anxiety?"npx ts-node recommend-base.ts "parenting teenagers" 3
cd recommendations/phpcomposer installphp recommend_base.php "How do I deal with anxiety?"php recommend_base.php "parenting teenagers" 3
cd recommendations/gogo mod tidygo run . base "How do I deal with anxiety?"go run . base "parenting teenagers" 3
cd recommendations/javamvn compile -qmvn -q exec:java -Dexec.args='base "How do I deal with anxiety?"'mvn -q exec:java -Dexec.args='base "parenting teenagers" 3'
2
Snippet previews
python recommend_verbose.py "How do I deal with anxiety?"python recommend_verbose.py "parenting teenagers" 3
node recommend-verbose.js "How do I deal with anxiety?"node recommend-verbose.js "parenting teenagers" 3
npx ts-node recommend-verbose.ts "How do I deal with anxiety?"npx ts-node recommend-verbose.ts "parenting teenagers" 3
php recommend_verbose.php "How do I deal with anxiety?"php recommend_verbose.php "parenting teenagers" 3
go run . verbose "How do I deal with anxiety?"go run . verbose "parenting teenagers" 3
mvn -q exec:java -Dexec.args='verbose "How do I deal with anxiety?"'mvn -q exec:java -Dexec.args='verbose "parenting teenagers" 3'
3
Affiliate discovery
python recommend_affiliates.py "How do I deal with anxiety?"python recommend_affiliates.py "parenting teenagers" 3
node recommend-affiliates.js "How do I deal with anxiety?"node recommend-affiliates.js "parenting teenagers" 3
npx ts-node recommend-affiliates.ts "How do I deal with anxiety?"npx ts-node recommend-affiliates.ts "parenting teenagers" 3
php recommend_affiliates.php "How do I deal with anxiety?"php recommend_affiliates.php "parenting teenagers" 3
go run . affiliates "How do I deal with anxiety?"go run . affiliates "parenting teenagers" 3
mvn -q exec:java -Dexec.args='affiliates "How do I deal with anxiety?"'mvn -q exec:java -Dexec.args='affiliates "parenting teenagers" 3'
Try it: frontend example
The cookbook includes a browser-based frontend that connects to a proxy server, letting you visualize all three recommendation modes. The proxy server keeps your credentials secure on the server side (see API Key Security).Architecture
Browser (HTML/JS) → Proxy Server (localhost:3000) → Gloo AI APIs
The proxy server exposes three endpoints:
POST /api/recommendations/base — Publisher recommendations (metadata only)
POST /api/recommendations/verbose — Publisher recommendations (with snippet previews)
POST /api/recommendations/affiliates — Affiliate network discovery
Start the Proxy ServerEach language includes a proxy server. Start one:
cd recommendations/pythonsource venv/bin/activatepython server.py
cd recommendations/javascriptnode server.js
cd recommendations/typescriptnpx ts-node server.ts
cd recommendations/phpphp -S localhost:3000 server.php
cd recommendations/gogo run . server
cd recommendations/javamvn -q exec:java -Dexec.args='server'
Then open http://localhost:3000 in your browser.Publisher RecommendationsEnter a query, choose how many items to return, and optionally enable Verbose mode to show snippet previews alongside each result:
Affiliate Network DiscoveryThe Explore More panel fires automatically alongside your publisher results, surfacing related content from across the Gloo network:
The frontend is language-agnostic — the same HTML/JS works with any language’s
proxy server. This is one approach; customize for your branding and framework.
Troubleshooting
No Results Returned
certainty_threshold too strict: This tutorial sends 0.75, which filters out lower-confidence matches. Lower it to 0.5 (the API default) to broaden results.
Content not indexed: Test the same query in the Search Playground. If content appears there, your API parameters are correct.
Wrong tenant: Results are scoped to your publisher. Verify the tenant name matches your publisher in Organizations.
403 Forbidden
You can only access your own publisher’s content via the publisher endpoints.
Verify your API key is correct and has not been revoked.
The affiliate endpoint has broader access — a 403 there indicates an API key issue.
Affiliate Endpoint Returns Empty
Not all content is available in the affiliate network. Publishers must opt in.
Try a broader or different query to confirm the endpoint is working.