← Back to documentation

agent-onboarding-flow

Agent Onboarding Flow: API Key Signup & Quickstart

A step-by-step guide for AI agent developers to get onboarded with BuyWhere's agent-native product catalog API in under 10 minutes.

Overview

This onboarding flow will guide you through:

  1. ✅ Getting your API key (signup)
  2. 🚀 Making your first API call (quickstart)
  3. 🔧 Exploring key features for AI agents
  4. 💡 Building your first agent integration

Step 1: Get Your API Key (Signup)

Option A: Self-Service (Recommended for Development)

If you have access to a development environment, you can bootstrap your first API key:

# 1. Check if any API keys exist (should return 0 for fresh install)
curl http://localhost:8000/keys/bootstrap
# Response: {"detail":"Bootstrap is only allowed when no API keys exist..."} (if keys exist)

# 2. If no keys exist, create your first key
curl -X POST http://localhost:8000/keys/bootstrap \
  -H "Content-Type: application/json" \
  -d '{"name":"My AI Agent"}'

Response:

{
  "key_id": "uuid-of-your-key",
  "raw_key": "bw_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
  "name": "My AI Agent",
  "tier": "basic",
  "message": "Store this key securely — it will not be shown again. This is your first API key."
}

Important: Save the raw_key — it will not be displayed again!

Option B: Request from Team (Production)

For production access, contact the BuyWhere team to provision an API key. You'll receive:

  • A key ID (UUID) — used for JWT tokens
  • A raw key (bw_live_xxxxx) — used directly as Bearer token

Step 2: Make Your First API Call (Quickstart)

2.1 Test Connectivity

Verify the API is reachable:

curl https://api.buywhere.ai/health

Expected response:

{"status":"ok"}

2.2 Search for Products

Make your first authenticated request:

curl "https://api.buywhere.ai/v2/products?q=wireless%20headphones&limit=3" \
  -H "Authorization: Bearer bw_live_your_api_key_here"

Expected response structure:

{
  "total": 248,
  "limit": 3,
  "offset": 0,
  "items": [
    {
      "id": 78234,
      "name": "Sony WH-1000XM5 Wireless Headphones",
      "price": "449.00",
      "currency": "SGD",
      "confidence_score": 0.95,
      "availability_prediction": "high",
      "competitor_count": 12,
      "price_trend": "stable",
      "buy_url": "https://shopee.sg/product/12345",
      "affiliate_url": "https://api.buywhere.ai/v1/track/abc123"
    }
  ],
  "has_more": true
}

Step 3: Explore Key Features for AI Agents

3.1 Agent-Native Enhancements

The v2 API includes special fields optimized for AI agents:

FieldPurposeExample Value
confidence_scoreData reliability (0.0-1.0)0.95
availability_predictionStock availability forecast"high"/"medium"/"low"
competitor_countNumber of sellers for same product12
price_trendRecent price movement"up"/"down"/"stable"

3.2 Key Endpoints

EndpointPurposeBest For
GET /v2/productsProduct search with filtersDiscovery & browsing
GET /v2/products/{id}Detailed product infoSpecific product lookup
POST /v2/products/batch-detailsMultiple product lookup (max 100)Price comparison, inventory checks
GET /v2/agents/exploreRandomized product discoveryMarket analysis, serendipitous discovery
GET /v2/trendingPopular products by viewsTrend detection, viral product identification

Step 4: Build Your First Agent Integration

4.1 Basic Product Search Agent (Python)

import os
import requests

