Once you have a valid session, call the /agent/recommend endpoint.
TypeScript/JavaScript
React
Android (Kotlin)
Flutter (Dart)
Swift/iOS
React Native
export async function getAdmeshRecommendations(query: string) {
const ADMESH_BASE = "https://api.useadmesh.com";
const sessionId =
localStorage.getItem("admesh_session_id") || (await createAdmeshSession());
const res = await fetch(`${ADMESH_BASE}/agent/recommend`, {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.REACT_APP_ADMESH_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
session_id: sessionId,
message_id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
format: "auto"
}),
});
if (res.status === 401) {
const newSession = await createAdmeshSession();
return getAdmeshRecommendations(query);
}
return res.json();
}
import { useState, useCallback } from 'react';
export function useAdmeshRecommendations() {
const [recommendations, setRecommendations] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const fetchRecommendations = useCallback(async (query: string) => {
setLoading(true);
setError(null);
try {
const sessionId = localStorage.getItem("admesh_session_id");
if (!sessionId) throw new Error("No active session");
const res = await fetch("https://api.useadmesh.com/agent/recommend", {
method: "POST",
headers: {
"Authorization": `Bearer ${process.env.REACT_APP_ADMESH_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
query,
session_id: sessionId,
message_id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
format: "auto"
}),
});
if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
const data = await res.json();
setRecommendations(data);
return data;
} catch (err) {
const message = err instanceof Error ? err.message : "Unknown error";
setError(message);
console.error("⚠️ Failed to fetch recommendations:", message);
return null;
} finally {
setLoading(false);
}
}, []);
return { recommendations, loading, error, fetchRecommendations };
}
import kotlinx.coroutines.*
import java.net.URL
import java.net.HttpURLConnection
import android.content.SharedPreferences
class AdmeshRecommendationManager(private val prefs: SharedPreferences) {
companion object {
private const val ADMESH_BASE = "https://api.useadmesh.com"
private const val API_KEY = "your_api_key_here"
}
suspend fun getRecommendations(query: String): String? = withContext(Dispatchers.IO) {
try {
val sessionId = prefs.getString("admesh_session_id", null) ?: return@withContext null
val url = URL("$ADMESH_BASE/agent/recommend")
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "POST"
connection.setRequestProperty("Authorization", "Bearer $API_KEY")
connection.setRequestProperty("Content-Type", "application/json")
val messageId = "msg_${System.currentTimeMillis()}_${java.util.UUID.randomUUID().toString().substring(0, 9)}"
val body = """{"query":"$query","session_id":"$sessionId","message_id":"$messageId","format":"auto"}"""
connection.outputStream.write(body.toByteArray())
if (connection.responseCode == HttpURLConnection.HTTP_OK) {
val response = connection.inputStream.bufferedReader().readText()
android.util.Log.d("AdMesh", "✅ Recommendations fetched")
response
} else {
android.util.Log.e("AdMesh", "⚠️ Failed: ${connection.responseCode}")
null
}
} catch (e: Exception) {
android.util.Log.e("AdMesh", "⚠️ Error: ${e.message}")
null
}
}
}
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';
class AdmeshRecommendationManager {
static const String admeshBase = 'https://api.useadmesh.com';
static const String apiKey = 'your_api_key_here';
static Future<Map<String, dynamic>?> getRecommendations(String query) async {
try {
final prefs = await SharedPreferences.getInstance();
final sessionId = prefs.getString('admesh_session_id');
if (sessionId == null) return null;
final response = await http.post(
Uri.parse('$admeshBase/agent/recommend'),
headers: {
'Authorization': 'Bearer $apiKey',
'Content-Type': 'application/json',
},
body: jsonEncode({
'query': query,
'session_id': sessionId,
'message_id': 'msg_${DateTime.now().millisecondsSinceEpoch}_${Uuid().v4().substring(0, 9)}',
'format': 'auto',
}),
);
if (response.statusCode == 200) {
final data = jsonDecode(response.body);
print('✅ Recommendations fetched');
return data;
} else {
print('⚠️ Failed: ${response.statusCode}');
return null;
}
} catch (e) {
print('⚠️ Error: $e');
return null;
}
}
}
import Foundation
class AdmeshRecommendationManager {
static let admeshBase = "https://api.useadmesh.com"
static let apiKey = "your_api_key_here"
static func getRecommendations(query: String, completion: @escaping ([String: Any]?) -> Void) {
guard let sessionId = UserDefaults.standard.string(forKey: "admesh_session_id") else {
completion(nil)
return
}
let url = URL(string: "\(admeshBase)/agent/recommend")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let messageId = "msg_\(Int(Date().timeIntervalSince1970 * 1000))_\(UUID().uuidString.prefix(9))"
let body: [String: Any] = [
"query": query,
"session_id": sessionId,
"message_id": messageId,
"format": "auto"
]
request.httpBody = try? JSONSerialization.data(withJSONObject: body)
URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
print("⚠️ Error: \(error?.localizedDescription ?? "Unknown")")
completion(nil)
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
print("✅ Recommendations fetched")
completion(json)
} else {
completion(nil)
}
} catch {
print("⚠️ Parse error: \(error)")
completion(nil)
}
}.resume()
}
}
import AsyncStorage from '@react-native-async-storage/async-storage';
export async function getAdmeshRecommendations(query: string) {
try {
const sessionId = await AsyncStorage.getItem('admesh_session_id');
if (!sessionId) throw new Error('No active session');
const response = await fetch('https://api.useadmesh.com/agent/recommend', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.ADMESH_API_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
query,
session_id: sessionId,
message_id: `msg_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`,
format: 'auto',
}),
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log('✅ Recommendations fetched');
return data;
} catch (error) {
console.error('⚠️ Error fetching recommendations:', error);
return null;
}
}
Request Parameters
| Parameter | Type | Required | Description |
|---|
query | string | Yes | User’s search or chat query |
session_id | string | Yes | Session ID from /agent/session/new |
message_id | string | Yes | Unique message ID for deduplication across platforms. Format: msg_{timestamp}_{random} |
format | string | No | Layout format: auto, card, inline. Defaults to auto |
source | string | No | Source of the request: "admesh_ui_sdk" (frontend SDK) or "admesh_weave_node" (backend weave integration). Defaults to "admesh_ui_sdk" |
Important: message_id is required for deduplication. Generate a unique ID for each message in the format: msg_{timestamp}_{random_string}. This ensures recommendations are not duplicated across multiple requests for the same message.
Example Response
The response follows the finalized minimal schema structure:
{
"session_id": "admesh_sess_1760022990_w8RkKA",
"message_id": "msg_1760022990_abc123",
"recommendations": [
{
"product_id": "prod_123",
"ad_id": "ad_7a2b",
"recommendation_id": "rec_xyz789",
"product_title": "Notion for Teams",
"tail_summary": "Notion is a powerful workspace tool designed for teams...",
"product_summary": "All-in-one workspace for notes, docs, and collaboration",
"weave_summary": "Recommended for collaboration and team productivity",
"exposure_url": "https://api.useadmesh.com/expose/ad_7a2b?...",
"click_url": "https://api.useadmesh.com/click/r/ad_7a2b?...",
"product_logo": {
"url": "https://cdn.example.com/notion-logo.png"
},
"categories": ["productivity", "collaboration"],
"contextual_relevance_score": 0.87,
"trust_score": 85.5,
"model_used": "openai/gpt-4o",
"creative_input": {
"brand_name": "Notion",
"product_name": "Notion for Teams",
"short_description": "All-in-one workspace for notes, docs, and collaboration",
"long_description": "Notion is a powerful workspace tool designed for teams who need to organize their work, collaborate effectively, and stay productive.",
"value_props": [
"Unified workspace",
"Real-time collaboration",
"Customizable templates"
],
"context_snippet": "For teams needing better organization and collaboration",
"cta_label": "Start Free Trial",
"cta_url": "https://notion.so/signup",
"assets": {
"logo_url": "https://cdn.example.com/notion-logo.png",
"image_urls": ["https://cdn.example.com/notion-screenshot.png"],
"resource_urls": ["https://notion.so/signup"]
},
"offer_summary": "Special offer: 50% off first year for teams"
}
}
]
}
Response Schema
Top-Level Fields
| Field | Type | Required | Description |
|---|
session_id | string | Yes | Session ID from the request |
message_id | string | Yes | Message ID from the request (for deduplication) |
recommendations | array | Yes | Array of recommendation objects |
Recommendation Object (14 Core Fields)
Each recommendation object contains the following fields:
| Field | Type | Required | Description |
|---|
product_id | string | Yes | Unique product identifier |
ad_id | string | Yes | Unique ad identifier |
recommendation_id | string | Yes | Unique recommendation identifier |
product_title | string | Yes | Product name (renamed from title) |
tail_summary | string | No | Tail format summary text (moved from top-level) |
product_summary | string | No | Product summary text (moved from top-level) |
weave_summary | string | No | Weave format summary for inline integration |
exposure_url | string | Yes | URL to fire when ad is viewed (MRC-compliant) |
click_url | string | Yes | URL to redirect to when ad is clicked |
product_logo | object | No | Product logo object with url field |
categories | array | No | Product categories |
contextual_relevance_score | number | No | Relevance score (0.0-1.0) |
trust_score | number | No | Trust score (0-100) |
model_used | string | No | AI model used for generation |
creative_input | object | No | Full creative input structure (see below) |
The creative_input object contains detailed creative information:
| Field | Type | Required | Description |
|---|
brand_name | string | Yes | Brand or advertiser name |
product_name | string | Yes | Product or offer name |
short_description | string | Yes | 1-2 sentence summary (max 200 chars) |
long_description | string | Yes | 2-4 sentence description (max 500 chars) |
value_props | array | Yes | Value propositions (bullet points) |
context_snippet | string | Yes | 60-100 character contextual hint for weave format |
cta_label | string | Yes | Call-to-action label |
cta_url | string | Yes | Call-to-action URL |
assets | object | Yes | Creative assets (logo, images, resource URLs) |
offer_summary | string | No | Special offer summary (when available) |
product_id | string | No | Product identifier |
categories | array | No | Product categories |
fallback_formats | array | No | Fallback ad formats if preferred unavailable |
Next → Weave Inline Recommendations