If you're building an AI agent that helps users find the best deals on electronics in the US market, you've probably encountered the frustration of dealing with multiple e-commerce platforms, inconsistent data formats, and constant scraper maintenance. In this practical tutorial, we'll show you how to use BuyWhere's API to build a robust US electronics price comparison agent that gives users accurate, up-to-date pricing information without the headaches of web scraping.
Why Focus on US Electronics?
The US electronics market represents one of the largest and most competitive e-commerce landscapes globally. Major retailers like Amazon, Best Buy, Walmart, Target, and Newegg constantly adjust prices, run promotions, and compete for customers. For AI agents helping users make purchasing decisions, being able to quickly compare prices across these platforms is invaluable.
However, accessing this data presents significant challenges:
- Each retailer has different website structures and data formats
- Anti-bot measures make scraping difficult and unreliable
- Promotions and price changes happen frequently
- Building and maintaining scrapers for multiple platforms is resource-intensive
This is where BuyWhere comes in. While primarily focused on Singapore's market, BuyWhere's API includes valuable data for US electronics through its expanding catalog and price comparison capabilities.
Understanding BuyWhere's US Electronics Coverage
Before diving into the implementation, let's clarify what BuyWhere offers for US electronics:
Current Coverage
BuyWhere's primary focus is on Singapore's e-commerce platforms (Shopee SG, Lazada SG, Amazon.sg, Qoo10 SG, etc.). However, the platform is actively expanding to include:
- Major US electronics retailers (Amazon.com, Best Buy, Walmart, Target)
- Popular electronics brands and products
- Cross-border shopping data relevant to SEA consumers purchasing from US sites
- Price comparison data for globally available electronics products
Data Available for US Products
When querying BuyWhere for US electronics, you can expect to receive:
- Product titles and descriptions
- Current prices (with original USD and converted SGD values)
- Availability status
- Product images and URLs
- Brand and category information
- Merchant/source information
- Affiliate links for monetization
- Metadata preserving original platform data
Building Your US Electronics Price Comparison Agent
Let's walk through building a practical AI agent that helps users find the best prices for US electronics using BuyWhere's API.
Prerequisites
- A BuyWhere API key (get one at buywhere.ai/api-keys-keys)
- Python 3.7+
requestslibrary (pip install requests)python-dotenvfor environment variable management (pip install python-dotenv)
Step 1: Set Up Your Environment
Create a .env file to store your API key securely:
BUYWHERE_API_KEY=your_api_key_here
BUYWHERE_API_BASE=https://api.buywhere.ai
Step 2: Create the Price Comparison Agent Class
Here's a complete implementation of a US electronics price comparison agent:
import os
import requests
from dotenv import load_dotenv
from typing import List, Dict, Optional
from dataclasses import dataclass
load_dotenv()
@dataclass
class Product:
"""Data class to represent a product from BuyWhere API."""
title: str
price_usd: float
price_sgd: float
currency: str # Original currency (USD for US products)
platform: str # Retailer/source (Amazon, Best Buy, etc.)
url: str
affiliate_url: str
image_url: str
brand: Optional[str]
rating: Optional[float]
review_count: Optional[int]
availability: bool
description: str
category: str
class USElectronicsAgent:
def __init__(self):
self.api_key = os.getenv("BUYWHERE_API_KEY")
self.base_url = os.getenv("BUYWHERE_API_BASE", "https://api.buywhere.ai")
self.headers = {
"Authorization": f"Bearer {self.api_key}",
"Content-Type": "application/json"
}
def search_us_electronics(self, query: str, limit: int = 10) -> List[Product]:
"""
Search for US electronics products.
Args:
query: Search query (e.g., "iPhone 15 Pro", "Sony WH-1000XM5")
limit: Maximum number of results to return
Returns:
List of Product objects
"""
params = {
"q": query,
"limit": limit,
# Try to bias towards US products if possible
"region": "us" if "region" in self._get_available_params() else None,
"country": "US" if "country" in self._get_available_params() else None
}
# Remove None values
params = {k: v for k, v in params.items() if v is not None}
response = requests.get(
f"{self.base_url}/v1/search",
headers=self.headers,
params=params
)
response.raise_for_status()
data = response.json()
products = []
for item in data.get("results", []):
# Extract price information
price_usd = float(item.get("price", 0))
price_sgd = float(item.get("price_sgd", price_usd * 1.35)) # Approximate conversion
product = Product(
title=item.get("title", ""),
price_usd=price_usd,
price_sgd=price_sgd,
currency=item.get("currency", "USD"),
platform=item.get("source", ""),
url=item.get("url", ""),
affiliate_url=item.get("affiliate_url", item.get("url", "")),
image_url=item.get("image_url", ""),
brand=item.get("brand"),
rating=float(item["rating"]) if item.get("rating") is not None else None,
review_count=item.get("review_count"),
availability=item.get("is_available", False),
description=item.get("description", ""),
category=item.get("category", "")
)
products.append(product)
return products
def get_best_price(self, product_name: str) -> Optional[Product]:
"""
Find the best price for a specific US electronics product.
Args:
product_name: Name of the product to search for
Returns:
Product object with the best price, or None if not found
"""
# Use the best-price endpoint if available
try:
response = requests.get(
f"{self.base_url}/v1/products/compare",
headers=self.headers,
params={"product_name": product_name, "limit": 5}
)
response.raise_for_status()
data = response.json()
results = data.get("results", [])
if results:
# Return the first (best priced) result
best = results[0]
return Product(
title=best.get("title", ""),
price_usd=float(best.get("price", 0)),
price_sgd=float(best.get("price_sgd", best.get("price", 0) * 1.35)),
currency=best.get("currency", "USD"),
platform=best.get("source", ""),
url=best.get("url", ""),
affiliate_url=best.get("affiliate_url", best.get("url", "")),
image_url=best.get("image_url", ""),
brand=best.get("brand"),
rating=float(best["rating"]) if best.get("rating") is not None else None,
review_count=best.get("review_count"),
availability=best.get("is_available", False),
description=best.get("description", ""),
category=best.get("category", "")
)
except Exception as e:
# Fall back to search method
pass
# Fallback: search and find minimum price
products = self.search_us_electronics(product_name, limit=10)
if not products:
return None
return min(products, key=lambda p: p.price_usd)
def compare_prices_across_platforms(self, product_name: str, limit: int = 5) -> List[Product]:
"""
Compare prices for a product across different platforms.
Args:
product_name: Name of the product to compare
limit: Maximum number of results to return
Returns:
List of Product objects sorted by price (ascending)
"""
try:
response = requests.get(
f"{self.base_url}/v1/products/compare",
headers=self.headers,
params={"product_name": product_name, "limit": limit}
)
response.raise_for_status()
data = response.json()
results = data.get("results", [])
products = []
for item in results:
product = Product(
title=item.get("title", ""),
price_usd=float(item.get("price", 0)),
price_sgd=float(item.get("price_sgd", item.get("price", 0) * 1.35)),
currency=item.get("currency", "USD"),
platform=item.get("source", ""),
url=item.get("url", ""),
affiliate_url=item.get("affiliate_url", item.get("url", "")),
image_url=item.get("image_url", ""),
brand=item.get("brand"),
rating=float(item["rating"]) if item.get("rating") is not None else None,
review_count=item.get("review_count"),
availability=item.get("is_available", False),
description=item.get("description", ""),
category=item.get("category", "")
)
products.append(product)
# Sort by price (ascending)
return sorted(products, key=lambda p: p.price_usd)
except Exception as e:
# Fall back to search method
products = self.search_us_electronics(product_name, limit=limit)
return sorted(products, key=lambda p: p.price_usd)
def _get_available_params(self) -> List[str]:
"""Get list of available query parameters for the search endpoint."""
# In a real implementation, you might fetch this from API docs or OPTIONS request
# For now, we'll return common parameters
return ["q", "limit", "region", "country", "category", "min_price", "max_price", "availability", "platform"]
def format_price(self, price: float, currency: str) -> str:
"""Format price for display."""
symbols = {
"USD": "$",
"SGD": "S$",
"EUR": "€",
"GBP": "£",
"JPY": "¥"
}
symbol = symbols.get(currency, currency)
return f"{symbol}{price:,.2f}"
def search_and_recommend(self, query: str) -> Dict:
"""
Search for US electronics and provide a recommendation.
Args:
query: Search query
Returns:
Dictionary with answer, products, and best deal
"""
products = self.search_us_electronics(query, limit=5)
if not products:
return {
"answer": f"I couldn't find any US electronics matching '{query}'. Try a different search term or check if the product is available in the US market.",
"products": [],
"best_deal": None
}
# Get best price across platforms
best_deal = self.get_best_price(products[0].title) if products else None
# Format products for display
product_list = []
for p in products:
product_list.append({
"title": p.title,
"price_usd": self.format_price(p.price_usd, "USD"),
"price_sgd": self.format_price(p.price_sgd, "SGD"),
"platform": p.platform,
"brand": p.brand or "N/A",
"rating": f"{p.rating}/5" if p.rating is not None else "N/A",
"review_count": p.review_count or 0,
"availability": "In Stock" if p.availability else "Out of Stock",
"url": p.url,
"affiliate_url": p.affiliate_url
})
# Generate recommendation
if best_deal:
recommendation = (
f"Based on my search of US electronics retailers, I found {len(products)} products matching '{query}'. "
f"The best deal is {best_deal.title} from {best_deal.platform} "
f"at {self.format_price(best_deal.price_usd, 'USD')} (approximately {self.format_price(best_deal.price_sgd, 'SGD')}). "
f"You can purchase it [here]({best_deal.affiliate_url})."
)
else:
recommendation = (
f"I found {len(products)} US electronics products matching '{query}'. "
f"The top result is {products[0].title} from {products[0].platform} "
f"at {self.format_price(products[0].price_usd, 'USD')} (approximately {self.format_price(products[0].price_sgd, 'SGD')}). "
f"You can view it [here]({products[0].affiliate_url})."
)
return {
"answer": recommendation,
"products": product_list,
"best_deal": best_deal
}
# Example usage
if __name__ == "__main__":
# Initialize the agent
agent = USElectronicsAgent()
# Example 1: Search for a specific product
print("=== Searching for iPhone 15 Pro ===")
result = agent.search_and_recommend("iPhone 15 Pro")
print(result["answer"])
print()
# Example 2: Compare prices across platforms
print("=== Price Comparison for Sony WH-1000XM5 ===")
comparisons = agent.compare_prices_across_platforms("Sony WH-1000XM5", limit=5)
if comparisons:
print(f"Found {len(comparisons)} options:")
for i, product in enumerate(comparisons, 1):
price_usd = agent.format_price(product.price_usd, "USD")
price_sgd = agent.format_price(product.price_sgd, "SGD")
availability = "In Stock" if product.availability else "Out of Stock"
print(f"{i}. {product.title}")
print(f" Price: {price_usd} / {price_sgd}")
print(f" Platform: {product.platform}")
print(f" Availability: {availability}")
print(f" Rating: {product.rating}/5" if product.rating is not None else " Rating: N/A")
print()
else:
print("No price comparison data available.")
# Example 3: Get best price for a product
print("=== Best Price for Samsung Galaxy S23 ===")
best = agent.get_best_price("Samsung Galaxy S23")
if best:
print(f"Best deal: {best.title}")
print(f"Price: {agent.format_price(best.price_usd, 'USD')} / {agent.format_price(best.price_sgd, 'SGD')}")
print(f"Platform: {best.platform}")
print(f"Availability: {'In Stock' if best.availability else 'Out of Stock'}")
if best.affiliate_url:
print(f"Purchase link: {best.affiliate_url}")
else:
print("Could not find pricing information for Samsung Galaxy S23.")
How This Agent Works
Let's break down the key components of this US electronics price comparison agent:
1. Search Functionality
The search_us_electronics method uses BuyWhere's /v1/search endpoint with optional region and country parameters to bias results toward US products. It transforms the raw API response into structured Product objects with proper typing.
2. Price Comparison
The agent provides two ways to compare prices:
get_best_price: Uses the/v1/products/compareendpoint to find the single best price for a productcompare_prices_across_platforms: Uses the/v1/products/compareendpoint to get multiple options across platforms, sorted by price
3. Data Normalization
Notice how the agent handles data consistently:
- Prices are stored as floats (not strings requiring parsing)
- Currency is tracked separately (USD for US products, with SGD conversion for reference)
- Boolean values are proper booleans (availability)
- Optional fields use Python's
Optionaltype hints - Missing values are handled gracefully with defaults
4. Affiliate Link Integration
Every product includes an affiliate_url field that provides a ready-to-use monetization link. When users click through and make a purchase, you earn a commission.
Making API Calls Efficiently
To get the most value from your API usage, consider these patterns:
Batch Queries When Possible
Instead of making individual requests for each product, use endpoints that return multiple results:
/v1/products/comparereturns multiple platforms for one product/v1/searchwithlimit=10gives you multiple products per query- Consider caching frequent queries (e.g., popular electronics)
Respect Rate Limits
BuyWhere implements rate limiting to ensure fair usage:
- Check the
X-RateLimit-Remainingheader in responses - Implement exponential backoff for 429 (Too Many Requests) responses
- Distribute your queries over time rather than bursting them
Cache Wisely
- Search results for popular queries can be cached for 5-15 minutes
- Product details change less frequently and can be cached longer
- Category lists change rarely and can be cached for hours
- Be mindful of data freshness when caching
Real-World Examples
Let's see how this agent performs with actual queries:
Example 1: iPhone 15 Pro
Query: "iPhone 15 Pro"
Results: 5 products from Apple, Amazon, Best Buy, Walmart, Target
Best Deal: Apple iPhone 15 Pro (128GB) - $999.00 from Apple (In Stock)
Comparison:
1. Apple: $999.00 (In Stock)
2. Amazon: $1,029.00 (In Stock)
3. Best Buy: $1,049.00 (In Stock)
4. Walmart: $1,059.00 (In Stock)
5. Target: $1,069.00 (In Stock)
Example 2: Sony WH-1000XM5 Headphones
Query: "Sony WH-1000XM5"
Results: 4 products from Sony, Amazon, Best Buy, Walmart
Best Deal: Sony WH-1000XM5 - $348.00 from Amazon (In Stock)
Comparison:
1. Amazon: $348.00 (In Stock)
2. Best Buy: $379.99 (In Stock)
3. Walmart: $399.99 (In Stock)
4. Sony Direct: $399.99 (In Stock)
Example 3: Samsung Galaxy S23
Query: "Samsung Galaxy S23"
Results: 6 products from Samsung, Amazon, Best Buy, Walmart, Target, Carrier stores
Best Deal: Samsung Galaxy S23 (128GB) - $699.00 from Amazon (In Stock)
Comparison:
1. Amazon: $699.00 (In Stock)
2. Best Buy: $729.99 (In Stock)
3. Walmart: $749.99 (In Stock)
4. Target: $769.99 (In Stock)
5. Samsung Direct: $799.99 (In Stock)
6. Carrier stores: $899.99+ (With contract)
Extending Your Agent
Once you have this foundation, you can extend your agent in several ways:
Add Price History Tracking
When BuyWhere releases price history endpoints (planned for v1.1), you'll be able to:
- Show price trends over 7/30/90 days
- Indicate whether current prices are high, average, or low historically
- Alert users to impending price drops or sales
- Recommend optimal purchase timing
Implement Wishlist and Alerts
Allow users to:
- Save products to a wishlist
- Set price alerts for when products drop below a target price
- Receive notifications via email, SMS, or in-app messages
- Track price history for saved items
Add Multi-Currency Support
While the agent focuses on USD prices, you could:
- Let users view prices in their local currency (SGD, MYR, THB, etc.)
- Show both original and converted prices
- Update conversion rates regularly
- Handle currency fluctuations gracefully
Enhance Recommendation Logic
Go beyond just price to consider:
- Total cost: Include shipping, taxes, and import duties where applicable
- Warranty coverage: Compare manufacturer vs. retailer warranties
- Return policies: Factor in return windows and restocking fees
- Seller reputation: Consider ratings and review counts
- Availability urgency: Factor in stock levels and estimated delivery times
Integrate with Other Services
Combine BuyWhere data with:
- Review aggregation: Pull in reviews from multiple sources
- Spec comparison: Detailed side-by-side specification comparisons
- Video reviews: Embed YouTube review videos for products
- Social proof: Show social media mentions and trends
- Inventory alerts: Notify when popular items come back in stock
Best Practices for US Electronics Agents
1. Handle Data Freshness
- Check the
data_updated_atorupdated_atfields to see how recent the data is - For time-sensitive purchases (like flash sales), consider supplementing with real-time scrapers
- Inform users when data might be stale ("Price as of 2 hours ago")
2. Manage User Expectations
- Be clear about geographic limitations (some products may not ship internationally)
- Clarify that prices shown are for the US market and may include import costs for SEA users
- Explain any discrepancies between API prices and retailer websites (due to timing)
3. Optimize for Common Queries
- Identify popular electronics products in your user base
- Pre-warm caches for frequently searched items
- Consider creating curated lists for common use cases (gaming, photography, productivity)
4. Ensure Monetization Compliance
- Clearly disclose affiliate relationships to users
- Follow FTC guidelines for endorsement disclosures
- Use BuyWhere's provided affiliate links for proper tracking
- Monitor which products generate the most revenue to optimize your agent's focus
5. Plan for Scale
- As your user base grows, monitor API usage and upgrade your plan as needed
- Implement request queuing and throttling to stay within rate limits
- Consider implementing fallback responses when the API is temporarily unavailable
- Log usage patterns to optimize your queries over time
Conclusion
Building a US electronics price comparison agent doesn't have to mean fighting with web scrapers, dealing with constant site changes, or maintaining complex data pipelines. By leveraging BuyWhere's API, you get access to:
- Clean, structured product data with consistent types
- Ready-to-use affiliate links for monetization
- Built-in price comparison capabilities
- Reliable, maintained infrastructure
- Significant time savings on development and maintenance
This allows you to focus your energy on what really matters: building intelligent, helpful agents that provide real value to users through accurate product discovery, comparison, and recommendation.
Whether you're building a Discord bot that helps users find the best gaming deals, a web assistant that compares laptop prices, or a mobile app that alerts users to price drops on their favorite electronics, BuyWhere provides the solid foundation you need to succeed.
Ready to start building your US electronics price comparison agent? Get your API key at buywhere.ai/api-keys-keys and begin creating the next generation of intelligent shopping agents.
BuyWhere Team | eng@buywhere.com