class BuyWhereAgent:
    def __init__(self, api_key: str):
        self.api_key = api_key
        self.base_url = "https://api.buywhere.ai/v2"
        self.headers = {"Authorization": f"Bearer {api_key}"}
    
    def search_products(self, query: str, limit: int = 10):
        """Search for products and return formatted results for agent consumption."""
        response = requests.get(
            f"{self.base_url}/products",
            headers=self.headers,
            params={"q": query, "limit": limit, "currency": "SGD"}
        )
        response.raise_for_status()
        return response.json()
    
    def get_product_details(self, product_id: int):
        """Get detailed information for a specific product."""
        response = requests.get(
            f"{self.base_url}/products/{product_id}",
            headers=self.headers
        )
        response.raise_for_status()
        return response.json()
    
    def compare_multiple_products(self, product_ids: list):
        """Efficiently check multiple products (max 100)."""
        response = requests.post(
            f"{self.base_url}/products/batch-details",
            headers=self.headers,
            json={"product_ids": product_ids}
        )
        response.raise_for_status()
        return response.json()

# Usage example
if __name__ == "__main__":
    agent = BuyWhereAgent(os.getenv("BUYWHERE_API_KEY"))
    
    # Search for gaming laptops
    results = agent.search_products("gaming laptop", limit=5)
    
    print(f"Found {results['total']} gaming laptops")
    for product in results['items']:
        if product.get('confidence_score', 0) > 0.8:  # High confidence only
            print(f"• {product['name']}")
            print(f"  Price: SGD {product['price']}")
            print(f"  Confidence: {product['confidence_score']:.2f}")
            print(f"  Availability: {product.get('availability_prediction', 'unknown')}")
            print(f"  Competitors: {product.get('competitor_count', 0)} sellers")
            print()

### 4.2 Price Comparison Agent

