Code Examples
Integration examples for popular programming languages and agent frameworks
⚡ Quick Integration
Get started quickly with these minimal examples. For production use, add proper error handling, caching, and rate limiting.
Try in Playground First →JavaScript / Node.js
Basic Search with Fetch API
// Basic product search
async function searchProducts(query, apiKey) {
const response = await fetch('https://abbababa.com/api/v1/search', {
method: 'POST',
headers: {
'X-API-Key': apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: query,
filters: {
inStock: true,
minQualityScore: 0.7
},
limit: 10,
sortBy: 'quality_score'
})
});
if (!response.ok) {
throw new Error(`Search failed: ${response.statusText}`);
}
return await response.json();
}
// Usage example
const results = await searchProducts(
'wireless bluetooth headphones',
'aba_your_api_key'
);
console.log(`Found ${results.total} products`);
results.products.forEach(product => {
console.log(`${product.name} - $${product.price}`);
});Advanced Agent Integration
class AbbabaAgent {
constructor(apiKey) {
this.apiKey = apiKey;
this.baseUrl = 'https://abbababa.com/api/v1';
}
async search(query, options = {}) {
const searchParams = {
query,
filters: {
inStock: true,
minQualityScore: options.minQuality || 0.7,
priceMax: options.maxPrice,
categories: options.categories,
...options.filters
},
limit: options.limit || 10,
sortBy: options.sortBy || 'quality_score'
};
try {
const response = await fetch(`${this.baseUrl}/search`, {
method: 'POST',
headers: {
'X-API-Key': this.apiKey,
'Content-Type': 'application/json'
},
body: JSON.stringify(searchParams)
});
if (!response.ok) {
const error = await response.json();
throw new Error(`API Error: ${error.message}`);
}
return await response.json();
} catch (error) {
console.error('Search failed:', error);
throw error;
}
}
async getProduct(productId) {
const response = await fetch(`${this.baseUrl}/products/${productId}`, {
headers: { 'X-API-Key': this.apiKey }
});
if (!response.ok) {
throw new Error(`Product not found: ${productId}`);
}
return await response.json();
}
async checkUsage() {
const response = await fetch(`${this.baseUrl}/auth/usage`, {
headers: { 'X-API-Key': this.apiKey }
});
return await response.json();
}
}
// Usage
const agent = new AbbabaAgent('aba_your_api_key');
// Search for products
const products = await agent.search('smart watch', {
maxPrice: 300,
categories: ['electronics'],
minQuality: 0.8
});
// Get detailed product info
const product = await agent.getProduct('prod_123');
// Check API usage
const usage = await agent.checkUsage();
console.log(`Used ${usage.requestsToday}/${usage.dailyLimit} requests today`);Python
Simple Python Client
import requests
from typing import Dict, List, Optional
class AbbabaClient:
def __init__(self, api_key: str):
self.api_key = api_key
self.base_url = "https://abbababa.com/api/v1"
self.session = requests.Session()
self.session.headers.update({
"X-API-Key": api_key,
"Content-Type": "application/json"
})
def search(self, query: str, **kwargs) -> Dict:
"""Search for products with filters"""
payload = {
"query": query,
"filters": {
"inStock": kwargs.get("in_stock", True),
"minQualityScore": kwargs.get("min_quality", 0.7),
"priceMax": kwargs.get("max_price"),
"categories": kwargs.get("categories"),
},
"limit": kwargs.get("limit", 10),
"sortBy": kwargs.get("sort_by", "quality_score")
}
# Remove None values
payload["filters"] = {k: v for k, v in payload["filters"].items() if v is not None}
response = self.session.post(f"{self.base_url}/search", json=payload)
response.raise_for_status()
return response.json()
def get_product(self, product_id: str) -> Dict:
"""Get detailed product information"""
response = self.session.get(f"{self.base_url}/products/{product_id}")
response.raise_for_status()
return response.json()
def check_usage(self) -> Dict:
"""Check API usage statistics"""
response = self.session.get(f"{self.base_url}/auth/usage")
response.raise_for_status()
return response.json()
# Usage example
client = AbbabaClient("aba_your_api_key")
# Search for headphones under $200
results = client.search(
"noise canceling headphones",
max_price=200,
categories=["electronics", "audio"],
min_quality=0.8
)
print(f"Found {results['total']} products")
for product in results["products"]:
print(f"{product['name']} - ${product['price']}")
print(f"Quality: {product['dataQualityScore']:.1%}")
print(f"Merchant: {product['merchantName']}")
print(f"URL: {product['referralUrl']}")
print("---")LangChain Integration
Custom Tool for LangChain Agents
from langchain.tools import BaseTool
from langchain.agents import initialize_agent, Tool
from langchain.llms import OpenAI
import requests
import json
class AbbabaSearchTool(BaseTool):
name = "abbababa_product_search"
description = """
Search for products on the Abbababa B2A marketplace.
Use this when you need to find products for purchase recommendations.
Input should be a search query string.
"""
def __init__(self, api_key: str):
super().__init__()
self.api_key = api_key
self.base_url = "https://abbababa.com/api/v1"
def _run(self, query: str) -> str:
headers = {
"X-API-Key": self.api_key,
"Content-Type": "application/json"
}
payload = {
"query": query,
"filters": {"inStock": True, "minQualityScore": 0.7},
"limit": 5,
"sortBy": "quality_score"
}
try:
response = requests.post(
f"{self.base_url}/search",
headers=headers,
json=payload
)
response.raise_for_status()
data = response.json()
products = data.get("products", [])
if not products:
return f"No products found for '{query}'"
result = f"Found {len(products)} products for '{query}':\n"
for i, product in enumerate(products, 1):
result += f"{i}. {product['name']} - ${product['price']} "
result += f"(Quality: {product['dataQualityScore']:.1%}) "
result += f"from {product['merchantName']}\n"
result += f" Link: {product['referralUrl']}\n"
return result
except Exception as e:
return f"Error searching for products: {str(e)}"
def _arun(self, query: str):
raise NotImplementedError("Async not supported")
# Initialize the tool and agent
abbababa_tool = AbbabaSearchTool("aba_your_api_key")
tools = [abbababa_tool]
llm = OpenAI(temperature=0)
agent = initialize_agent(
tools,
llm,
agent="zero-shot-react-description",
verbose=True
)
# Example usage
response = agent.run("I need wireless earbuds for running under $100")
print(response)Error Handling Best Practices
// Robust error handling with retry logic
class AbbabaClientWithRetry {
constructor(apiKey, options = {}) {
this.apiKey = apiKey;
this.baseUrl = 'https://abbababa.com/api/v1';
this.maxRetries = options.maxRetries || 3;
this.retryDelay = options.retryDelay || 1000;
}
async makeRequest(endpoint, options = {}) {
const url = `${this.baseUrl}${endpoint}`;
const config = {
headers: {
'X-API-Key': this.apiKey,
'Content-Type': 'application/json',
...options.headers
},
...options
};
for (let attempt = 1; attempt <= this.maxRetries; attempt++) {
try {
const response = await fetch(url, config);
if (response.ok) {
return await response.json();
}
const error = await response.json().catch(() => ({}));
// Don't retry on client errors (4xx)
if (response.status >= 400 && response.status < 500) {
throw new Error(`API Error (${response.status}): ${error.message || response.statusText}`);
}
// Retry on server errors (5xx) or network issues
if (attempt === this.maxRetries) {
throw new Error(`API Error after ${this.maxRetries} attempts: ${error.message || response.statusText}`);
}
console.warn(`Request failed (attempt ${attempt}/${this.maxRetries}), retrying in ${this.retryDelay}ms...`);
await this.sleep(this.retryDelay * attempt); // Exponential backoff
} catch (error) {
if (attempt === this.maxRetries || error.name === 'TypeError') {
throw error;
}
console.warn(`Network error (attempt ${attempt}/${this.maxRetries}), retrying...`);
await this.sleep(this.retryDelay * attempt);
}
}
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async search(query, options = {}) {
return this.makeRequest('/search', {
method: 'POST',
body: JSON.stringify({
query,
filters: options.filters || { inStock: true },
limit: options.limit || 10,
sortBy: options.sortBy || 'quality_score'
})
});
}
}
// Usage with error handling
const client = new AbbabaClientWithRetry('aba_your_api_key', {
maxRetries: 3,
retryDelay: 1000
});
try {
const results = await client.search('laptop computers');
console.log(`Found ${results.total} products`);
} catch (error) {
console.error('Search failed:', error.message);
if (error.message.includes('401')) {
console.error('Invalid API key - please check your credentials');
} else if (error.message.includes('403')) {
console.error('Rate limit exceeded - please try again later');
} else {
console.error('Unexpected error - please contact support');
}
}