```python
def find_best_price(agent, product_query):
    """Find the best price for a product across all platforms."""
    # Search for the product
    search_results = agent.search_products(product_query, limit=1)
    if not search_results['items']:
        return None
    
    product_id = search_results['items'][0]['id']
    
    # Get detailed info (would ideally use compare endpoint if available)
    product_details = agent.get_product_details(product_id)
    
    return {
        'product': product_details['items'][0],
        # In a full implementation, you'd aggregate data from multiple sources
        # using the batch endpoint or dedicated compare functionality
    }

# Usage
best_deal = find_best_price(agent, "iPhone 15 Pro")
if best_deal:
    p = best_deal['product']
    print(f"Best found: {p['name']} for SGD {p['price']}")
    print(f"Confidence: {p['confidence_score']:.2f}")

Step 5: Best Practices for AI Agents

5.1 Data Quality

  • Filter by confidence: Use confidence_score > 0.8 for reliable data
  • Check availability: Prioritize items with "availability_prediction": "high"
  • Validate freshness: Check updated_at timestamps for recent data

5.2 Performance Optimization

  • Use batch endpoints: For multiple product checks, use /batch-details (100 IDs max)
  • Leverage caching: The API caches responses; repeated identical queries are faster
  • Implement pagination: Use limit and offset for large result sets

5.3 Error Handling

def safe_search(agent, query):
    try:
        return agent.search_products(query)
    except requests.exceptions.HTTPError as e:
        if e.response.status_code == 401:
            raise Exception("Invalid or expired API key")
        elif e.response.status_code == 429:
            raise Exception("Rate limited - retry after delay")
        elif e.response.status_code >= 500:
            raise Exception("API temporarily unavailable")
        else:
            raise Exception(f"Request failed: {e.response.status_code}")
    except requests.exceptions.RequestException as e:
        raise Exception(f"Network error: {str(e)}")

5.4 Rate Limit Management

  • Monitor headers: Check X-RateLimit-Remaining in responses
  • Implement backoff: Use exponential backoff for 429 responses
  • Cache results: Store frequent queries to reduce API calls
  • Batch requests: Combine multiple needs into single API calls when possible

Step 6: Common Use Cases & Templates

6.1 Deal Alert Agent

def scan_for_deals(agent, max_price=100, min_confidence=0.8):
    """Find products likely to be good deals."""
    results = agent.search_products("", limit=50, max_price=max_price)
    
    deals = []
    for product in results['items']:
        # Simple heuristic: falling price + high confidence = potential deal
        if (product.get('confidence_score', 0) >= min_confidence and
            product.get('price_trend') == 'down' and
            product.get('availability_prediction') == 'high'):
            deals.append(product)
    
    return sorted(deals, key=lambda x: x['confidence_score'], reverse=True)[:10]

6.2 Product Recommendation Agent

def recommend_products(agent, category=None, budget=500, min_reviews=10):
    """Recommend products based on quality and value."""
    results = agent.search_products(
        "",
        limit=20,
        category=category,
        max_price=budget,
        sort_by="rating"  # Start with highly rated
    )
    
    # Filter for quality signals
    quality_products = [
        p for p in results['items']
        if (p.get('confidence_score', 0) > 0.85 and
            p.get('in_stock') == True and
            p.get('review_count', 0) >= min_reviews)
    ]
    
    # Sort by rating (descending) then by confidence
    return sorted(
        quality_products,
        key=lambda x: (x['rating'], x['confidence_score']),
        reverse=True
    )[:5]

6.3 Market Analysis Agent

def analyze_market_trends(agent, category="electronics"):
    """Analyze current market trends in a category."""
    # Get trending products
    trending = agent.get_trending(category=category, limit=20)
    
    # Get exploratory/random sample for broader view
    exploratory = agent.explore_products(category=category, limit=20)
    
    # Analyze price trends
    trending_up = [p for p in trending['items'] if p.get('price_trend') == 'up']
    trending_down = [p for p in trending['items'] if p.get('price_trend') == 'down']
    
    return {
        'trending_products': len(trending['items']),
        'price_increasing': len(trending_up),
        'price_decreasing': len(trending_down),
        'stable_prices': len(trending['items']) - len(trending_up) - len(trending_down),
        'avg_confidence': sum(p.get('confidence_score', 0) for p in trending['items']) / len(trending['items'])
    }

Step 7: Next Steps & Resources

7.1 Explore Further

7.2 Join the Community

7.3 Get Support

Troubleshooting

Common Issues

  1. "Invalid API key" (401)

    • Double-check your API key format (bw_live_...)
    • Ensure you're using Authorization: Bearer <key> header
    • Verify key hasn't expired or been revoked
  2. "Rate limit exceeded" (429)

    • Check Retry-After header for delay duration
    • Implement caching or reduce request frequency
    • Consider upgrading your API tier
  3. "No results found"

    • Try broader search terms
    • Verify product exists in Singapore market
    • Check spelling and try alternative keywords
  4. Network/connection issues

    • Verify API endpoint: https://api.buywhere.ai
    • Check your internet connection
    • Try the health endpoint first: /health

Quick Reference Cheat Sheet

Essential Commands

# Health check
curl https://api.buywhere.ai/health

# Search products
curl "https://api.buywhere.ai/v2/products?q=iphone&limit=5" \
  -H "Authorization: Bearer bw_live_your_key"

# Get product details
curl "https://api.buywhere.ai/v2/products/12345" \
  -H "Authorization: Bearer bw_live_your_key"

# Batch product lookup (up to 100 IDs)
curl -X POST "https://api.buywhere.ai/v2/products/batch-details" \
  -H "Authorization: Bearer bw_live_your_key" \
  -H "Content-Type: application/json" \
  -d '{"product_ids": [12345, 67890, 11111]}'

Response Fields to Check First

  • items[].name - Product name
  • items[].price - Current price
  • items[].currency - Price currency (usually SGD)
  • items[].confidence_score - Data quality indicator (0.0-1.0)
  • items[].availability_prediction - Stock level prediction
  • items[].buy_url - Direct purchase link
  • items[].affiliate_url - Affiliate-tracked link

Status Codes

  • 200 - Success
  • 400 - Bad request (check parameters)
  • 401 - Unauthorized (check API key)
  • 429 - Rate limited (slow down)
  • 422 - Validation error (fix request format)
  • 500 - Server error (try again later)

You're now onboarded! 🎉 You have your API key, you've made your first API call, and you know how to build AI agent integrations with BuyWhere.

Start building your AI-powered shopping agent today!