# ShopSavvy Data API - Documentation

> Complete developer guide for the ShopSavvy Data API

*Source: https://shopsavvy.com/data/documentation*

---

## Table of Contents

Each entry is also its own page, linked in parentheses. Changelog: https://shopsavvy.com/data/changelog (RSS: https://shopsavvy.com/data/changelog.xml). OpenAPI spec: https://api.shopsavvy.com/v1/openapi.json

- **Getting Started**
  - [Authenticate with an API key](#overview--authentication) (https://shopsavvy.com/data/documentation/authentication)
  - [Quickstart: every retailer's price for one product in 5 minutes](#quick-start-guide) (https://shopsavvy.com/data/documentation/quickstart)
  - [Credits, request limits and plans](#pricing--credits) (https://shopsavvy.com/data/documentation/pricing-credits)
- **SDKs & Libraries**
  - [TypeScript and JavaScript SDK](#typescriptjavascript-sdk) (https://shopsavvy.com/data/documentation/sdk-typescript)
  - [Python SDK](#python-sdk) (https://shopsavvy.com/data/documentation/sdk-python)
  - [Ruby SDK](#ruby-sdk) (https://shopsavvy.com/data/documentation/sdk-ruby)
  - [Go SDK](#go-sdk) (https://shopsavvy.com/data/documentation/sdk-go)
  - [Java SDK](#java-sdk) (https://shopsavvy.com/data/documentation/sdk-java)
  - [PHP SDK](#php-sdk) (https://shopsavvy.com/data/documentation/sdk-php)
  - [C# and .NET SDK](#c-sdk) (https://shopsavvy.com/data/documentation/sdk-csharp)
  - [Rust SDK](#rust-sdk) (https://shopsavvy.com/data/documentation/sdk-rust)
  - [Swift SDK](#swift-sdk) (https://shopsavvy.com/data/documentation/sdk-swift)
  - [Kotlin SDK](#kotlin-sdk) (https://shopsavvy.com/data/documentation/sdk-kotlin)
  - [Choose an SDK](#sdk-comparison) (https://shopsavvy.com/data/documentation/sdk-comparison)
- **AI Integration**
  - [Give AI assistants live product prices with the MCP server](#model-context-protocol-server) (https://shopsavvy.com/data/documentation/mcp-server)
  - [Connect Claude, Cursor and other MCP clients](#claude-desktop-setup) (https://shopsavvy.com/data/documentation/mcp-installation)
  - [Tools the ShopSavvy MCP server provides](#available-ai-tools) (https://shopsavvy.com/data/documentation/mcp-tools)
  - [Example prompts for the ShopSavvy MCP server](#usage-examples) (https://shopsavvy.com/data/documentation/mcp-usage)
- **Products API**
  - [Look up a product by UPC, ASIN, URL or model number](#retrieving-product-details) (https://shopsavvy.com/data/documentation/product-details)
  - [Get product details as CSV](#retrieving-product-details-in-csv-format) (https://shopsavvy.com/data/documentation/product-details-csv)
  - [Search products by keyword](#searching-products-by-keyword) (https://shopsavvy.com/data/documentation/product-search)
  - [Look up up to 100 products in one request](#batch-product-lookup) (https://shopsavvy.com/data/documentation/product-batch)
- **Pricing API**
  - [Get a product's current price at every retailer](#retrieving-offers-for-products-at-all-retailers) (https://shopsavvy.com/data/documentation/offers-all-retailers)
  - [Get a product's price at one retailer](#retrieving-offers-for-a-single-retailer) (https://shopsavvy.com/data/documentation/offers-single-retailer)
  - [Export current prices as CSV](#retrieving-offers-in-csv-format) (https://shopsavvy.com/data/documentation/offers-csv)
  - [Get price history for a product](#retrieving-offers-with-historical-offer-data) (https://shopsavvy.com/data/documentation/offers-history)
- **Scheduling API**
  - [Schedule hourly, daily or weekly price monitoring](#enabling-scheduled-refreshes-for-products) (https://shopsavvy.com/data/documentation/schedule-product)
  - [Change a product's monitoring schedule](#changing-refresh-schedule-for-products) (https://shopsavvy.com/data/documentation/update-schedule)
  - [Stop monitoring a product](#disabling-scheduled-refreshes-for-products) (https://shopsavvy.com/data/documentation/unschedule-product)
  - [List the products you are monitoring](#retrieve-products-currently-enabled-for-scheduled-refreshes) (https://shopsavvy.com/data/documentation/get-scheduled)
- **Deals & Reviews**
  - [Get the deals feed](#browse-deals) (https://shopsavvy.com/data/documentation/deals)
  - [Get a product's TLDR review](#get-tldr-review-for-product) (https://shopsavvy.com/data/documentation/reviews)
- **Webhooks**
  - [Get price-drop and availability webhooks](#webhooks) (https://shopsavvy.com/data/documentation/webhooks)
- **Account & Tools**
  - [Check your credit usage](#get-api-usage-statistics) (https://shopsavvy.com/data/documentation/usage-stats)
  - [Turn a CSV of barcodes into one API request](#csv-to-api-request-converter) (https://shopsavvy.com/data/documentation/csv-converter)
- **Recipes**
  - [Recipes: complete scripts for common Data API tasks](#recipes) (https://shopsavvy.com/data/documentation/recipes)
  - [Turn a barcode list into product details](#recipe-barcode-list-to-product-details) (https://shopsavvy.com/data/documentation/recipe-barcode-list)
  - [Monitor prices with scheduled refreshes and webhooks](#recipe-price-monitor-with-webhooks) (https://shopsavvy.com/data/documentation/recipe-price-monitor)
  - [Export 90 days of price history to CSV](#recipe-export-90-days-of-price-history-to-csv) (https://shopsavvy.com/data/documentation/recipe-price-history-export)
  - [Build a competitor price position report](#recipe-competitor-price-position-report) (https://shopsavvy.com/data/documentation/recipe-price-position)
  - [Give Claude Code live prices with the MCP server](#recipe-live-prices-in-claude-code) (https://shopsavvy.com/data/documentation/recipe-claude-code)
- **Reference**
  - [Error codes and how to fix them](#errors) (https://shopsavvy.com/data/documentation/errors)
  - [Rate limits](#rate-limits) (https://shopsavvy.com/data/documentation/rate-limits)
  - [Versioning and deprecation policy](#versioning--deprecation) (https://shopsavvy.com/data/documentation/versioning)
  - [OpenAPI specification](#openapi-specification) (https://shopsavvy.com/data/documentation/openapi)
  - [All Data API endpoints and their credit costs](#quick-reference-all-endpoints) (https://shopsavvy.com/data/documentation/endpoints)

---

## Getting Started

### Overview & Authentication

- First you'll need to [subscribe to one of our plans](https://shopsavvy.com/data#pricing).
- Once you've subscribed, you'll be redirected to your [Data API Dashboard](https://shopsavvy.com/data/dashboard).
- Go to [API Keys](https://shopsavvy.com/data/api-keys) to create and manage your API keys.
- Use your API keys to authenticate with the API.

**Base URL:** `https://api.shopsavvy.com/v1`

**Authentication:** Include your API key in the `Authorization` header as a Bearer token, or as an `api_key` query parameter.

**Authentication Examples:**

**Header (Recommended):**
```
Authorization: Bearer ss_live_abc123...
```

**Query Parameter:**
```
GET /v1/products?ids=123&api_key=ss_live_abc123...
```

That's it. You're now ready to start requesting data from the API. The [Quick Start Guide](#quick-start-guide) walks through a first request.

**OpenAPI spec:** the full API description is at [`https://api.shopsavvy.com/v1/openapi.json`](https://api.shopsavvy.com/v1/openapi.json) (OpenAPI 3.0). Import it into Postman, Insomnia or a client generator. See [OpenAPI Specification](#openapi-specification).

### Quick Start Guide

**Get every retailer's price for one product in about 5 minutes.** You'll make one request with `curl`, read the response, and know what it cost.

#### Using an AI agent? Paste this first

If you work in Claude Code, Cursor, ChatGPT or another agent, hand it your key and let it make the first call. In Claude Code, one command connects the ShopSavvy MCP server:

```bash
claude mcp add --transport http shopsavvy https://api.shopsavvy.com/mcp \
  --header "Authorization: Bearer ss_live_your_key_here"
```

In any other agent, paste this prompt (with your key in it):

```text
Use the ShopSavvy Data API to look up products and compare current prices across retailers.

- OpenAPI spec: https://api.shopsavvy.com/v1/openapi.json (read it first)
- Base URL: https://api.shopsavvy.com/v1
- Auth: send the header "Authorization: Bearer ss_live_your_key_here" on every request
- If you support MCP, connect to https://api.shopsavvy.com/mcp with the same header instead of calling REST yourself.

Start by getting every retailer's current price for UPC 611247373064 (GET /v1/products/offers?ids=611247373064), then tell me which retailer is cheapest and when each price was checked.
```

The [API Keys](https://shopsavvy.com/data/api-keys) page shows these with your key already filled in, plus an `mcp.json` block for Cursor and other MCP clients. More prompts and per-call costs: [Live Prices in Claude Code](#recipe-live-prices-in-claude-code). The same first call with `curl` follows.

#### Before you start

- **An API key.** Keys come with a Data API plan: start the [14-day Starter trial](https://shopsavvy.com/data#pricing), then copy a key from [API Keys](https://shopsavvy.com/data/api-keys). Your first key is created automatically when the subscription starts. Keys look like `ss_live_` followed by 32 characters.
- **curl.** Check it's installed with `curl --version`. Any HTTP client works; the [SDKs](#sdks--libraries) wrap the same calls.

No key yet? The [playground](https://shopsavvy.com/data/playground) shows real response shapes in your browser without one.

#### 1. Put your key in an environment variable

```bash
export SHOPSAVVY_API_KEY="ss_live_your_api_key_here"
```

#### 2. Ask for every retailer's current price for one barcode

`611247373064` is the UPC of a Keurig K-Mini coffee maker. Any identifier works in its place: UPC, EAN, ISBN, ASIN, model number, MPN, a product URL at any retailer, or a ShopSavvy product ID.

```bash
curl "https://api.shopsavvy.com/v1/products/offers?ids=611247373064" \
  -H "Authorization: Bearer $SHOPSAVVY_API_KEY"
```

#### 3. Read the response

You get the product, an `offers` array with one entry per retailer listing, and a `meta` block. This is trimmed to two offers and a few product fields; your prices and timestamps will be current, not these:

```json
{
  "success": true,
  "data": [
    {
      "title": "Keurig K-Mini Single Serve K-Cup Pod Coffee Maker, 6 to 12oz Brew size, with Cord Storage, Perfect for Small Spaces, Black",
      "brand": "Keurig",
      "shopsavvy": "products/3ONn300xybP3y66ibqc1",
      "barcode": "611247373064",
      "amazon": "B07GV2S1GS",
      "model": "K-Mini",
      "match": { "identifier": "611247373064", "by": "barcode", "candidates": 1 },
      "offers": [
        {
          "id": "4c3bb2ea-f37c-4dcd-90f4-eba7280d7473",
          "availability": "in",
          "condition": "new",
          "condition_grade": "new",
          "retailer": "Best Buy",
          "currency": "USD",
          "price": 99.99,
          "is_marketplace": false,
          "URL": "https://www.bestbuy.com/site/-/-.p?skuId=6358476",
          "timestamp": "2026-10-12T01:33:09.069Z",
          "history": []
        },
        {
          "id": "bk-93f02932398a06f9c68522ceda3a36da",
          "availability": "in",
          "condition": "used",
          "condition_grade": "unknown",
          "retailer": "Amazon",
          "currency": "USD",
          "price": 44.99,
          "seller": "Tech & Beyond",
          "is_marketplace": true,
          "URL": "https://www.amazon.com/dp/B07GV2S1GS?th=1&psc=1",
          "timestamp": "2026-10-12T01:32:49.321Z",
          "history": []
        }
      ]
    }
  ],
  "meta": {
    "request_id": "4f9d2c1e-…",
    "credits_used": 3,
    "credits_remaining": 997,
    "rate_limit_remaining": 999
  }
}
```

#### What just happened

- `match` shows which identifier produced the product and how (`barcode` is an exact match). See [How Identifiers Are Matched](#how-identifiers-are-matched).
- Each offer is one listing: `retailer`, `price` and `currency`, `availability` (omitted when unknown), `condition`, and `is_marketplace` with `seller` when a third-party seller is behind it. `timestamp` is when ShopSavvy last saw that price.
- The call cost **3 credits** (all-retailer offers, per product found). A product with no offers, or an identifier that matches nothing, costs nothing. `meta.credits_remaining` is your balance after this call; `meta.rate_limit_remaining` is how many requests you have left in the rolling hour.

#### Next steps

- Look up many products at once: pass up to 100 comma-separated identifiers in `ids`, or use [Batch Product Lookup](#batch-product-lookup).
- Track prices over time: [Price History](#retrieving-offers-with-historical-offer-data) and [Scheduled Refreshes](#enabling-scheduled-refreshes-for-products) with [Webhooks](#webhooks).
- Handle failures: every [error](#errors) has a code, an `action` and a `docs_url`.
- Use an SDK in your language:

| Language | Install | Package |
|----------|---------|---------|
| TypeScript / JavaScript | `npm install @shopsavvy/sdk` | [npm](https://www.npmjs.com/package/@shopsavvy/sdk) |
| Python | `pip install shopsavvy-sdk` | [PyPI](https://pypi.org/project/shopsavvy-sdk/) |
| Ruby | `gem install shopsavvy-sdk` | [RubyGems](https://rubygems.org/gems/shopsavvy-sdk) |
| Go | `go get github.com/shopsavvy/sdk-go` | [pkg.go.dev](https://pkg.go.dev/github.com/shopsavvy/sdk-go) |
| Java | `com.shopsavvy:shopsavvy-sdk:1.1.0` (Maven / Gradle) | [Maven Central](https://central.sonatype.com/artifact/com.shopsavvy/shopsavvy-sdk) |
| Kotlin | `implementation("com.shopsavvy:shopsavvy-sdk-kotlin:1.1.0")` | [Maven Central](https://central.sonatype.com/artifact/com.shopsavvy/shopsavvy-sdk-kotlin) |
| C# / .NET | `dotnet add package ShopSavvy.Sdk` | [NuGet](https://www.nuget.org/packages/ShopSavvy.Sdk) |
| Rust | `cargo add shopsavvy-sdk` | [crates.io](https://crates.io/crates/shopsavvy-sdk) |
| Swift | `.package(url: "https://github.com/shopsavvy/sdk-swift.git", from: "1.3.0")` | [GitHub](https://github.com/shopsavvy/sdk-swift) |
| PHP | `composer config repositories.shopsavvy vcs https://github.com/shopsavvy/sdk-php` then `composer require shopsavvy/shopsavvy-sdk-php` | [GitHub](https://github.com/shopsavvy/sdk-php) |

### Pricing & Credits

The ShopSavvy Data API uses a credit-based pricing system. Different operations cost different amounts of credits.

#### Credit Costs

| Operation | Cost |
|-----------|------|
| Retrieving Product Details | 1 credit per product found |
| Searching Products by Keyword | 1 credit per product returned |
| Current Offers (All Retailers) | 3 credits per product with offers or in-store prices |
| Current Offers (Single Retailer) | 2 credits per product with offers or in-store prices |
| Price History | Offer cost per product + 1 credit per day of the window (the per-day component is charged once per request, not per product) — charged only when offers are found |
| Schedule Product Monitoring | 1 credit per product (refreshes are not charged) |
| Browse Deals | 1 credit per 10 deals returned |
| TLDR Product Review | 1 credit per product (0 when no review exists) |
| Batch Product Lookup | 1 credit per product found (+ 3 per product that has offers or in-store prices when including offers, + 1 per product that has a review when including reviews) |

#### Request Limits

| Limit | Value |
|-------|-------|
| Identifiers per request (`ids=` on any endpoint, and `identifiers` on `POST /products/batch`) | 100 |
| Price-history window (`start` to `end`) | 366 days |

Requests over either limit are rejected with `ERR_INVALID_PARAMS` before any credits are charged. Split them into successive calls.

#### Subscription Plans

Visit the [pricing page](https://shopsavvy.com/data#pricing) to see current subscription plans and credit allocations.

#### Try it before you sign up (Live Sandbox)

The [playground](https://shopsavvy.com/data/playground) has a **Live Sandbox** mode that fires real API calls against a curated set of sample products — no account, no credit card, no credits consumed. Use it to see real response shapes before you write any code. Sample products only; start a 14-day Starter trial at [shopsavvy.com/data#pricing](https://shopsavvy.com/data#pricing) to query the full catalog.

#### Referral Program

Earn bonus API credits by referring other developers. Grab your referral link from the [Referrals page](https://shopsavvy.com/data/referrals) in your dashboard (`https://shopsavvy.com/data?ref=YOUR_CODE`) and share it — for example, in your project's README. When a developer who signs up through your link becomes a paying subscriber, bonus credits are added to your account automatically. The bonus tops up your monthly allowance and carries over until used. Rewards apply to brand-new accounts on their first paid conversion, and are reversed on refund, dispute, or cancellation within the clawback window.

---

## SDKs & Libraries

### TypeScript/JavaScript SDK

Our official TypeScript/JavaScript SDK provides a convenient way to interact with the ShopSavvy Data API from Node.js and browser environments.

- [View on GitHub](https://github.com/shopsavvy/sdk-typescript)
- [View on npm](https://www.npmjs.com/package/@shopsavvy/sdk)

#### Installation

```bash
npm install @shopsavvy/sdk
# or
yarn add @shopsavvy/data-api
# or
bun add @shopsavvy/data-api
```

#### Basic Usage

```typescript
import { createShopSavvyClient } from '@shopsavvy/data-api'

// Initialize the client
const api = createShopSavvyClient({
  apiKey: 'ss_live_your_api_key_here'
})

// Look up a product by barcode
const product = await api.getProductDetails('012345678901')
console.log(product.data.name)

// Get current prices from all retailers
const offers = await api.getCurrentOffers('012345678901')
offers.data.forEach(offer => {
  console.log(`${offer.retailer}: $${offer.price}`)
})

// Get price history
const history = await api.getPriceHistory(
  '012345678901',
  '2024-01-01',
  '2024-01-31'
)
```

#### Features

- Full TypeScript support with comprehensive type definitions
- Modern async/await API
- Automatic error handling and retry logic
- Support for both Node.js and browser environments
- Built-in request/response validation
- Comprehensive documentation and examples

#### Error Handling

```typescript
try {
  const product = await api.getProductDetails('invalid-identifier')
} catch (error) {
  if (error.message.includes('Product not found')) {
    console.log('Product does not exist')
  } else if (error.message.includes('Invalid API key')) {
    console.log('Check your API key')
  } else {
    console.log('Unexpected error:', error.message)
  }
}
```

### Python SDK

Our official Python SDK provides a convenient way to interact with the ShopSavvy Data API from Python applications with full type safety and modern async support.

- [View on GitHub](https://github.com/shopsavvy/sdk-python)
- [View on PyPI](https://pypi.org/project/shopsavvy-sdk/)

#### Installation

```bash
pip install shopsavvy-sdk
```

#### Basic Usage

```python
from shopsavvy import create_client

# Initialize the client
client = create_client("ss_live_your_api_key_here")

# Look up a product by barcode
product = client.get_product_details("012345678901")
print(product.data.name)

# Get current prices from all retailers
offers = client.get_current_offers("012345678901")
for offer in offers.data:
    print(f"{offer.retailer}: {offer.price}")

# Get price history
history = client.get_price_history(
    "012345678901",
    "2024-01-01",
    "2024-01-31"
)
```

#### Features

- Full type safety with Pydantic models
- Modern HTTP client with automatic retries
- Comprehensive error handling
- Rails integration support
- Context manager support for automatic cleanup
- Python 2.7+ compatibility

#### Context Manager Usage

```python
with create_client("ss_live_your_api_key_here") as client:
    product = client.get_product_details("012345678901")
    print(product.data.name)
# Client automatically closed
```

#### Error Handling

```python
from shopsavvy import create_client, NotFoundError, AuthenticationError

try:
    client = create_client("ss_live_your_api_key_here")
    product = client.get_product_details("invalid-identifier")
except NotFoundError:
    print("Product not found")
except AuthenticationError:
    print("Invalid API key")
except Exception as e:
    print(f"Unexpected error: {e}")
```

### Ruby SDK

Our official Ruby SDK provides a convenient way to interact with the ShopSavvy Data API from Ruby applications with idiomatic Ruby patterns and comprehensive documentation.

- [View on GitHub](https://github.com/shopsavvy/sdk-ruby)
- [View on RubyGems](https://rubygems.org/gems/shopsavvy-sdk)

#### Installation

```bash
gem install shopsavvy-sdk

# Or add to your Gemfile:
gem 'shopsavvy-sdk'
```

#### Basic Usage

```ruby
require 'shopsavvy_data_api'

# Initialize the client
client = ShopsavvyDataApi.new(api_key: "ss_live_your_api_key_here")

# Look up a product by barcode
product = client.get_product_details("012345678901")
puts product.data.name

# Get current prices from all retailers
offers = client.get_current_offers("012345678901")
offers.data.each do |offer|
  puts "#{offer.retailer}: $#{offer.price}"
end

# Get price history
history = client.get_price_history(
  "012345678901",
  "2024-01-01",
  "2024-01-31"
)
```

#### Features

- Idiomatic Ruby patterns and conventions
- Comprehensive YARD documentation
- Automatic retry logic with exponential backoff
- Convenient model methods and helpers
- Rails integration examples
- Ruby 2.7+ compatibility

#### Rails Integration

```ruby
# config/initializers/shopsavvy.rb
Rails.application.config.shopsavvy_client = ShopsavvyDataApi.new(
  api_key: Rails.application.credentials.shopsavvy_api_key
)

# In your models/controllers
client = Rails.application.config.shopsavvy_client
product = client.get_product_details(params[:barcode])
```

#### Error Handling

```ruby
begin
  client = ShopsavvyDataApi.new(api_key: "ss_live_your_api_key_here")
  product = client.get_product_details("invalid-identifier")
rescue ShopsavvyDataApi::NotFoundError => e
  puts "Product not found"
rescue ShopsavvyDataApi::AuthenticationError => e
  puts "Invalid API key"
rescue ShopsavvyDataApi::RateLimitError => e
  puts "Rate limit exceeded"
rescue ShopsavvyDataApi::APIError => e
  puts "API error: #{e.message}"
end
```

### Go SDK

Our official Go SDK provides a fast, type-safe way to interact with the ShopSavvy Data API from Go applications.

- [View on GitHub](https://github.com/shopsavvy/sdk-go)
- [View Docs on pkg.go.dev](https://pkg.go.dev/github.com/shopsavvy/sdk-go)

#### Installation

```bash
go get github.com/shopsavvy/sdk-go
```

#### Quick Start

```go
package main

import (
    "fmt"
    "log"

    "github.com/shopsavvy/sdk-go"
)

func main() {
    // Create a new client
    client, err := shopsavvy.NewClient("ss_live_your_api_key_here")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Look up a product by barcode
    product, err := client.GetProductDetails("012345678901")
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("Product: %s\n", product.Data.Name)

    // Get current offers
    offers, err := client.GetCurrentOffers("012345678901", "")
    if err != nil {
        log.Fatal(err)
    }

    for _, offer := range offers.Data {
        fmt.Printf("%s: $%.2f\n", offer.Retailer, offer.Price)
    }
}
```

#### Features

- Full type safety with Go generics
- Comprehensive error handling with custom error types
- Context support for request cancellation
- Built-in rate limiting and retry logic
- Support for both JSON and CSV response formats
- Batch operations for multiple products

### Java SDK

Our official Java SDK provides enterprise-grade reliability and performance for Java applications.

- [View on GitHub](https://github.com/shopsavvy/sdk-java)
- [Maven Central](https://central.sonatype.com/artifact/com.shopsavvy/shopsavvy-sdk)

#### Installation

**Maven:**

```xml
<dependency>
  <groupId>com.shopsavvy</groupId>
  <artifactId>shopsavvy-sdk</artifactId>
  <version>1.1.0</version>
</dependency>
```

**Gradle:**

```groovy
implementation 'com.shopsavvy:shopsavvy-sdk:1.1.0'
```

#### Quick Start

```java
import com.shopsavvy.ShopSavvyClient;
import com.shopsavvy.model.Product;
import com.shopsavvy.model.ApiResponse;

public class Example {
    public static void main(String[] args) {
        // Create a new client
        ShopSavvyClient client = new ShopSavvyClient("ss_live_your_api_key_here");

        try {
            // Get product details
            ApiResponse<Product> response = client.getProductDetails("012345678901");
            Product product = response.getData();

            System.out.println("Product: " + product.getName());
            System.out.println("Brand: " + product.getBrand());

            // Get current offers
            var offers = client.getCurrentOffers("012345678901");
            offers.getData().forEach(offer -> {
                System.out.printf("%s: $%.2f%n",
                    offer.getRetailer(), offer.getPrice());
            });

        } catch (Exception e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}
```

#### Features

- Full Java type safety with generics
- Builder pattern for configuration
- Async support with CompletableFuture
- Spring Boot auto-configuration
- Jackson JSON serialization
- Comprehensive error handling

### PHP SDK

Our official PHP SDK provides easy integration for PHP applications and frameworks like Laravel, Symfony, and CodeIgniter.

- [View on GitHub](https://github.com/shopsavvy/sdk-php)
- Packagist listing pending: install from the GitHub repository as shown below.

#### Installation

```bash
composer config repositories.shopsavvy vcs https://github.com/shopsavvy/sdk-php
composer require shopsavvy/shopsavvy-sdk-php
```

#### Quick Start

```php
<?php
require_once 'vendor/autoload.php';

use ShopSavvy\Client;

// Create a new client
$client = new Client('ss_live_your_api_key_here');

// Get product details
$product = $client->getProductDetails('012345678901');
echo "Product: " . $product['data']['name'] . "\n";

// Get current offers
$offers = $client->getCurrentOffers('012345678901');
foreach ($offers['data'] as $offer) {
    echo $offer['retailer'] . ": $" . $offer['price'] . "\n";
}

// Get price history
$history = $client->getPriceHistory(
    '012345678901',
    '2024-01-01',
    '2024-01-31'
);
```

#### Laravel Integration

```php
// config/services.php
'shopsavvy' => [
    'api_key' => env('SHOPSAVVY_API_KEY'),
],

// In your controller
use ShopSavvy\Client;

class ProductController extends Controller
{
    public function show($barcode)
    {
        $client = new Client(config('services.shopsavvy.api_key'));
        $product = $client->getProductDetails($barcode);

        return view('product.show', compact('product'));
    }
}
```

#### Features

- PSR-4 autoloading
- Laravel service provider
- Guzzle HTTP client
- Comprehensive error handling
- Support for PHP 8.0+
- Full PHPDoc documentation

### C# SDK

Our official C# SDK provides seamless integration for .NET applications, with full async/await support and strong typing.

- [View on GitHub](https://github.com/shopsavvy/sdk-csharp)
- [NuGet](https://www.nuget.org/packages/ShopSavvy.Sdk/)

#### Installation

```bash
dotnet add package ShopSavvy.Sdk
```

#### Quick Start

```csharp
using ShopSavvy;

// Create a new client
var client = new ShopSavvyClient("ss_live_your_api_key_here");

// Get product details
var product = await client.GetProductDetailsAsync("012345678901");
Console.WriteLine($"Product: {product.Data.Name}");

// Get current offers
var offers = await client.GetCurrentOffersAsync("012345678901");
foreach (var offer in offers.Data)
{
    Console.WriteLine($"{offer.Retailer}: ${offer.Price:F2}");
}

// Get price history
var history = await client.GetPriceHistoryAsync(
    "012345678901",
    new DateTime(2024, 1, 1),
    new DateTime(2024, 1, 31)
);
```

#### Dependency Injection

```csharp
// Program.cs or Startup.cs
services.AddShopSavvy(options =>
{
    options.ApiKey = Configuration["ShopSavvy:ApiKey"];
    options.BaseUrl = "https://api.shopsavvy.com/v1";
});

// In your controller
[ApiController]
public class ProductsController : ControllerBase
{
    private readonly IShopSavvyClient _client;

    public ProductsController(IShopSavvyClient client)
    {
        _client = client;
    }

    [HttpGet("{barcode}")]
    public async Task<IActionResult> GetProduct(string barcode)
    {
        var product = await _client.GetProductDetailsAsync(barcode);
        return Ok(product);
    }
}
```

#### Features

- Full async/await support
- Strong typing with C# models
- Dependency injection support
- ConfigureAwait(false) for library code
- Custom exception types
- Support for .NET 6+

### Rust SDK

Our official Rust SDK provides memory-safe, high-performance access to the ShopSavvy Data API with full type safety.

- [View on GitHub](https://github.com/shopsavvy/sdk-rust)
- [Crates.io](https://crates.io/crates/shopsavvy-sdk)

#### Installation

```toml
[dependencies]
shopsavvy-sdk = "1.0"
tokio = { version = "1.0", features = ["full"] }
```

#### Quick Start

```rust
use shopsavvy_sdk::{Client, Result};

#[tokio::main]
async fn main() -> Result<()> {
    // Create a new client
    let client = Client::new("ss_live_your_api_key_here")?;

    // Get product details
    let product = client.get_product_details("012345678901").await?;
    println!("Product: {}", product.data.name);

    // Get current offers
    let offers = client.get_current_offers("012345678901", None).await?;
    for offer in offers.data {
        println!("{}: ${:.2}", offer.retailer, offer.price);
    }

    // Get price history
    let history = client.get_price_history(
        "012345678901",
        "2024-01-01",
        "2024-01-31",
        None
    ).await?;

    Ok(())
}
```

#### Error Handling

```rust
use shopsavvy_sdk::{Client, Error};

match client.get_product_details("invalid-id").await {
    Ok(product) => println!("Found: {}", product.data.name),
    Err(Error::NotFound) => println!("Product not found"),
    Err(Error::RateLimit) => println!("Rate limit exceeded"),
    Err(Error::Authentication) => println!("Invalid API key"),
    Err(e) => println!("Other error: {}", e),
}
```

#### Features

- Memory safe with zero-cost abstractions
- Full async/await support with tokio
- Strongly typed with serde serialization
- Comprehensive error handling
- Built-in rate limiting
- Support for Rust 1.70+

### Swift SDK

Our official Swift SDK provides native iOS and macOS integration with modern Swift concurrency and SwiftUI support.

- [View on GitHub](https://github.com/shopsavvy/sdk-swift)

#### Installation

Swift Package Manager:

```swift
.package(url: "https://github.com/shopsavvy/sdk-swift.git", from: "1.3.0")
```

#### Quick Start

```swift
import ShopSavvy

// Create a new client
let client = ShopSavvyClient(apiKey: "ss_live_your_api_key_here")

// Get product details
do {
    let product = try await client.getProductDetails("012345678901")
    print("Product: \(product.data.name)")

    // Get current offers
    let offers = try await client.getCurrentOffers("012345678901")
    for offer in offers.data {
        print("\(offer.retailer): $\(offer.price, specifier: "%.2f")")
    }

    // Get price history
    let history = try await client.getPriceHistory(
        "012345678901",
        startDate: "2024-01-01",
        endDate: "2024-01-31"
    )

} catch {
    print("Error: \(error)")
}
```

#### SwiftUI Integration

```swift
struct ProductView: View {
    @State private var product: Product?
    @State private var offers: [Offer] = []

    let barcode: String
    let client = ShopSavvyClient(apiKey: "your_api_key")

    var body: some View {
        VStack {
            if let product = product {
                Text(product.name)
                    .font(.title)

                LazyVStack {
                    ForEach(offers, id: \.id) { offer in
                        HStack {
                            Text(offer.retailer)
                            Spacer()
                            Text("$\(offer.price, specifier: "%.2f")")
                        }
                    }
                }
            }
        }
        .task {
            await loadProduct()
        }
    }

    private func loadProduct() async {
        do {
            let productResponse = try await client.getProductDetails(barcode)
            let offersResponse = try await client.getCurrentOffers(barcode)

            await MainActor.run {
                self.product = productResponse.data
                self.offers = offersResponse.data
            }
        } catch {
            print("Error loading product: \(error)")
        }
    }
}
```

#### Features

- Modern Swift concurrency (async/await)
- SwiftUI and UIKit support
- Codable models for type safety
- iOS 15+ and macOS 12+ support
- Built-in error handling
- Network layer with URLSession

### Kotlin SDK

Our official Kotlin SDK provides native Android integration with coroutines support and modern Kotlin idioms.

- [View on GitHub](https://github.com/shopsavvy/sdk-kotlin)
- [Maven Central](https://central.sonatype.com/artifact/com.shopsavvy/shopsavvy-sdk-kotlin)

#### Installation

```kotlin
// build.gradle.kts
dependencies {
    implementation("com.shopsavvy:shopsavvy-sdk-kotlin:1.1.0")
}
```

#### Quick Start

```kotlin
import com.shopsavvy.sdk.*
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    // Create a new client
    val client = ShopSavvyClient("ss_live_your_api_key_here")

    try {
        // Get product details
        val product = client.getProductDetails("012345678901")
        println("Product: ${product.data.name}")

        // Get current offers
        val offers = client.getCurrentOffers("012345678901")
        offers.data.forEach { offer ->
            println("${offer.retailer}: $${offer.price}")
        }

        // Get price history
        val history = client.getPriceHistory(
            "012345678901",
            "2024-01-01",
            "2024-01-31"
        )

    } catch (e: Exception) {
        println("Error: ${e.message}")
    }
}
```

#### Android Integration

```kotlin
class ProductRepository(private val client: ShopSavvyClient) {

    suspend fun getProduct(barcode: String): Result<Product> =
        try {
            val response = client.getProductDetails(barcode)
            Result.success(response.data)
        } catch (e: Exception) {
            Result.failure(e)
        }
}

// In your ViewModel
class ProductViewModel(
    private val repository: ProductRepository
) : ViewModel() {

    private val _product = MutableLiveData<Product?>()
    val product: LiveData<Product?> = _product

    fun loadProduct(barcode: String) {
        viewModelScope.launch {
            repository.getProduct(barcode)
                .onSuccess { _product.value = it }
                .onFailure { /* handle error */ }
        }
    }
}
```

#### Features

- Full coroutines support
- Null safety with Kotlin types
- Android lifecycle awareness
- OkHttp-based HTTP client
- Serialization with kotlinx.serialization
- Support for Android API 21+

### SDK Comparison

Choose the right SDK for your technology stack. All SDKs provide the same comprehensive API coverage with language-specific optimizations.

| Feature | TypeScript/JavaScript | Python | Ruby |
|---------|----------------------|--------|------|
| Package Manager | npm, yarn, bun | pip | gem, bundler |
| Type Safety | Full TypeScript | Pydantic models | Runtime validation |
| Async Support | Native async/await | Sync + async variants | Sync only |
| Environment | Node.js, Browser | Python 3.8+ | Ruby 2.7+ |
| Error Handling | Comprehensive | Exception hierarchy | Custom error classes |
| Framework Integration | React, Next.js, Express | Django, FastAPI, Flask | Rails, Sinatra |
| Documentation | TSDoc + examples | Google-style + Sphinx | YARD + examples |

#### Quick Installation Comparison

| SDK | Install | Best For |
|-----|---------|----------|
| TypeScript/JavaScript | `npm install @shopsavvy/sdk` | Frontend apps, Node.js services, full-stack applications |
| Python | `pip install shopsavvy-sdk` | Data science, ML pipelines, Django/FastAPI apps |
| Ruby | `gem install shopsavvy-sdk` | Rails applications, Ruby scripts, background jobs |
| Go | `go get github.com/shopsavvy/sdk-go` | High-performance services, microservices |
| Java | `com.shopsavvy:shopsavvy-sdk:1.1.0` (Maven/Gradle) | Enterprise Java apps, Spring Boot |
| PHP | `composer require shopsavvy/shopsavvy-sdk-php` (after adding the GitHub repository, see PHP SDK) | Laravel, Symfony, PHP web apps |
| C# | `dotnet add package ShopSavvy.Sdk` | .NET applications, ASP.NET |
| Rust | `cargo add shopsavvy-sdk` | Systems programming, high-performance |
| Swift | SPM: `https://github.com/shopsavvy/sdk-swift.git` | iOS, macOS native apps |
| Kotlin | `com.shopsavvy:shopsavvy-sdk-kotlin:1.1.0` (Gradle) | Android apps, Kotlin services |

#### When to Use Each SDK

**Choose TypeScript/JavaScript if:**
- Building web applications or Node.js services
- Need browser compatibility
- Want the best type safety and IDE support
- Using modern JavaScript frameworks

**Choose Python if:**
- Building data analysis or ML applications
- Need both sync and async support
- Want comprehensive type validation
- Using Django, FastAPI, or Flask

**Choose Ruby if:**
- Building Rails applications
- Want idiomatic Ruby patterns
- Need excellent Rails integration
- Prefer Ruby's expressive syntax

---

## AI Integration

### Model Context Protocol Server

Connect AI assistants directly to ShopSavvy's product database. The [Model Context Protocol](https://modelcontextprotocol.io) (MCP) server lets Claude, ChatGPT, Cursor, VS Code, Codex, Gemini CLI and other MCP clients look up products, compare current prices across retailers, read price history and schedule monitoring in conversation, using the same data as the REST API.

- **Hosted endpoint:** `https://api.shopsavvy.com/mcp` (Streamable HTTP). Legacy HTTP+SSE clients use `https://api.shopsavvy.com/mcp/sse`.
- **No key needed to start.** Anonymous use is rate-limited per IP address. Send your Data API key as a Bearer token for higher limits and the account tools (scheduling, usage).
- **Open source:** the stdio package `@shopsavvy/mcp-server` and its source are [on GitHub](https://github.com/shopsavvy/shopsavvy-mcp-server) under the MIT license.

Next: [connect your client](#claude-desktop-setup), see the [15 tools](#available-ai-tools), or try the [example prompts](#usage-examples). Setup guides for each client are on [shopsavvy.com/agents](https://shopsavvy.com/agents#install).

### Claude Desktop Setup

#### 1. Connect by URL

Claude Code, Cursor, VS Code, Codex, Gemini CLI, claude.ai and ChatGPT connect to the hosted server directly. The key is optional (anonymous use is rate-limited per IP); send it for your plan's limits:

```bash
claude mcp add --transport http shopsavvy https://api.shopsavvy.com/mcp \
  --header "Authorization: Bearer ss_live_your_key_here"
```

Per-client setup: https://shopsavvy.com/agents#install

#### 2. Or run it locally

For clients that can only launch local (stdio) servers, such as Claude Desktop's config file:

```json
{
  "mcpServers": {
    "shopsavvy": {
      "command": "npx",
      "args": ["-y", "@shopsavvy/mcp-server"],
      "env": {
        "SHOPSAVVY_API_KEY": "ss_live_your_key_here"
      }
    }
  }
}
```

#### 3. Get Your API Key

- [Subscribe to a Plan](https://shopsavvy.com/data#pricing)
- [Create API Key](https://shopsavvy.com/data/dashboard)

### Available AI Tools

The server exposes 15 tools. Your assistant picks them from your request; you don't call them by name.

| Tool | What it does | Key needed |
|------|--------------|------------|
| `product_lookup` | One product's record (title, brand, model, MPN, barcode, ASIN, ShopSavvy ID) from a barcode, ASIN, URL, model number or name | No |
| `product_lookup_batch` | The same for a comma-separated list of identifiers | No |
| `product_search` | Keyword search over the catalog, best match first, paginated | No |
| `product_offers` | Current prices for one product at every retailer, lowest first, with availability, condition, seller and when each was last checked | No |
| `product_offers_retailer` | Current prices for one product at one retailer domain (e.g. `bestbuy.com`) | No |
| `product_price_history` | Recorded prices between two dates (`start`/`end`), grouped by retailer | No |
| `product_schedule` | Schedule hourly, daily or weekly price re-checks for products | Yes |
| `product_unschedule` | Stop scheduled re-checks | Yes |
| `scheduled_products_list` | List the products scheduled on your account | Yes |
| `api_usage` | This month's credits used and remaining | Yes, for credit figures |
| `content_best_picks` | ShopSavvy's published "best of" buying guides for a category | No |
| `content_tldr_review` | A product's TLDR review: pros, cons, bottom line and score | No |
| `content_qa_answers` | Published answers to common questions about a product | No |
| `content_buying_guide` | When-to-buy guides: the months and sales events when prices usually drop | No |
| `universal_search` | Ranked products and matching guides for broad "what should I buy" queries | No |

Without a key the server allows 10 tool calls a minute and 100 an hour per IP address. With a Data API key the limit rises to 100 tool calls a minute with no hourly cap, and tool calls use your plan's credits.

### Usage Examples

**Product Research:**
- "Look up the product with barcode 012345678901"
- "Find product information for ASIN B08N5WRWNW"
- "Get details for this Amazon URL: https://amazon.com/dp/B08N5WRWNW"

**Price Comparison:**
- "Show me current prices for ASIN B08N5WRWNW from all retailers"
- "Get Amazon prices for product 012345678901"
- "Compare Best Buy and Target prices for this product"

**Price History:**
- "Get price history for B08N5WRWNW from January 1-31, 2024"
- "Show me price trends for the last 3 months"
- "What were Amazon's prices for this product in December?"

**Price Monitoring:**
- "Schedule daily price monitoring for these products"
- "Set up hourly monitoring for ASIN B08N5WRWNW"
- "Show me all my scheduled products"

### Advanced Features

- **Open Source** - MIT licensed and available on GitHub for customization and contributions.
- **Easy Integration** - Works with Claude Desktop, Cursor, and any MCP-compatible AI assistant.
- **Batch Operations** - Look up multiple products, compare prices across retailers, and manage large product catalogs efficiently.
- **Usage Tracking** - Built-in usage analytics help you monitor API consumption and optimize your credit usage.

**Credit Usage:** The MCP server uses the same credit system as the REST API. Each AI tool interaction consumes credits based on the data requested.

---

## Products API

### Retrieving Product Details

**Cost:** 1 credit per product found. Identifiers that match nothing cost nothing.

You can retrieve product details by using the `GET /products?ids={identifiers}` endpoint.

The `identifiers` parameter can be a comma-separated list of **one** or **more** identifiers. You can mix and match any combination of different identifiers, like `GET /products?ids=B07G14HTBZ,611247369449,3ONn300xybP3y66ibqc1`.

An identifier can be any of the following:

- UPC
- EAN
- ISBN
- GTIN
- Amazon ASIN
- Model Number
- Product Name
- URL at any Retailer
- ShopSavvy Product ID

#### Examples

**Example with barcodes:**

```bash
curl -X GET "https://api.shopsavvy.com/v1/products?ids=611247373064,611247369449" \
  -H "Authorization: Bearer ss_live_your_api_key_here"
```

**Example with product name:**

```bash
curl -X GET "https://api.shopsavvy.com/v1/products?ids=iPhone%2015%20Pro" \
  -H "Authorization: Bearer ss_live_your_api_key_here"
```

**Note:** When using a product name, the API uses full-text search to find the best matching product based on relevance and offer availability.

#### How Identifiers Are Matched

Each identifier is tried against these fields, in order, and the first field that matches wins:

1. **Barcode** (UPC / EAN / ISBN / GTIN). A full-length barcode (UPC-A, EAN-13, ISBN-13, GTIN-14) with a valid check digit is looked up **only** as a barcode (and a ShopSavvy Product ID). It is never re-interpreted as a model number, so a UPC can't come back as an unrelated product whose model number happens to be the same digits.
2. **ShopSavvy Product ID**
3. **Model number**, then **MPN** (skipped for inputs that look like product names, i.e. contain spaces)
4. **Amazon ASIN**
5. **Product URL** at any retailer (tracking parameters such as `utm_*` are stripped before matching)
6. **Product name** (full-text search, a best guess)

Some identifiers are shared by more than one product in the catalog, such as a barcode a manufacturer reused or a model number used across several listings. When that happens the API returns the product with the most evidence behind it (the most verified offers on file, then the most watched), and the result is the same every time you ask.

Every product in a response carries a `match` object that tells you which identifier produced it and how:

```json
"match": { "identifier": "611247373064", "by": "barcode", "candidates": 1 }
```

| Field | Description |
|-------|-------------|
| `identifier` | The identifier exactly as you sent it. Use this to line results up with your request, because identifiers that match nothing are left out of `data`. |
| `by` | Which field matched: `barcode`, `shopsavvy_id`, `asin`, `url`, `model`, `mpn`, or `name`. Everything except `name` is an exact match. Treat `name` as low confidence. |
| `candidates` | How many products matched on that field. More than `1` means the identifier is shared and the best-evidence product was chosen. Always `1` for `name`. |

#### Response Format

The response will be a JSON object with success status, data array, and metadata including credits used.

Products will each have the following fields. (Note: not all fields are available on all products).

| Field | Description |
|-------|-------------|
| `title` | The name of the product. |
| `title_short` | A shorter, human-friendly version of the title (when available). |
| `slug` | URL-friendly slug for the product. |
| `category` | A comma separated list of categories for the product. |
| `brand` | The brand of the product. |
| `color` | The color of the product. |
| `model` | The model of the product. |
| `shopsavvy` | The ShopSavvy Product ID of the product. This can optionally be used alongside any other identifier when retrieving products, offers, etc. |
| `barcode` | The barcode of the product. Will always be a number. |
| `amazon` | The Amazon ASIN of the product. |
| `mpn` | The manufacturer's part number of the product. |
| `images` | An array of image URLs pointing to images of the product. |
| `identifiers` | All known identifiers for the product (barcode, amazon, walmart, bestbuy, newegg, etc.). |
| `description` | Product description text (single best available description). |
| `categories` | Array of category path strings. |
| `attributes` | Product specifications as a flat object (e.g., `{"Color": "Black", "Weight": "250g"}`). |
| `rating` | Aggregated customer rating with `value` (out of 5) and `count` (total reviews). |
| `score` | Expert quality scores on a **0-1 scale**: `overall`, `customer`, `professional`, plus an `aspects` object of per-aspect scores keyed by free-form aspect names drawn from the product's professional reviews (e.g. `value`, `features`, `reliability`, `quality` — the set varies per product). Only populated fields are included. Multiply by 10 or 100 if you want to display a /10 or /100 score. |
| `keywords` | Array of relevant search keywords for the product. |
| `match` | How your identifier matched this product: `identifier`, `by`, and `candidates` (see [How Identifiers Are Matched](#how-identifiers-are-matched)). Present on every endpoint that takes identifiers. |

All response `meta` objects now include a `request_id` field — a unique identifier for every API request. Include this in any support inquiries.

**Error Responses** include both a human-readable `error` string and a structured `error_detail` object with `code`, `message`, `action` (what to do), and `docs_url` (link to relevant documentation).

#### Example Response

```json
{
  "success": true,
  "data": [
    {
      "title": "Keurig K-Mini Single Serve Coffee Maker, Black",
      "category": "Grocery & Gourmet Food > Beverages > Coffee, Tea & Cocoa > Coffee > Single-Serve Capsules & Pods",
      "brand": "Keurig",
      "color": "Black",
      "model": "K-MINI",
      "shopsavvy": "products/3ONn300xybP3y66ibqc1",
      "barcode": 611247373064,
      "amazon": "B07G14HTBZ",
      "mpn": "5000200237",
      "images": [
        "https://images-na.ssl-images-amazon.com/images/I/31jy5fSzyRL.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/411uxu%2Bg17L.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/41jEx1YoTQL.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/41CanelWIlL.jpg"
      ]
    },
    {
      "title": "Keurig K-Elite Single Serve K-Cup Pod Maker with Strength and Temperature Control, Iced Coffee Capability, 12oz Brew Size, Brushed Silver",
      "category": "Home & Kitchen > Kitchen & Dining > Coffee, Tea & Espresso > Coffee Makers > Single-Serve Brewers",
      "brand": "Keurig",
      "color": "Silver",
      "model": "K-Elite",
      "shopsavvy": "products/DrKWneG0MpFlZpwZXNYa",
      "barcode": 611247369449,
      "amazon": "B0788F3R8X",
      "mpn": "5000197492",
      "images": [
        "https://images-na.ssl-images-amazon.com/images/I/411fEW99TlL.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/51bdqFw6lNL.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/51-NbDX9S7L.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/412o2pQ-swL.jpg"
      ]
    }
  ],
  "meta": {
    "credits_used": 2,
    "credits_remaining": 998,
    "rate_limit_remaining": 58
  }
}
```

### Retrieving Product Details in CSV Format

**Cost:** 1 credit per product found.

By default all responses are in JSON format, but you can also retrieve products in CSV format by adding `?format=csv` to the request:

```
GET /products?ids=611247373064,611247369449&format=csv
```

When you do this, the response will be formatted as a CSV file, with columns for each of the different fields, and each product on its own row:

```csv
shopsavvy,barcode,amazon,title,category,brand,color,mpn,model,image
3ONn300xybP3y66ibqc1,611247373064,B07G14HTBZ,"Keurig K-Mini Single Serve Coffee Maker, Black","Grocery & Gourmet Food > Beverages > Coffee, Tea & Cocoa > Coffee > Single-Serve Capsules & Pods",Keurig,Black,5000200237,K-MINI,https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/31jy5fSzyRL.jpg
DrKWneG0MpFlZpwZXNYa,611247369449,B0788F3R8X,"Keurig K-Elite Single Serve K-Cup Pod Maker with with Strength and Temperature Control, Iced Coffee Capability, 12oz Brew Size, Brushed Silver","Home & Kitchen > Kitchen & Dining > Coffee, Tea & Espresso > Coffee Makers > Single-Serve Brewers",Keurig,Silver,5000197492,K-Elite,https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/411fEW99TlL.jpg
```

### Searching Products by Keyword

**Cost:** 1 credit per product returned.

You can search for products by keyword using the `GET /products/search?q={query}` endpoint.

This endpoint uses PostgreSQL full-text search to find products matching your search query. Results are ranked by a composite score that combines:

- **Text Relevance (70%)**: How well the product title, brand, and model match your search query
- **Offer Count (25%)**: Products with more current offers are ranked higher (indicates active products)
- **Recency (5%)**: Recently updated products are slightly preferred

#### Query Parameters

| Parameter | Required | Description |
|-----------|----------|-------------|
| `q` | Yes | Search query or keyword (e.g., "iphone 15 pro", "samsung tv", "nike shoes") |
| `limit` | No | Maximum number of results to return (default: 20, max: 100) |
| `offset` | No | Offset for pagination (default: 0) |

#### Example Request

```bash
curl -X GET "https://api.shopsavvy.com/v1/products/search?q=iphone%2015%20pro&limit=10" \
  -H "Authorization: Bearer ss_live_your_api_key_here"
```

#### Example Response

```json
{
  "success": true,
  "data": [
    {
      "title": "Apple iPhone 15 Pro Max 256GB - Natural Titanium",
      "category": "Cell Phones & Accessories > Cell Phones > Smartphones",
      "brand": "Apple",
      "color": "Natural Titanium",
      "model": "iPhone 15 Pro Max",
      "shopsavvy": "products/abc123xyz",
      "barcode": 195949038674,
      "amazon": "B0CHX3TZ7R",
      "mpn": "MU773LL/A",
      "images": [
        "https://images-na.ssl-images-amazon.com/images/I/41BvSLn90ML.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/51ckLKbsOsL.jpg"
      ]
    },
    {
      "title": "Apple iPhone 15 Pro 128GB - Blue Titanium",
      "category": "Cell Phones & Accessories > Cell Phones > Smartphones",
      "brand": "Apple",
      "color": "Blue Titanium",
      "model": "iPhone 15 Pro",
      "shopsavvy": "products/def456uvw",
      "barcode": 195949037894,
      "amazon": "B0CHX1W1XY",
      "mpn": "MTUX3LL/A",
      "images": [
        "https://images-na.ssl-images-amazon.com/images/I/41m9Pq3ScgL.jpg"
      ]
    }
  ],
  "pagination": {
    "total": 47,
    "limit": 10,
    "offset": 0,
    "returned": 2
  },
  "meta": {
    "credits_used": 2,
    "credits_remaining": 998,
    "rate_limit_remaining": 58
  }
}
```

#### Use Cases

- **Autocomplete / Search Suggestions**: Use with a low limit (e.g., 5-10) to show real-time search results as users type
- **Category Browsing**: Search for broad categories like "gaming laptops" or "bluetooth speakers"
- **Product Discovery**: Find products when you don't have a specific identifier like a barcode or ASIN
- **Fuzzy Matching**: The full-text search handles typos and variations in product names

**Note:** Once you have a product from search results, you can use its `shopsavvy` ID, `barcode`, or `amazon` ASIN with the other endpoints like `GET /products/offers` to retrieve pricing data.

---

## Batch API

### Batch Product Lookup

Look up multiple products at once. For small batches (up to 20 identifiers), results are returned immediately. For larger batches (21-100), processing happens asynchronously — you receive a batch ID and poll for results.

**Endpoint:** `POST /v1/products/batch`

**Credit Cost:** Same as individual lookups (1 credit per product found, + 3 per product that has offers if including offers, + 1 per product that has a review if including reviews)

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `identifiers` | string[] | Yes | Array of product identifiers (1-100). Supports barcodes, ASINs, URLs, model numbers. |
| `include` | string[] | No | Additional data to fetch: `"offers"` and/or `"reviews"` |

**Example Request (Synchronous, <=20 identifiers):**

```bash
curl -X POST 'https://api.shopsavvy.com/v1/products/batch' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{
    "identifiers": ["B09XS7JWHH", "B0CHX3TW6K", "027242923782"],
    "include": ["offers"]
  }'
```

**Synchronous Response (<=20 identifiers):**

```json
{
  "success": true,
  "results": [
    { "identifier": "B09XS7JWHH", "status": "found", "product": { "title": "Sony WH-1000XM5", ... }, "offers": [...] },
    { "identifier": "B0CHX3TW6K", "status": "found", "product": { "title": "iPhone 15 Pro", ... }, "offers": [...] },
    { "identifier": "INVALID123", "status": "not_found", "product": null }
  ],
  "summary": { "total": 3, "found": 2, "not_found": 1 },
  "meta": { "request_id": "abc-123", "credits_used": 8, "credits_remaining": 992 }
}
```

**Async Response (>20 identifiers):**

When submitting more than 20 identifiers, you receive a batch ID immediately:

```json
{
  "success": true,
  "batch": {
    "id": "batch_abc123def456",
    "status": "processing",
    "total": 50,
    "processed": 0,
    "poll_url": "/v1/batch/batch_abc123def456",
    "estimated_seconds": 75
  }
}
```

Poll `GET /v1/batch/{batch_id}` until `status` is `"completed"`, then the response includes the full `results` array.

---

## Pricing API

### Retrieving Offers for Products at All Retailers

**Cost:** 3 credits per product that has offers or in-store prices. Products with neither, and identifiers that match nothing, cost nothing.

An **offer** represents a **product** being sold by a specific **retailer** or **seller** for a specific price, condition, etc.

**Currency:** the offer endpoints currently return **USD-denominated offers only**, and there is no parameter to request other currencies. ShopSavvy does mine offers in other currencies, so for a product whose only offers are non-USD (a UK-only retailer, for example) these endpoints return an empty `offers` array rather than an error — an empty array means "no USD offers on file", which is not the same as "no offers exist". If you need non-USD coverage, contact us at hello@greatwork.company.

You can retrieve offers for products by using the `GET /products/offers` endpoint. The `ids` parameter supports all identifier types including barcodes, ASINs, model numbers, URLs, and **product names**.

**Example with barcodes:**

```
GET /products/offers?ids=611247373064,611247369449
```

**Example with product name:**

```
GET /products/offers?ids=iPhone%2015%20Pro
```

**Note:** When using a product name, the API uses full-text search to find the best matching product based on relevance and offer availability, then returns offers for that product.

#### Offer Fields

This will return an array of products, each containing a new `offers` property, which will be an array of offer objects, each containing the following properties:

| Field | Description |
|-------|-------------|
| `id` | A unique identifier for this offer. |
| `availability` | The availability of the product in the offer. This will only be present if the value is confirmed and known. It will be missing if availability is unknown. Will be either `"in"` or `"out"`. |
| `condition` | The condition of the product in the offer. Will be `"new"`, `"used"`, or `"refurbished"`. |
| `condition_grade` | A finer grade alongside `condition` when the retailer states one, such as `"open-box"`, `"refurbished-excellent"`, or `"used-like-new"`. `null` when the retailer did not grade it. |
| `retailer` | The name of the retailer or marketplace the offer is for. |
| `price` | The price of the product in the offer. Will always be a number. |
| `seller` | The name of the marketplace seller selling this product. If missing, then the offer is from a first-party retailer and there is no marketplace seller. |
| `is_marketplace` | `true` when the offer is sold by a third-party marketplace seller (named in `seller`), `false` when it is sold by the retailer itself, `null` when the source did not say. Use it to build "sold by the retailer only" views. |
| `URL` | The URL for the offer. |
| `timestamp` | An [ISO 8601](https://www.w3.org/TR/NOTE-datetime) formatted date and time representing when the offer was last seen by ShopSavvy. |

#### In-Store Prices

Each product also has an `in_store_prices` array: shelf prices that physical stores charged, read from receipts ShopSavvy app users scanned ("Kroger on Vine St sold this for $3.49 on 2026-11-07"). They are labeled `source: "user-collected"` and included on every plan. A receipt shows what the store charged that day, not whether it is in stock now, so there is no `availability`. Nothing about the shopper is included. The array is empty when no in-store prices are on file; with `retailer`, it lists only that retailer's stores. At most 25 per product, newest first. In-store prices from member warehouse clubs and stores that publish few or no online prices (Costco, Sam's Club, BJ's, Aldi, Trader Joe's, WinCo and Restaurant Depot) are included on Professional, Scale and Enterprise plans and are an add-on on Starter (email api@shopsavvy.com to add it). Without it, those stores' entries are left out of the array; every other retailer's in-store prices are on every plan.

| Field | Description |
|-------|-------------|
| `source` | Always `"user-collected"`. |
| `retailer` | The store's retailer name, such as `"Kroger"`. |
| `store.address` | The store's street address. |
| `store.latitude`, `store.longitude` | The store's coordinates. |
| `price` | The unit shelf price paid. When several receipts from the same store agree, their median. |
| `currency` | ISO currency code of `price`. |
| `observed_on` | `YYYY-MM-DD` date of the most recent receipt behind the price. |
| `timestamp` | ISO 8601 time ShopSavvy last updated this price. |

```json
"in_store_prices": [
  {
    "source": "user-collected",
    "retailer": "Kroger",
    "store": { "address": "1014 Vine St, Cincinnati, OH 45202, USA", "latitude": 39.1086, "longitude": -84.5154 },
    "price": 3.49,
    "currency": "USD",
    "observed_on": "2026-11-07",
    "timestamp": "2026-11-08T14:02:11.000Z"
  }
]
```

In CSV, each store adds `in_store_price-`, `in_store_currency-`, `in_store_observed_on-`, `in_store_latitude-`, `in_store_longitude-` and `in_store_source-` columns named `<retailer> (<address>)`. The MCP `product_offers` tools list them under "In-store prices (user-collected from shopper receipts)".

#### Example Response

```json
[
    {
      "title": "Keurig K-Mini Single Serve Coffee Maker, Black",
      "category": "Grocery & Gourmet Food > Beverages > Coffee, Tea & Cocoa > Coffee > Single-Serve Capsules & Pods",
      "brand": "Keurig",
      "color": "Black",
      "model": "K-MINI",
      "shopsavvy": "3ONn300xybP3y66ibqc1",
      "barcode": 611247373064,
      "amazon": "B07G14HTBZ",
      "mpn": "5000200237",
      "images": [
        "https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/31jy5fSzyRL.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/411uxu%2Bg17L.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/41jEx1YoTQL.jpg",
        "https://images-na.ssl-images-amazon.com/images/I/41CanelWIlL.jpg"
      ],
      "offers": [
        {
          "id": "0IUouCFtZEhxeOablTPl",
          "availability": "in",
          "condition": "new",
          "retailer": "Amazon",
          "price": 74.96,
          "seller": "Palm Tree Deals",
          "URL": "https://www.amazon.com/dp/B07GV2S1GS?m=A1GKQADQC2VI6E",
          "timestamp": "2022-05-01T22:36:33.236Z"
        },
        {
          "id": "0RmL0ZMUesP2PmSlP97G",
          "availability": "in",
          "condition": "new",
          "retailer": "Amazon",
          "price": 58.86,
          "URL": "https://www.amazon.com/dp/B07GV2S1GS",
          "timestamp": "2022-05-03T22:52:06.802Z"
        },
        {
          "id": "0qp0KKdFnwIi3c09kGyT",
          "availability": "in",
          "condition": "new",
          "retailer": "Walmart",
          "price": 60.34,
          "URL": "https://www.walmart.com/ip/Keurig-K-Mini-Single-Serve-Coffee-Maker-Black/389238886?selectedSellerId=FBB34940E137490C8ABD825B48534874",
          "timestamp": "2022-05-01T20:38:25.218Z"
        },
        {
          "id": "2EHAxfhrvF6hEFs8IarY",
          "availability": "in",
          "condition": "new",
          "retailer": "Walmart",
          "price": 81.5,
          "seller": "Focus Camera",
          "URL": "https://www.walmart.com/ip/Keurig-K-Mini-Single-Serve-K-Cup-Pod-Coffee-Maker-6-to-12-oz-Brew-Sizes-Black/389238886?selectedSellerId=888853D0A1394FA4BB92C88C4FD20210",
          "timestamp": "2022-05-02T20:26:42.657Z"
        },
        {
          "id": "1upFPYp9qj74v8S0E7qp",
          "availability": "in",
          "condition": "refurbished",
          "retailer": "shopcheap.club",
          "price": 59.99,
          "seller": null,
          "URL": "https://shopcheap.club/kitchen-tabletop/keurig-k-mini-coffee-maker-single-serve-k-cup-pod-coffee-brewer-6-to-12-oz-brew-sizes-black/",
          "timestamp": "2022-05-03T13:49:10.053Z"
        }
      ]
    }
]
```

### Retrieving Offers for a Single Retailer

**Cost:** 2 credits per product that has offers at that retailer. Products with no offers cost nothing.

You can retrieve offers for products at a single retailer by specifying a value for the `retailer` parameter. The value should be the domain of the retailer you want to retrieve offers for, like `amazon.com` or `bestbuy.com`.

```
GET /products/offers?ids=611247373064,611247369449&retailer=amazon.com
```

The response will be in the same format and schema, but it will only contain offers from your specified retailer.

#### Example Response

```json
[
    {
      "title": "Keurig K-Mini Single Serve Coffee Maker, Black",
      "category": "Grocery & Gourmet Food > Beverages > Coffee, Tea & Cocoa > Coffee > Single-Serve Capsules & Pods",
      "brand": "Keurig",
      "color": "Black",
      "model": "K-MINI",
      "shopsavvy": "3ONn300xybP3y66ibqc1",
      "barcode": 611247373064,
      "amazon": "B07G14HTBZ",
      "mpn": "5000200237",
      "images": [
        "https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/31jy5fSzyRL.jpg"
      ],
      "offers": [
        {
          "id": "0IUouCFtZEhxeOablTPl",
          "availability": "in",
          "condition": "new",
          "retailer": "Amazon",
          "price": 74.96,
          "seller": "ACME Deals",
          "URL": "https://www.amazon.com/dp/B07G14HTBZ?m=A1GKQADQC2VI6E",
          "timestamp": "2022-05-01T22:36:33.236Z"
        },
        {
          "id": "0RmL0ZMUesP2PmSlP97G",
          "availability": "in",
          "condition": "new",
          "retailer": "Amazon",
          "price": 58.86,
          "URL": "https://www.amazon.com/dp/B07G14HTBZ",
          "timestamp": "2022-05-03T22:52:06.802Z"
        }
      ]
    }
]
```

### Retrieving Offers in CSV Format

**Cost:** 3 credits per product that has offers when requesting all retailers, 2 when requesting a single retailer.

By default all responses are in JSON format, but you can also retrieve data in CSV format by adding `?format=csv` to the request:

```
GET /products/offers?ids=611247373064,611247369449&retailer=bestbuy.com&format=csv
```

When you do this, the response will be formatted as a CSV file, with columns for each of the different fields, and each product on its own row. Each offer field will be a separate column, allowing for easy integration into spreadsheets and other tools or workflows.

#### Example Response

```csv
shopsavvy,barcode,amazon,title,category,brand,color,mpn,model,image,currency-Best Buy,price-Best Buy,availability-Best Buy,condition-Best Buy,condition_grade-Best Buy,is_marketplace-Best Buy,URL-Best Buy,timestamp-Best Buy
3ONn300xybP3y66ibqc1,611247373064,B07G14HTBZ,"Keurig K-Mini Single Serve Coffee Maker, Black","Grocery & Gourmet Food > Beverages > Coffee, Tea & Cocoa > Coffee > Single-Serve Capsules & Pods",Keurig,Matte Black,5000200237,K-MINI,https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/31jy5fSzyRL.jpg,USD,59.99,in,new,,false,https://www.bestbuy.com/site/keurig-k-mini-single-serve-k-cup-pod-coffee-maker-matte-black/6358476.p?skuId=6358476&ref=NS&loc=101,2022-11-05T11:47:00.226Z
DrKWneG0MpFlZpwZXNYa,611247369449,B0788F3R8X,"Keurig K-Elite Single Serve K-Cup Pod Maker with with Strength and Temperature Control, Iced Coffee Capability, 12oz Brew Size, Brushed Silver","Home & Kitchen > Kitchen & Dining > Coffee, Tea & Espresso > Coffee Makers > Single-Serve Brewers",Keurig,Brushed Silver,5000197492,K-Elite,https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/411fEW99TlL.jpg,USD,129.99,,new,,false,https://www.bestbuy.com/site/keurig-k-elite-single-serve-k-cup-pod-coffee-maker-brushed-silver/6203569.p?skuId=6203569,2022-11-05T11:33:16.004Z
```

### Retrieving Offers With Historical Offer Data

**Cost:** 3 credits per product that has offers when requesting all retailers, 2 when requesting a single retailer. Additionally, there is a cost of 1 credit per day of historical data requested.

**The per-day component is charged once for the whole request, not once per product.** A request for 1 product over a 90-day window costs `1 × 3 + 90 = 93` credits; the same window for 10 products costs `10 × 3 + 90 = 120` credits, not `10 × 93`. Every other row in the cost table above scales per product, so this one is called out explicitly.

Both components are only charged when we actually find offers for the request. If a request returns no offers at all, it costs 0 credits — including the per-day component.

Historical data can be requested by adding `start` and `end` parameters to the request. These should be formatted as `YYYY-MM-DD`. The window may span at most **366 days**; request longer histories in successive calls.

```
GET /products/offers/history?ids=611247373064&start=2022-11-20&end=2022-11-27
```

Please note you'll be charged **1 credit** for each day of historical data you request, on requests that return offers — once per request, however many `ids` it carries.

**eBay listings do not carry history.** A fresh eBay listing can still appear in the `offers` array, but its `history` array is always empty. eBay is a used/marketplace/reseller channel whose price series is not comparable to first-party retail, and ShopSavvy's own price chart has always excluded it for the same reason.

**History points are quality-filtered.** You receive the same series ShopSavvy's own price chart renders, not raw archived rows. A point is returned only if it came from a verified retailer or from a listing our product-match validation confirmed is this exact product, only if it carries a real price in that listing's own currency, and only if it survives the same per-retailer outlier band the chart applies. This exists because scraped-feed noise is real: on a $200-260 product we have measured archived points as low as $1.49 and as high as $548, all of which would wreck a naive "lowest price ever" or trend calculation. Well-covered products are unaffected; products with noisy long-tail sources return fewer, cleaner points.

The response uses the same envelope as the offers endpoint: `data` is an array with **one entry per product** you requested (products that could not be found are omitted). Each entry carries the same product fields as `GET /products`, plus an `offers` array with the same offer fields as `GET /products/offers`. Each offer additionally includes a `history` field: an array of historical price points for that specific offer, **newest first**. An offer with no qualifying points (for example any eBay listing) has an empty `history` array. Each point will include these fields:

| Field | Description |
|-------|-------------|
| `timestamp` | An [ISO 8601](https://www.w3.org/TR/NOTE-datetime) formatted date and time representing when the change was seen by ShopSavvy. |
| `price` | The price of the offer at the time of the change. This will always be a number. |
| `currency` | The [ISO 4217](https://en.wikipedia.org/wiki/ISO_4217) currency code the `price` is denominated in (e.g. `"USD"`). `null` on the rare archived point that carries no recorded currency — never assume a missing value means US dollars. |
| `availability` | The availability of the offer at the time of the change. This will only be present if the value is confirmed and known. It will be missing if availability is unknown. Will be either `"in"` or `"out"`. |

As with the other offer endpoints, an offer's own `availability` is omitted when unknown and `seller` is `null` when the listing is not a marketplace listing.

#### Example Response

```json
{
  "success": true,
  "data": [
    {
      "title": "Keurig K-Mini Single Serve Coffee Maker, Black",
      "category": "Grocery & Gourmet Food > Beverages > Coffee, Tea & Cocoa > Coffee > Single-Serve Capsules & Pods",
      "brand": "Keurig",
      "color": "Black",
      "shopsavvy": "products/3ONn300xybP3y66ibqc1",
      "barcode": "611247373064",
      "amazon": "B07G14HTBZ",
      "model": "K-MINI",
      "mpn": "5000200237",
      "images": [
        "https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/31jy5fSzyRL.jpg"
      ],
      "offers": [
        {
          "id": "0IUouCFtZEhxeOablTPl",
          "availability": "in",
          "condition": "new",
          "retailer": "Amazon",
          "currency": "USD",
          "price": 74.96,
          "seller": "ACME Deals",
          "URL": "https://www.amazon.com/dp/B07G14HTBZ?m=A1GKQADQC2VI6E",
          "timestamp": "2022-11-27T22:36:33.236Z",
          "history": [
            {
              "availability": "in",
              "price": 74.96,
              "currency": "USD",
              "timestamp": "2022-11-27T22:36:33.236Z"
            },
            {
              "availability": "out",
              "price": 70.99,
              "currency": "USD",
              "timestamp": "2022-11-24T10:00:00.000Z"
            },
            {
              "price": 79.99,
              "currency": "USD",
              "timestamp": "2022-11-21T08:15:00.000Z"
            }
          ]
        },
        {
          "id": "Z9kQ2mBestBuyOffer01",
          "condition": "new",
          "retailer": "Best Buy",
          "currency": "USD",
          "price": 59.99,
          "seller": null,
          "URL": "https://www.bestbuy.com/site/keurig-k-mini-single-serve-k-cup-pod-coffee-maker-matte-black/6358476.p?skuId=6358476",
          "timestamp": "2022-11-26T11:47:00.226Z",
          "history": [
            {
              "availability": "in",
              "price": 59.99,
              "currency": "USD",
              "timestamp": "2022-11-26T11:47:00.226Z"
            }
          ]
        }
      ]
    }
  ],
  "meta": {
    "request_id": "abc-123",
    "credits_used": 11,
    "credits_remaining": 989,
    "rate_limit_remaining": 999
  }
}
```

---

## Scheduling API

### Enabling Scheduled Refreshes for Products

**Cost:** 1 credit per product scheduled. Refreshes themselves are not charged; you pay the normal offers cost only when you read the results with `GET /products/offers`.

Enabling scheduled refreshes for products will cause ShopSavvy to refresh the pricing and availability data for the specified products on an interval you specify.

**What gets refreshed on your cadence:** offers at retailers we can re-check through an official retailer API, which today means **Amazon** (for products with an ASIN) and **Best Buy** (for products with a Best Buy SKU). The `identifiers` object on a product tells you which of these it has. Offers at other retailers keep updating as ShopSavvy sees them through shopper activity and our regular catalog crawls, but not on a guaranteed schedule. Each offer's `timestamp` tells you when it was last seen, so you can always check how fresh it is. If you pass `retailer=`, only that retailer is refreshed.

You can schedule one or more products using the same `ids` parameter as the `GET /products` and `GET /products/offers` endpoints.

Use the `schedule` parameter to specify how frequently you like the product(s) refreshed. This can be a string with a value of `"hourly"`, `"daily"`, or `"weekly"`.

```
PUT /products/scheduled?ids=611247373064,611247369449&schedule=daily
```

This will begin refreshing the pricing and availability for the product(s), and return products that were just scheduled. Note: You will need to call the `GET /products/offers` endpoint whenever you want to retrieve the latest data.

### Changing Refresh Schedule for Products

**Cost:** 1 credit per product scheduled. Refreshes themselves are not charged.

You can change how frequently previously scheduled product(s) are refreshed by calling the same `PUT` endpoint again with the new `schedule` (and optional `retailer`) — it updates the existing schedule in place rather than creating a duplicate. Everything else works the same as enabling scheduled refreshes for new products. Pass parameters as **query parameters**. The JSON body that older SDK versions send (`{ "identifiers": [...], "frequency": "daily", "retailer": "..." }`) is also accepted; when both are present, query parameters win.

Use the `schedule` parameter to specify how frequently you like the product(s) refreshed. This can be a string with a value of `"hourly"`, `"daily"`, or `"weekly"`.

```
PUT /products/scheduled?ids=611247373064&schedule=hourly&retailer=bestbuy.com
```

This will begin refreshing the pricing and availability for the product(s), and return products that had their refresh schedule changed. Note: You will need to call the `GET /products/offers` endpoint whenever you want to retrieve the latest data.

### Disabling Scheduled Refreshes for Products

**Cost:** 0 credits per product scheduled.

Disabling scheduled refreshes for products will cause ShopSavvy to stop refreshing the pricing and availability data for the specified products.

```
DELETE /products/scheduled?ids=611247369449
```

### Retrieve Products Currently Enabled for Scheduled Refreshes

**Cost:** 0 credits.

```
GET /products/scheduled
```

This returns all the products you currently have enabled for scheduled refreshes, along with each of their configuration and refresh interval.

#### Example Response

```json
[
  {
    "schedule": "hourly",
    "title": "Keurig K-Mini Single Serve Coffee Maker, Black",
    "category": "Grocery & Gourmet Food > Beverages > Coffee, Tea & Cocoa > Coffee > Single-Serve Capsules & Pods",
    "brand": "Keurig",
    "color": "Black",
    "model": "K-MINI",
    "shopsavvy": "3ONn300xybP3y66ibqc1",
    "barcode": 611247373064,
    "amazon": "B07G14HTBZ",
    "mpn": "5000200237",
    "images": [
      "https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/31jy5fSzyRL.jpg"
    ]
  },
  {
    "schedule": "daily",
    "retailer": "bestbuy.com",
    "title": "Keurig K-Elite Single Serve K-Cup Pod Maker with Strength and Temperature Control, Iced Coffee Capability, 12oz Brew Size, Brushed Silver",
    "category": "Home & Kitchen > Kitchen & Dining > Coffee, Tea & Espresso > Coffee Makers > Single-Serve Brewers",
    "brand": "Keurig",
    "color": "Silver",
    "model": "K-Elite",
    "shopsavvy": "DrKWneG0MpFlZpwZXNYa",
    "barcode": 611247369449,
    "amazon": "B0788F3R8X",
    "mpn": "5000197492",
    "images": [
      "https://x.shopsavvy.com/https://images-na.ssl-images-amazon.com/images/I/411fEW99TlL.jpg"
    ]
  }
]
```

---

## Deals API

### Browse Deals

Retrieve a feed of current shopping deals with Reddit-style sorting, filtering, and pagination. Each deal includes an expert grade (A+ through F), pricing, retailer info, community votes, and more.

**Endpoint:** `GET /v1/deals`

**Credit Cost:** 1 credit per 10 deals returned

**Parameters:**

| Parameter | Type | Default | Description |
|-----------|------|---------|-------------|
| `sort` | string | `hot` | Sort algorithm: `hot`, `new`, `top-hour`, `top-day`, `top-week` |
| `limit` | number | 25 | Results per page (1-100) |
| `offset` | number | 0 | Pagination offset |
| `category` | string | | Filter by product category |
| `retailer` | string | | Filter by retailer domain (e.g., `amazon.com`) |
| `tag` | string | | Filter by deal tag |
| `min_price` | number | | Minimum deal price |
| `max_price` | number | | Maximum deal price |
| `grade` | string | | Minimum grade: `A`, `B`, `C`, `D` |
| `format` | string | `json` | Response format: `json` or `csv` |

**Boolean Filters** (set to `true` to filter): `is_percentage_off`, `is_dollar_off`, `is_bogo`, `is_price_drop`, `is_free_shipping`, `is_fast_shipping`, `is_limited_time`, `is_clearance`, `is_new_product`, `is_bundle`, `is_refurbished`, `is_open_box`, `requires_membership`, `has_coupon_code`, `has_mail_in_rebate`

**Example Request:**

```bash
curl -X GET 'https://api.shopsavvy.com/v1/deals?sort=hot&limit=10&grade=B' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

**Example Response:**

```json
{
  "success": true,
  "deals": [
    {
      "path": "deals/abc123",
      "title": "Sony WH-1000XM5 Wireless Headphones - 25% Off",
      "subtitle": "Lowest price in 3 months",
      "description": "Industry-leading noise cancellation headphones at a rare discount...",
      "emoji": "🎧",
      "grade": { "letter": "A", "suffix": "+", "value": 0.98, "justification": "Excellent price on a top-rated product" },
      "pricing": { "current": 248.00, "original": 349.99, "currency": "USD" },
      "retailer": { "name": "Amazon" },
      "url": "https://...",
      "image": { "url": "https://..." },
      "votes": {
        "upvotes": 142,
        "downvotes": 3,
        "score": 139,
        "upvotes_internal": 6,
        "downvotes_internal": 1,
        "score_internal": 5,
        "upvotes_external": 136,
        "downvotes_external": 2,
        "score_external": 134
      },
      "comment_count": 23,
      "comment_count_community": 2,
      "tags": [{ "slug": "electronics", "display": "Electronics" }],
      "expires_at": "2026-04-15T00:00:00Z",
      "created_at": "2026-03-28T12:00:00Z"
    }
  ],
  "pagination": { "total": 487, "has_more": true, "limit": 10, "offset": 0 },
  "meta": { "request_id": "abc-123", "credits_used": 1, "credits_remaining": 999 }
}
```

**Vote and comment provenance**

Deals reach ShopSavvy two ways: posted by ShopSavvy users, and imported from public
deal communities. Engagement numbers on an imported deal carry over from its source,
so the top-level totals mix both populations. Read the breakdown when you need one or
the other:

| Field | Meaning |
|-------|---------|
| `votes.upvotes` / `downvotes` / `score` | Combined totals. Equals internal + external. |
| `votes.upvotes_internal` / `downvotes_internal` / `score_internal` | Votes cast by ShopSavvy accounts only. |
| `votes.upvotes_external` / `downvotes_external` / `score_external` | Engagement carried over from the deal's source at import time. |
| `comment_count` | Every comment on the deal thread. |
| `comment_count_community` | Comments written by ordinary ShopSavvy accounts, excluding ShopSavvy's own editorial personas. |

On the current corpus the external component dominates the combined totals by a wide
margin, so treat `score` as "how much attention this deal has attracted anywhere"
rather than "how many ShopSavvy users voted." Use `score_internal` /
`comment_count_community` for the latter. The same split is available in the CSV
export as `votes_up_internal`, `votes_down_internal`, `votes_up_external`,
`votes_down_external`, `comment_count` and `comment_count_community`.

---

## Reviews API

### Get TLDR Review for Product

Retrieve a concise expert review summary for a product, including pros, cons, a bottom line verdict, and quantitative scores. These are curated TLDR reviews — not raw customer reviews.

**Endpoint:** `GET /v1/products/reviews`

**Credit Cost:** 1 credit when a review exists for the product, 0 when it does not (`review` is `null`).

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `id` | string | Yes | Product identifier (barcode, ASIN, URL, model number) |
| `format` | string | No | Response format: `json` or `csv` |

**Example Request:**

```bash
curl -X GET 'https://api.shopsavvy.com/v1/products/reviews?id=B09XS7JWHH' \
  -H 'Authorization: Bearer YOUR_API_KEY'
```

**Example Response:**

```json
{
  "success": true,
  "product": { "path": "products/sony-wh1000xm5", "title": "Sony WH-1000XM5" },
  "review": {
    "slug": "sony-wh-1000xm5-review",
    "headline": "Best-in-class noise cancellation with premium sound",
    "pros": ["Industry-leading ANC", "30-hour battery life", "Comfortable all-day wear"],
    "cons": ["No IP rating", "No aptX support", "Premium pricing"],
    "bottom_line": "The best noise-cancelling headphones for most people.",
    "scores": {
      "overall": 0.87,
      "customer": 0.85,
      "professional": 0.89,
      "aspects": { "value": 0.78, "features": 0.91, "reliability": 0.83 }
    }
  },
  "meta": { "request_id": "abc-123", "credits_used": 1, "credits_remaining": 998 }
}
```

**Note:** Returns `"review": null` if no TLDR review exists for the product (no credit is charged).

**Scores** are on a **0-1 scale** (multiply by 10 or 100 for display). `aspects` is keyed by free-form aspect names drawn from the product's professional reviews — the set of aspects varies per product, and `scores` (or `aspects`) is omitted when no scored reviews exist.

---

## Webhooks

Register webhook URLs to get notified when prices drop, product availability changes, or scheduled refreshes complete.

### Create Webhook

**Endpoint:** `POST /v1/webhooks`

**Request Body:**

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| `url` | string | Yes | HTTPS URL to receive webhook POST requests |
| `events` | string[] | Yes | Event types: `price_drop`, `availability_change`, `schedule_completion` |

**Example:**
```bash
curl -X POST 'https://api.shopsavvy.com/v1/webhooks' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{"url": "https://your-app.com/webhooks/shopsavvy", "events": ["price_drop", "availability_change"]}'
```

The response includes a `secret` field (shown once) — use it to verify webhook signatures.

### Webhook Delivery Format

Every delivery is a JSON POST shaped like this:

```json
{
  "id": "8f14e45f-ceea-467a-9d2b-1c8f0b1a9c33",
  "event": "price_drop",
  "attempt": 1,
  "timestamp": "2026-08-10T18:04:11.529Z",
  "data": { "product": { }, "retailer": "amazon", "price": { }, "availability": { } }
}
```

`id` is the stable identifier for the event. `attempt` is the 1-based delivery attempt — `1` on the first delivery, `2` through `5` on retries. Both are also sent as headers, `X-ShopSavvy-Event-Id` and `X-ShopSavvy-Delivery-Attempt`, so you can check them without parsing the body.

### Deduplicating Retries

Delivery is at-least-once. If your server processes a request but the response is lost, times out, or returns a non-2xx status, we treat the delivery as failed and retry it — so you can receive the same event more than once.

`id` stays the same across the first attempt and every retry of that event, and is different for every new event. Record the ids you have processed and ignore a repeat. `timestamp` and the signature change on every attempt and must not be used for this.

`attempt` tells you which delivery of that event you are looking at without keeping any state of your own — `attempt > 1` means we did not see a 2xx for an earlier delivery of the same `id`. It is informational; dedupe on `id`.

### Verifying Webhook Signatures

Every webhook delivery includes an `X-ShopSavvy-Signature` header with format: `t=<timestamp>,v1=<signature>`.

To verify: compute `HMAC-SHA256(secret, "<timestamp>.<request_body>")` and compare to `v1`.

### List Webhooks

`GET /v1/webhooks` — Returns all your registered webhooks with status and failure counts.

### Update Webhook

**Endpoint:** `PUT /v1/webhooks/:id`

Update an existing webhook without losing its signing secret. All fields are optional, but at least one must be provided. Omitted fields are left unchanged — so you can flip `is_active` without resending `url` or `events`.

| Field | Type | Description |
|-------|------|-------------|
| `url` | string | New HTTPS URL to receive webhook POST requests |
| `events` | string[] | Replacement event list: `price_drop`, `availability_change`, `schedule_completion` |
| `is_active` | boolean | Enable (`true`) or disable (`false`) the webhook |

**Example — disable a webhook without deleting it:**
```bash
curl -X PUT 'https://api.shopsavvy.com/v1/webhooks/wh_abc123' \
  -H 'Authorization: Bearer YOUR_API_KEY' \
  -H 'Content-Type: application/json' \
  -d '{"is_active": false}'
```

Re-enabling a webhook (`is_active: true`) resets its consecutive-failure counter, so a webhook that was auto-disabled after repeated failures starts fresh.

### Test Webhook

`POST /v1/webhooks/:id/test` — Sends a test event to verify your URL is reachable.

### Delete Webhook

`DELETE /v1/webhooks/:id` — Permanently removes a webhook and all its event history.

**Retry Policy:** Failed deliveries are retried with exponential backoff (1min, 5min, 30min, 2hr, 12hr). After 5 failed attempts per event, the event is marked as permanently failed. After 50 consecutive failures, the webhook is automatically disabled.

**Limits:** Maximum 5 webhooks per account. Maximum 3 event types per webhook.

---

## Analytics & Tools

### Get API Usage Statistics

**Cost:** 0 credits.

You can retrieve your current API usage statistics and limits by using the `GET /usage` endpoint.

```bash
curl -X GET "https://api.shopsavvy.com/v1/usage" \
  -H "Authorization: Bearer ss_live_your_api_key_here"
```

This will return information about your current billing period usage, including credits used, remaining credits, and the percentage of your monthly limit used.

#### Example Response

```json
{
  "success": true,
  "data": {
    "current_period": {
      "start_date": "2025-01-01",
      "end_date": "2025-01-31",
      "credits_used": 1500,
      "credits_limit": 10000,
      "credits_remaining": 8500,
      "requests_made": 245
    },
    "usage_percentage": 15,
    "subscription_required": false,
    "subscription_status": "active"
  },
  "meta": {
    "credits_used": 0,
    "credits_remaining": 8500,
    "rate_limit_remaining": 958
  }
}
```

#### Response Fields

| Field | Description |
|-------|-------------|
| `start_date` / `end_date` | Your current billing period dates. |
| `credits_used` | Total credits consumed this billing period. |
| `credits_limit` | Your monthly credit allowance based on your subscription plan. |
| `credits_remaining` | Credits left for the current billing period. |
| `requests_made` | Total API requests made this billing period. |
| `usage_percentage` | Percentage of your monthly limit used. |
| `subscription_required` | `true` when no active Data API plan is attached to your account, in which case `credits_limit` is `0` and calls that cost credits will be rejected. |
| `subscription_status` | The status of your subscription — `active`, `trialing`, `past_due`, or `null` if you do not have one. A `past_due` subscription keeps working during the payment-retry grace period. |

### CSV to API Request Converter

This is an interactive tool on the documentation page that allows you to upload a CSV file, choose a column to use as product identifiers, and it will generate the HTTP path to request from the API to get product or pricing data for each of those products in a single request.

The tool supports:
- **Pasting CSV content** directly
- **Selecting an identifier column** from your CSV headers
- **Skipping the first row** (header row) toggle
- **Request type selection**: Product Details or Product Offers
- **Retailer filtering**: All Retailers or Single Retailer (with domain input, e.g., `bestbuy.com`)
- **Response format**: CSV or JSON

The generated API request path can be copied and used directly with `curl` or any HTTP client.

---

## Recipes

Five tasks from start to finish, each as a complete script in three languages: bash with `curl` and `jq`, Python 3 with `requests`, and TypeScript for Node 18+ (run it with `npx tsx`) or Bun. Every script on these pages was run against the live API before it was published. Each one reads your key from the `SHOPSAVVY_API_KEY` environment variable.

The scripts call the REST API directly rather than through an SDK so they can tell the two kinds of HTTP 429 apart: `ERR_RATE_LIMIT` means wait the `Retry-After` seconds and try again, `ERR_CREDITS_EXHAUSTED` means stop, because retrying will not help until the period resets (see [Errors](#errors)). Save the helper for your language next to the recipe scripts; every recipe uses it.

#### Helper: bash (shopsavvy-call.sh)

```bash
# Source this file: . ./shopsavvy-call.sh   (needs curl and jq; SHOPSAVVY_API_KEY in the environment)
# api METHOD PATH [JSON_BODY]: prints the response body. Waits out ERR_RATE_LIMIT (Retry-After),
# stops on ERR_CREDITS_EXHAUSTED and on any other error except a 404 (no product matched).
api() {
  local attempt status
  for attempt in 1 2 3 4 5; do
    if [ $# -ge 3 ]; then
      status=$(curl -sS -o "$SS_TMP/body" -D "$SS_TMP/headers" -w '%{http_code}' -X "$1" "https://api.shopsavvy.com/v1$2" \
        -H "Authorization: Bearer $SHOPSAVVY_API_KEY" -H 'Content-Type: application/json' -d "$3")
    else
      status=$(curl -sS -o "$SS_TMP/body" -D "$SS_TMP/headers" -w '%{http_code}' -X "$1" "https://api.shopsavvy.com/v1$2" \
        -H "Authorization: Bearer $SHOPSAVVY_API_KEY")
    fi
    if [ "$status" = 429 ]; then
      if [ "$(jq -r '.error_detail.code' "$SS_TMP/body")" = ERR_CREDITS_EXHAUSTED ]; then
        jq -r '.error_detail.action' "$SS_TMP/body" >&2
        return 2
      fi
      sleep "$(awk 'tolower($1) == "retry-after:" { print $2 + 0 }' "$SS_TMP/headers")"
      continue
    fi
    if [ "$status" -ge 400 ] && [ "$status" != 404 ]; then
      jq -r '"\(.error_detail.code): \(.error_detail.message) \(.error_detail.action)"' "$SS_TMP/body" >&2
      return 1
    fi
    cat "$SS_TMP/body"
    return 0
  done
  echo "Still rate limited after 5 attempts" >&2
  return 1
}
SS_TMP=$(mktemp -d)
```

#### Helper: Python (shopsavvy_call.py)

`pip install requests`

```python
import os
import time

import requests

API = "https://api.shopsavvy.com/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['SHOPSAVVY_API_KEY']}"}


class CreditsExhausted(Exception):
    """This month's credits are used up: waiting will not help until the period resets."""


def call(method, path, not_found_ok=False, **kwargs):
    """One Data API request. Waits out ERR_RATE_LIMIT (Retry-After) and stops on ERR_CREDITS_EXHAUSTED."""
    for _ in range(5):
        response = requests.request(method, API + path, headers=HEADERS, timeout=120, **kwargs)
        if response.status_code == 429:
            detail = response.json().get("error_detail", {})
            if detail.get("code") == "ERR_CREDITS_EXHAUSTED":
                raise CreditsExhausted(detail.get("action"))
            time.sleep(int(response.headers.get("Retry-After", "60")))
            continue
        if response.status_code == 404 and not_found_ok:
            return response
        if response.status_code >= 400:
            detail = response.json().get("error_detail", {})
            raise RuntimeError(f"{detail.get('code')}: {detail.get('message')} {detail.get('action', '')}")
        return response
    raise RuntimeError("Still rate limited after 5 attempts")
```

#### Helper: TypeScript (shopsavvy-call.ts)

No dependencies: it uses the built-in `fetch`.

```typescript
const API = 'https://api.shopsavvy.com/v1'
const KEY = process.env.SHOPSAVVY_API_KEY

export class CreditsExhausted extends Error {}

// One Data API request. Waits out ERR_RATE_LIMIT (Retry-After) and stops on ERR_CREDITS_EXHAUSTED.
export async function call(method: string, path: string, options: { body?: unknown, notFoundOk?: boolean } = {}): Promise<Response> {
  for (let attempt = 0; attempt < 5; attempt++) {
    const response = await fetch(API + path, {
      method,
      headers: { Authorization: `Bearer ${KEY}`, 'Content-Type': 'application/json' },
      body: options.body === undefined ? undefined : JSON.stringify(options.body),
    })
    if (response.status === 429) {
      const detail = (await response.json()).error_detail ?? {}
      if (detail.code === 'ERR_CREDITS_EXHAUSTED') throw new CreditsExhausted(detail.action)
      await new Promise((resolve) => setTimeout(resolve, Number(response.headers.get('Retry-After') ?? 60) * 1000))
      continue
    }
    if (response.status === 404 && options.notFoundOk) return response
    if (response.status >= 400) {
      const detail = (await response.json()).error_detail ?? {}
      throw new Error(`${detail.code}: ${detail.message} ${detail.action ?? ''}`)
    }
    return response
  }
  throw new Error('Still rate limited after 5 attempts')
}

// One CSV line, quoting any field that needs it.
export function csvLine(fields: unknown[]): string {
  return fields.map((field) => {
    const text = field === undefined || field === null ? '' : String(field)
    return /[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text
  }).join(',') + '\n'
}
```

### Recipe: Barcode List to Product Details

Turn a CSV of barcodes into a CSV of product records: title, brand, model, ShopSavvy ID, and how each barcode matched. The input file has a `barcode` header, then one barcode per line. Output rows keep the input order, and barcodes that match nothing are listed as `not_found`.

| Step | REST endpoint | MCP tool | Credits |
|------|---------------|----------|---------|
| Look up 100 barcodes at a time | `POST /v1/products/batch` | `product_lookup_batch` | 1 per product found |
| Poll a batch of more than 20 until it completes | `GET /v1/batch/{id}` | none | 0 |

**Cost for N barcodes:** at most N credits, since barcodes that match nothing cost 0. 10,000 barcodes take 100 batch requests and at most 10,000 credits. Add `"include": ["offers"]` to the request body for current prices as well, at 3 more credits per product that has offers. Batches of 21 to 100 identifiers run asynchronously; see [Batch Product Lookup](#batch-product-lookup).

#### bash

```bash
#!/usr/bin/env bash
# Bulk barcode CSV -> product details CSV, 100 barcodes per POST /v1/products/batch.
# Usage: SHOPSAVVY_API_KEY=... ./barcodes-to-products.sh barcodes.csv products.csv
set -euo pipefail
. ./shopsavvy-call.sh

echo "barcode,status,title,brand,model,shopsavvy_id,matched_by,candidates" > "$2"
tail -n +2 "$1" | tr -d '\r' | grep -v '^$' | split -l 100 - "$SS_TMP/chunk_"
for chunk in "$SS_TMP"/chunk_*; do
  response=$(api POST /products/batch "$(jq -R -s -c 'split("\n") | map(select(length > 0)) | {identifiers: .}' "$chunk")")
  batch_id=$(jq -r '.batch.id // empty' <<< "$response")
  if [ -n "$batch_id" ]; then
    # More than 20 identifiers: poll until the batch is done.
    sleep "$(jq '[.batch.estimated_seconds // 10, 30] | min' <<< "$response")"
    until [ "$(jq -r '.batch.status' <<< "$response")" = completed ]; do
      [ "$(jq -r '.batch.status' <<< "$response")" = failed ] && { jq -r '.error' <<< "$response" >&2; exit 1; }
      sleep 5
      response=$(api GET "/batch/$batch_id")
    done
  fi
  # Results can come back in any order; write them in the order of the input file.
  jq -r --rawfile chunk "$chunk" '
    (.results | map({key: .identifier, value: .}) | from_entries) as $by
    | $chunk | split("\n") | map(select(length > 0))[]
    | . as $barcode | ($by[$barcode] // {status: "not_found"}) as $r
    | [$barcode, $r.status, $r.product.title, $r.product.brand, $r.product.model, $r.product.shopsavvy, $r.product.match.by, $r.product.match.candidates]
    | @csv' <<< "$response" >> "$2"
done
echo "Wrote $2"
```

#### Python

```python
"""Bulk barcode CSV -> product details CSV, 100 barcodes per POST /v1/products/batch.

Usage: SHOPSAVVY_API_KEY=... python barcodes_to_products.py barcodes.csv products.csv
"""
import csv
import sys
import time

from shopsavvy_call import call


def lookup(identifiers):
    """Up to 100 identifiers. 20 or fewer are answered at once; more are polled until done."""
    body = call("POST", "/products/batch", json={"identifiers": identifiers}).json()
    if "results" in body:
        return body["results"]
    batch_id = body["batch"]["id"]
    time.sleep(min(body["batch"].get("estimated_seconds", 10), 30))
    while True:
        status = call("GET", f"/batch/{batch_id}").json()
        if status["batch"]["status"] == "completed":
            return status["results"]
        if status["batch"]["status"] == "failed":
            raise RuntimeError(status.get("error", "batch failed"))
        time.sleep(5)


def main(source, destination):
    with open(source, newline="") as f:
        barcodes = [row["barcode"].strip() for row in csv.DictReader(f) if row["barcode"].strip()]
    with open(destination, "w", newline="") as f:
        out = csv.writer(f)
        out.writerow(["barcode", "status", "title", "brand", "model", "shopsavvy_id", "matched_by", "candidates"])
        for start in range(0, len(barcodes), 100):
            chunk = barcodes[start:start + 100]
            # Results can come back in any order; write them in the order of the input file.
            by_identifier = {result["identifier"]: result for result in lookup(chunk)}
            for barcode in chunk:
                result = by_identifier.get(barcode, {"status": "not_found"})
                product = result.get("product") or {}
                match = product.get("match") or {}
                out.writerow([barcode, result["status"], product.get("title", ""), product.get("brand", ""),
                              product.get("model", ""), product.get("shopsavvy", ""), match.get("by", ""), match.get("candidates", "")])
    print(f"Looked up {len(barcodes)} barcodes; wrote {destination}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
```

#### TypeScript

```typescript
// Bulk barcode CSV -> product details CSV, 100 barcodes per POST /v1/products/batch.
// Usage: SHOPSAVVY_API_KEY=... npx tsx barcodes-to-products.ts barcodes.csv products.csv
import { readFileSync, writeFileSync } from 'node:fs'
import { call, csvLine } from './shopsavvy-call'

const sleep = (seconds: number) => new Promise((resolve) => setTimeout(resolve, seconds * 1000))

// Up to 100 identifiers. 20 or fewer are answered at once; more are polled until done.
async function lookup(identifiers: string[]): Promise<any[]> {
  const body = await (await call('POST', '/products/batch', { body: { identifiers } })).json()
  if (body.results) return body.results
  await sleep(Math.min(body.batch.estimated_seconds ?? 10, 30))
  while (true) {
    const status = await (await call('GET', `/batch/${body.batch.id}`)).json()
    if (status.batch.status === 'completed') return status.results
    if (status.batch.status === 'failed') throw new Error(status.error ?? 'batch failed')
    await sleep(5)
  }
}

async function main(source: string, destination: string) {
  const barcodes = readFileSync(source, 'utf8').split(/\r?\n/).slice(1).map((line) => line.trim()).filter(Boolean)
  let csv = csvLine(['barcode', 'status', 'title', 'brand', 'model', 'shopsavvy_id', 'matched_by', 'candidates'])
  for (let start = 0; start < barcodes.length; start += 100) {
    const chunk = barcodes.slice(start, start + 100)
    // Results can come back in any order; write them in the order of the input file.
    const byIdentifier = new Map((await lookup(chunk)).map((result) => [result.identifier, result]))
    for (const barcode of chunk) {
      const result = byIdentifier.get(barcode) ?? { status: 'not_found' }
      const product = result.product ?? {}
      csv += csvLine([barcode, result.status, product.title, product.brand, product.model, product.shopsavvy, product.match?.by, product.match?.candidates])
    }
  }
  writeFileSync(destination, csv)
  console.log(`Looked up ${barcodes.length} barcodes; wrote ${destination}`)
}

main(process.argv[2], process.argv[3])
```

### Recipe: Price Monitor With Webhooks

Have ShopSavvy re-check a list of products every day and call your server when a price drops or a product goes in or out of stock. Part one schedules the products and registers the webhook. Part two is the receiver: it verifies the `X-ShopSavvy-Signature` header, rejects stale or forged requests, and ignores retries of an event it has already handled.

| Step | REST endpoint | MCP tool | Credits |
|------|---------------|----------|---------|
| Schedule daily re-checks | `PUT /v1/products/scheduled` | `product_schedule` | 1 per product, once |
| Register the webhook (save the secret it returns) | `POST /v1/webhooks` | none | 0 |
| Receive `price_drop` and `availability_change` events | your HTTPS endpoint | none | 0 |
| Read the latest prices when you need them | `GET /v1/products/offers` | `product_offers` | 3 per product with offers |

**Cost for N products:** N credits to schedule them; the daily refreshes and webhook deliveries are not charged. Scheduled refreshes run at the retailers ShopSavvy can re-check through an official retailer API (Amazon and Best Buy today); other retailers update as ShopSavvy sees them. See [Enabling Scheduled Refreshes for Products](#enabling-scheduled-refreshes-for-products) and [Webhooks](#webhooks). An account can have up to 5 webhooks.

#### Set up: bash

```bash
#!/usr/bin/env bash
# Schedule products for daily re-checks and register a webhook for price drops and stock changes.
# Usage: SHOPSAVVY_API_KEY=... ./monitor-setup.sh https://your-app.example/shopsavvy 611247373064,885909950805
set -euo pipefail
. ./shopsavvy-call.sh

# 1 credit per product scheduled (up to 100 per call); the daily refreshes themselves are not charged.
api PUT "/products/scheduled?ids=$2&schedule=daily" | jq -r '.data[] | "Scheduled \(.schedule): \(.title)"'
# The secret is shown once. Store it where your receiver can read it.
api POST /webhooks "$(jq -n --arg url "$1" '{url: $url, events: ["price_drop", "availability_change"]}')" \
  | jq -r '"Webhook \(.webhook.id) registered. SHOPSAVVY_WEBHOOK_SECRET=\(.webhook.secret)"'
```

#### Set up: Python

```python
"""Schedule products for daily re-checks and register a webhook for price drops and stock changes.

Usage: SHOPSAVVY_API_KEY=... python monitor_setup.py https://your-app.example/shopsavvy 611247373064 885909950805
"""
import sys

from shopsavvy_call import call


def main(webhook_url, identifiers):
    # 1 credit per product scheduled; the daily refreshes themselves are not charged.
    for start in range(0, len(identifiers), 100):
        ids = ",".join(identifiers[start:start + 100])
        scheduled = call("PUT", "/products/scheduled", params={"ids": ids, "schedule": "daily"}).json()
        for product in scheduled["data"]:
            print(f"Scheduled {product['schedule']}: {product['title']}")
    webhook = call("POST", "/webhooks", json={"url": webhook_url, "events": ["price_drop", "availability_change"]}).json()["webhook"]
    # The secret is shown once. Store it where your receiver can read it.
    print(f"Webhook {webhook['id']} registered. SHOPSAVVY_WEBHOOK_SECRET={webhook['secret']}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2:])
```

#### Set up: TypeScript

```typescript
// Schedule products for daily re-checks and register a webhook for price drops and stock changes.
// Usage: SHOPSAVVY_API_KEY=... npx tsx monitor-setup.ts https://your-app.example/shopsavvy 611247373064 885909950805
import { call } from './shopsavvy-call'

async function main(webhookUrl: string, identifiers: string[]) {
  // 1 credit per product scheduled; the daily refreshes themselves are not charged.
  for (let start = 0; start < identifiers.length; start += 100) {
    const ids = encodeURIComponent(identifiers.slice(start, start + 100).join(','))
    const scheduled = await (await call('PUT', `/products/scheduled?ids=${ids}&schedule=daily`)).json()
    for (const product of scheduled.data) console.log(`Scheduled ${product.schedule}: ${product.title}`)
  }
  const { webhook } = await (await call('POST', '/webhooks', { body: { url: webhookUrl, events: ['price_drop', 'availability_change'] } })).json()
  // The secret is shown once. Store it where your receiver can read it.
  console.log(`Webhook ${webhook.id} registered. SHOPSAVVY_WEBHOOK_SECRET=${webhook.secret}`)
}

main(process.argv[2], process.argv.slice(3))
```

#### Receiver: Python

The signature is `t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">`, computed with the webhook's secret. Verify it against the raw request body before parsing the JSON.

```python
"""Receive ShopSavvy Data API webhooks: verify the signature, drop repeats, handle the event.

Usage: SHOPSAVVY_WEBHOOK_SECRET=<secret from POST /v1/webhooks> python webhook_receiver.py
Listens on port 8000. Put it behind HTTPS and register that URL.
"""
import hashlib
import hmac
import json
import os
import time
from http.server import BaseHTTPRequestHandler, HTTPServer

SECRET = os.environ["SHOPSAVVY_WEBHOOK_SECRET"].encode()
TOLERANCE_SECONDS = 300
seen_event_ids = set()  # keep these in your database in production


def signature_valid(header, body):
    """X-ShopSavvy-Signature is t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">."""
    parts = dict(item.split("=", 1) for item in header.split(",") if "=" in item)
    timestamp, signature = parts.get("t", ""), parts.get("v1", "")
    if not timestamp.isdigit() or abs(time.time() - int(timestamp)) > TOLERANCE_SECONDS:
        return False
    expected = hmac.new(SECRET, timestamp.encode() + b"." + body, hashlib.sha256).hexdigest()
    return hmac.compare_digest(expected, signature)


class Handler(BaseHTTPRequestHandler):
    def do_POST(self):
        body = self.rfile.read(int(self.headers.get("Content-Length", 0)))
        if not signature_valid(self.headers.get("X-ShopSavvy-Signature", ""), body):
            self.send_response(401)
            self.end_headers()
            return
        event = json.loads(body)
        # Retries reuse the same id; test events have none.
        if event.get("id") not in seen_event_ids:
            if event.get("id"):
                seen_event_ids.add(event["id"])
            data = event.get("data", {})
            product, price = data.get("product", {}), data.get("price", {})
            print(f"{event['event']}: {product.get('title')} at {data.get('retailer')}: "
                  f"{price.get('old')} -> {price.get('new')} {price.get('currency') or ''}", flush=True)
        self.send_response(200)
        self.end_headers()


HTTPServer(("", 8000), Handler).serve_forever()
```

#### Receiver: TypeScript

```typescript
// Receive ShopSavvy Data API webhooks: verify the signature, drop repeats, handle the event.
// Usage: SHOPSAVVY_WEBHOOK_SECRET=<secret from POST /v1/webhooks> npx tsx webhook-receiver.ts
// Listens on port 8000. Put it behind HTTPS and register that URL.
import { createServer } from 'node:http'
import { createHmac, timingSafeEqual } from 'node:crypto'

const SECRET = process.env.SHOPSAVVY_WEBHOOK_SECRET!
const TOLERANCE_SECONDS = 300
const seenEventIds = new Set<string>() // keep these in your database in production

// X-ShopSavvy-Signature is t=<unix seconds>,v1=<hex HMAC-SHA256 of "<t>.<raw body>">.
function signatureValid(header: string, body: Buffer): boolean {
  const parts = Object.fromEntries(header.split(',').map((item) => item.split('=', 2)))
  const timestamp = parts.t ?? ''
  const signature = Buffer.from(parts.v1 ?? '')
  if (!/^\d+$/.test(timestamp) || Math.abs(Date.now() / 1000 - Number(timestamp)) > TOLERANCE_SECONDS) return false
  const expected = Buffer.from(createHmac('sha256', SECRET).update(`${timestamp}.`).update(body).digest('hex'))
  return expected.length === signature.length && timingSafeEqual(expected, signature)
}

createServer((request, response) => {
  const chunks: Buffer[] = []
  request.on('data', (chunk) => chunks.push(chunk))
  request.on('end', () => {
    const body = Buffer.concat(chunks)
    if (!signatureValid(String(request.headers['x-shopsavvy-signature'] ?? ''), body)) {
      response.writeHead(401).end()
      return
    }
    const event = JSON.parse(body.toString('utf8'))
    // Retries reuse the same id; test events have none.
    if (!seenEventIds.has(event.id)) {
      if (event.id) seenEventIds.add(event.id)
      const { product = {}, retailer, price = {} } = event.data ?? {}
      console.log(`${event.event}: ${product.title} at ${retailer}: ${price.old} -> ${price.new} ${price.currency ?? ''}`)
    }
    response.writeHead(200).end()
  })
}).listen(8000)
```

### Recipe: Export 90 Days of Price History to CSV

Write every recorded price of a list of products over the last 90 days to one CSV: one row per price point, with the product, retailer, date, price, currency and availability. The input file has an `identifier` header (barcodes, ASINs, model numbers or product URLs).

| Step | REST endpoint | MCP tool | Credits |
|------|---------------|----------|---------|
| History for up to 100 products, as CSV | `GET /v1/products/offers/history?format=csv` | `product_price_history` | 3 per product with offers, plus 90 per request (1 per day of the window) |

**Cost for N products:** 3 × N + 90 for every 100 products. 1,000 products cost 3,000 + 900 = 3,900 credits. A request in which no product has offers is not charged. Shorter windows cost less per request; the longest window is 366 days. See [Retrieving Offers With Historical Offer Data](#retrieving-offers-with-historical-offer-data).

#### bash

```bash
#!/usr/bin/env bash
# Export the last 90 days of recorded prices for a list of products to one CSV.
# Usage: SHOPSAVVY_API_KEY=... ./history-export.sh skus.csv history.csv
# skus.csv has an "identifier" column: barcodes, ASINs, model numbers or product URLs.
set -euo pipefail
. ./shopsavvy-call.sh

end=$(date -u +%Y-%m-%d)
start=$(date -u -v-90d +%Y-%m-%d 2>/dev/null || date -u -d '90 days ago' +%Y-%m-%d)
: > "$2"
tail -n +2 "$1" | tr -d '\r' | grep -v '^$' | split -l 100 - "$SS_TMP/chunk_"
for chunk in "$SS_TMP"/chunk_*; do
  ids=$(paste -sd, "$chunk" | jq -sRr @uri)
  api GET "/products/offers/history?ids=$ids&start=$start&end=$end&format=csv" > "$SS_TMP/part.csv"
  # A 404 (no product with offers in this chunk) comes back as JSON, not CSV: skip it.
  head -c 1 "$SS_TMP/part.csv" | grep -q '{' && continue
  if [ -s "$2" ]; then tail -n +2 "$SS_TMP/part.csv" >> "$2"; else cat "$SS_TMP/part.csv" >> "$2"; fi
done
echo "Wrote $2 ($start to $end)"
```

#### Python

```python
"""Export the last 90 days of recorded prices for a list of products to one CSV.

Usage: SHOPSAVVY_API_KEY=... python history_export.py skus.csv history.csv
skus.csv has an "identifier" column: barcodes, ASINs, model numbers or product URLs.
"""
import csv
import sys
from datetime import date, timedelta

from shopsavvy_call import call


def main(source, destination):
    with open(source, newline="") as f:
        identifiers = [row["identifier"].strip() for row in csv.DictReader(f) if row["identifier"].strip()]
    end = date.today()
    start = end - timedelta(days=90)
    header_written = False
    with open(destination, "w", newline="") as out:
        for first in range(0, len(identifiers), 100):
            params = {"ids": ",".join(identifiers[first:first + 100]), "start": start.isoformat(),
                      "end": end.isoformat(), "format": "csv"}
            response = call("GET", "/products/offers/history", not_found_ok=True, params=params)
            if response.status_code == 404:
                continue  # none of these matched a product with offers: nothing charged
            lines = response.text.splitlines(keepends=True)
            out.writelines(lines if not header_written else lines[1:])
            header_written = True
    print(f"Wrote {destination} ({start} to {end})")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
```

#### TypeScript

```typescript
// Export the last 90 days of recorded prices for a list of products to one CSV.
// Usage: SHOPSAVVY_API_KEY=... npx tsx history-export.ts skus.csv history.csv
// skus.csv has an "identifier" column: barcodes, ASINs, model numbers or product URLs.
import { readFileSync, writeFileSync } from 'node:fs'
import { call } from './shopsavvy-call'

async function main(source: string, destination: string) {
  const identifiers = readFileSync(source, 'utf8').split(/\r?\n/).slice(1).map((line) => line.trim()).filter(Boolean)
  const end = new Date()
  const start = new Date(end.getTime() - 90 * 24 * 60 * 60 * 1000)
  const day = (d: Date) => d.toISOString().slice(0, 10)
  let csv = ''
  for (let first = 0; first < identifiers.length; first += 100) {
    const ids = encodeURIComponent(identifiers.slice(first, first + 100).join(','))
    const response = await call('GET', `/products/offers/history?ids=${ids}&start=${day(start)}&end=${day(end)}&format=csv`, { notFoundOk: true })
    if (response.status === 404) continue // none of these matched a product with offers: nothing charged
    const text = await response.text()
    csv += csv === '' ? text : text.slice(text.indexOf('\n') + 1)
  }
  writeFileSync(destination, csv)
  console.log(`Wrote ${destination} (${day(start)} to ${day(end)})`)
}

main(process.argv[2], process.argv[3])
```

### Recipe: Competitor Price Position Report

For each of your products, find the lowest price among other retailers and where your own price ranks. The input file has `identifier` and `my_price` columns. The report compares the lowest new-condition price per retailer, counts only prices seen in the last 7 days, and leaves out third-party marketplace sellers. Set `COMPETITORS` to the retailers you actually compete with, so small sellers that list the same product do not set your benchmark.

| Step | REST endpoint | MCP tool | Credits |
|------|---------------|----------|---------|
| Current offers for up to 100 products | `GET /v1/products/offers` | `product_offers` | 3 per product with offers |

**Cost for N products:** at most 3 × N credits per run. Run it daily for a month and that is 90 × N, so 300 products checked daily come to about 27,000 credits. Each offer's `timestamp` is when ShopSavvy last saw that price; the 7-day window keeps old prices out of the comparison. See [Retrieving Offers for Products at All Retailers](#retrieving-offers-for-products-at-all-retailers).

#### bash

```bash
#!/usr/bin/env bash
# Where does your price sit against every retailer? One row per product.
# Usage: SHOPSAVVY_API_KEY=... ./price-position.sh my-prices.csv position.csv
# my-prices.csv has "identifier" (barcode, ASIN, model number or URL) and "my_price" columns.
set -euo pipefail
. ./shopsavvy-call.sh

MAX_AGE_DAYS=7       # ignore prices not seen in the last week
COMPETITORS='null'   # or a JSON array of retailer names, e.g. '["Amazon","Best Buy","Walmart"]'

echo "identifier,title,my_price,lowest_price,lowest_retailer,gap_pct,rank,retailers" > "$2"
tail -n +2 "$1" | tr -d '\r' | grep -v '^$' | split -l 100 - "$SS_TMP/chunk_"
for chunk in "$SS_TMP"/chunk_*; do
  ids=$(cut -d, -f1 "$chunk" | paste -sd, - | jq -sRr 'rtrimstr("\n") | @uri')
  api GET "/products/offers?ids=$ids" > "$SS_TMP/offers.json"
  jq -r --rawfile chunk "$chunk" --argjson competitors "$COMPETITORS" --argjson maxAge "$((MAX_AGE_DAYS * 86400))" '
    ((.data // []) | map({key: .match.identifier, value: .}) | from_entries) as $products
    | $chunk | split("\n") | map(select(length > 0) | split(","))[]
    | .[0] as $id | (.[1] | tonumber) as $mine | $products[$id] as $p
    # Lowest recent new-condition price per retailer: the retailer'"'"'s own price, not a marketplace seller'"'"'s.
    | [($p.offers // [])[]
        | select(.condition == "new" and .price != null and (.is_marketplace | not)
                 and (now - (.timestamp | sub("\\.[0-9]+Z$"; "Z") | fromdateiso8601)) <= $maxAge
                 and ($competitors == null or (.retailer as $r | $competitors | index($r))))]
    | group_by(.retailer) | map({retailer: .[0].retailer, price: (map(.price) | min)}) as $lowest
    | if ($lowest | length) == 0 then [$id, ($p.title // ""), $mine, "", "", "", "", 0]
      else ($lowest | min_by(.price)) as $best
        | [$id, $p.title, $mine, $best.price, $best.retailer,
           ((($mine - $best.price) / $best.price * 1000 | round) / 10),
           (1 + ($lowest | map(select(.price < $mine)) | length)), ($lowest | length)]
      end
    | @csv' "$SS_TMP/offers.json" >> "$2"
done
echo "Wrote $2"
```

#### Python

```python
"""Where does your price sit against every retailer? One row per product.

Usage: SHOPSAVVY_API_KEY=... python price_position.py my-prices.csv position.csv
my-prices.csv has "identifier" (barcode, ASIN, model number or URL) and "my_price" columns.
"""
import csv
import sys
from datetime import datetime, timedelta, timezone

from shopsavvy_call import call

MAX_AGE = timedelta(days=7)  # ignore prices not seen in the last week
COMPETITORS = None  # or a set of retailer names to compare against only those, e.g. {"Amazon", "Best Buy", "Walmart"}


def main(source, destination):
    with open(source, newline="") as f:
        mine = {row["identifier"].strip(): float(row["my_price"]) for row in csv.DictReader(f) if row["identifier"].strip()}
    identifiers = list(mine)
    products = {}
    for start in range(0, len(identifiers), 100):
        response = call("GET", "/products/offers", not_found_ok=True, params={"ids": ",".join(identifiers[start:start + 100])})
        if response.status_code == 404:
            continue  # none of these matched: nothing charged
        for product in response.json()["data"]:
            products[product["match"]["identifier"]] = product
    with open(destination, "w", newline="") as f:
        out = csv.writer(f)
        out.writerow(["identifier", "title", "my_price", "lowest_price", "lowest_retailer", "gap_pct", "rank", "retailers"])
        for identifier, my_price in mine.items():
            product = products.get(identifier)
            # Lowest recent new-condition price per retailer.
            cutoff = datetime.now(timezone.utc) - MAX_AGE
            lowest = {}
            for offer in (product or {}).get("offers", []):
                seen = datetime.fromisoformat(offer["timestamp"].replace("Z", "+00:00"))
                if (offer.get("condition") == "new" and offer.get("price") is not None and seen >= cutoff
                        and not offer.get("is_marketplace")  # the retailer's own price, not a third-party seller's
                        and (COMPETITORS is None or offer["retailer"] in COMPETITORS)):
                    lowest[offer["retailer"]] = min(offer["price"], lowest.get(offer["retailer"], offer["price"]))
            if not lowest:
                out.writerow([identifier, (product or {}).get("title", ""), my_price, "", "", "", "", 0])
                continue
            retailer, price = min(lowest.items(), key=lambda item: item[1])
            rank = 1 + sum(1 for p in lowest.values() if p < my_price)
            out.writerow([identifier, product["title"], my_price, price, retailer,
                          round((my_price - price) / price * 100, 1), rank, len(lowest)])
    print(f"Wrote {destination}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])
```

#### TypeScript

```typescript
// Where does your price sit against every retailer? One row per product.
// Usage: SHOPSAVVY_API_KEY=... npx tsx price-position.ts my-prices.csv position.csv
// my-prices.csv has "identifier" (barcode, ASIN, model number or URL) and "my_price" columns.
import { readFileSync, writeFileSync } from 'node:fs'
import { call, csvLine } from './shopsavvy-call'

const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 // ignore prices not seen in the last week
const COMPETITORS: Set<string> | null = null // or e.g. new Set(['Amazon', 'Best Buy', 'Walmart']) to compare against those only

async function main(source: string, destination: string) {
  const mine = new Map<string, number>()
  for (const line of readFileSync(source, 'utf8').split(/\r?\n/).slice(1)) {
    const [identifier, myPrice] = line.split(',').map((field) => field.trim())
    if (identifier) mine.set(identifier, Number(myPrice))
  }
  const identifiers = [...mine.keys()]
  const products = new Map<string, any>()
  for (let start = 0; start < identifiers.length; start += 100) {
    const ids = encodeURIComponent(identifiers.slice(start, start + 100).join(','))
    const response = await call('GET', `/products/offers?ids=${ids}`, { notFoundOk: true })
    if (response.status === 404) continue // none of these matched: nothing charged
    for (const product of (await response.json()).data) products.set(product.match.identifier, product)
  }
  let csv = csvLine(['identifier', 'title', 'my_price', 'lowest_price', 'lowest_retailer', 'gap_pct', 'rank', 'retailers'])
  for (const [identifier, myPrice] of mine) {
    const product = products.get(identifier)
    // Lowest recent new-condition price per retailer.
    const lowest = new Map<string, number>()
    for (const offer of product?.offers ?? []) {
      const recent = Date.now() - Date.parse(offer.timestamp) <= MAX_AGE_MS
      // The retailer's own price (not a third-party marketplace seller), optionally only your competitors.
      const wanted = !offer.is_marketplace && (COMPETITORS === null || COMPETITORS.has(offer.retailer))
      if (offer.condition === 'new' && offer.price != null && recent && wanted) lowest.set(offer.retailer, Math.min(offer.price, lowest.get(offer.retailer) ?? offer.price))
    }
    if (lowest.size === 0) {
      csv += csvLine([identifier, product?.title ?? '', myPrice, '', '', '', '', 0])
      continue
    }
    const [retailer, price] = [...lowest].reduce((best, entry) => (entry[1] < best[1] ? entry : best))
    const rank = 1 + [...lowest.values()].filter((p) => p < myPrice).length
    csv += csvLine([identifier, product.title, myPrice, price, retailer, Math.round((myPrice - price) / price * 1000) / 10, rank, lowest.size])
  }
  writeFileSync(destination, csv)
  console.log(`Wrote ${destination}`)
}

main(process.argv[2], process.argv[3])
```

### Recipe: Live Prices in Claude Code

Give Claude Code the ShopSavvy MCP server so it can look up products, compare prices across retailers and read price history while it works. It works without a key; with your Data API key the rate limit is higher and tool calls use your credits.

| Step | Command or prompt | MCP tool | Credits with a key |
|------|-------------------|----------|--------------------|
| Add the server | `claude mcp add --transport http shopsavvy https://api.shopsavvy.com/mcp` | none | 0 |
| Identify a product | "What product is barcode 611247373064?" | `product_lookup` | 1 |
| Compare prices | "Where is it cheapest right now, and when was each price checked?" | `product_offers` | 3 |
| Check the history | "How has its price changed over the last 30 days?" | `product_price_history` | 33 (1 per day plus 3) |
| Check your credits | "How many ShopSavvy credits do I have left this month?" | `api_usage` | 0 |

**Cost:** without a key, tool calls are free and limited to 10 a minute and 100 an hour per IP address. With a key the limit is 100 a minute and each call costs what the matching REST request does (the tool list is in [Available AI Tools](#available-ai-tools)). The four prompts above cost 37 credits with a key.

#### Add the server

```bash
# Without a key
claude mcp add --transport http shopsavvy https://api.shopsavvy.com/mcp

# With your Data API key: higher rate limit, calls use your credits
claude mcp add --transport http shopsavvy https://api.shopsavvy.com/mcp \
  --header "Authorization: Bearer $SHOPSAVVY_API_KEY"

# Check that it connected
claude mcp list
```

Then ask in plain language; Claude picks the tools. To see exactly what a tool returns, call the server yourself:

```bash
curl -s https://api.shopsavvy.com/mcp \
  -H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"product_offers","arguments":{"identifier":"611247373064"}}}'
```

Other clients (Cursor, VS Code, Claude Desktop, ChatGPT) are covered in [Claude Desktop Setup](#claude-desktop-setup).

---

## Reference

### Errors

Every error response has the same shape. `error` is kept as a plain string for older clients; read `error_detail` in new code.

```json
{
  "success": false,
  "error": "A product identifier is required.",
  "error_detail": {
    "code": "ERR_IDENTIFIER_REQUIRED",
    "message": "An 'ids' parameter is required. It must contain one or more product identifiers (barcode, UPC, EAN, ISBN, GTIN, ASIN, model number, URL, or ShopSavvy product ID), separated by commas.",
    "action": "Pass identifiers in the ids query parameter, e.g. ?ids=611247373064 (any type: barcode, ASIN, URL, model number). Parameters named barcode, upc or asin are not read.",
    "docs_url": "https://shopsavvy.com/data/documentation/errors#err_identifier_required"
  },
  "meta": {
    "request_id": "4f9d2c1e-…",
    "credits_used": 0,
    "credits_remaining": 0,
    "rate_limit_remaining": 958
  }
}
```

- Branch on `error_detail.code`, not on the HTTP status (two different codes share 429) or the message (messages get more specific over time).
- `action` is a one-line fix you can show to a developer. `docs_url` links to the entry for that code below.
- **Errors never cost credits.** `meta.credits_used` is always `0`; if any credits had been recorded for the request they are reversed, so your balance matches.
- Quote `meta.request_id` when you contact support@shopsavvy.com.

| Code | HTTP | Meaning | Retry? |
|------|------|---------|--------|
| `ERR_AUTH_MISSING` | 401 | No API key was sent. | No, fix the request |
| `ERR_AUTH_INVALID` | 401 | The key is not in the `ss_live_` format. | No |
| `ERR_AUTH_REVOKED` | 401 | The key does not exist or was revoked. | No |
| `ERR_SUBSCRIPTION_REQUIRED` | 403 | The account has no Data API plan. | No |
| `ERR_SUBSCRIPTION_INACTIVE` | 403 | The plan is canceled or unpaid past the grace window. | No |
| `ERR_CREDITS_EXHAUSTED` | 429 | This month's credits (and any bonus credits) are used up. | Not until the period resets or you upgrade |
| `ERR_RATE_LIMIT` | 429 | More than 1,000 requests in the rolling hour. | Yes, after `Retry-After` seconds |
| `ERR_INVALID_PARAMS` | 400 | A parameter is missing, malformed or over a limit. | No, fix the request |
| `ERR_IDENTIFIER_REQUIRED` | 400 | No identifiers were sent in `ids` (or `id` on reviews). | No, fix the request |
| `ERR_PRODUCT_NOT_FOUND` | 404 | None of the identifiers matched a product. | No; try another identifier |
| `ERR_ENDPOINT_NOT_FOUND` | 404 | The batch job or webhook id does not exist. | No |
| `ERR_METHOD_NOT_ALLOWED` | 405 | The endpoint is not available to this caller (for example, in the playground sandbox). | No |
| `ERR_INTERNAL` | 500 | Something failed on our side. | Yes, with backoff |

#### ERR_AUTH_MISSING

**HTTP 401.** The request had no `Authorization` header and no `api_key` query parameter. Send `Authorization: Bearer ss_live_…` with every request. See [Overview & Authentication](#overview--authentication).

#### ERR_AUTH_INVALID

**HTTP 401.** The value is not a ShopSavvy key: keys are `ss_live_` followed by 32 characters. Check for a missing `Bearer ` prefix, extra quotes or whitespace from an environment file, or a truncated copy. Copy the key again from [API Keys](https://shopsavvy.com/data/api-keys).

#### ERR_AUTH_REVOKED

**HTTP 401.** The key has the right format but no active key matches it, usually because it was revoked or belongs to a deleted account. Create a new key at [API Keys](https://shopsavvy.com/data/api-keys).

#### ERR_SUBSCRIPTION_REQUIRED

**HTTP 403.** The key is valid but the account has no Data API plan. Start a plan (Starter has a 14-day trial) at [shopsavvy.com/data](https://shopsavvy.com/data#pricing).

#### ERR_SUBSCRIPTION_INACTIVE

**HTTP 403.** The plan exists but is canceled, or a payment failed and the one-week grace window has passed. Update the payment method in [Billing](https://shopsavvy.com/data/billing).

#### ERR_CREDITS_EXHAUSTED

**HTTP 429**, without a `Retry-After` header. The plan's monthly credits, and any referral bonus credits, are used up. Retrying will not help until the billing period resets; upgrade in [Billing](https://shopsavvy.com/data/billing) to continue now. The error's `action` names the next plan up for your account, with its monthly price and credits (above Scale, it points to Enterprise pricing by quote). `GET /v1/usage` (0 credits) shows your balance and period dates. Credits are explained in [Pricing & Credits](#pricing--credits).

#### ERR_RATE_LIMIT

**HTTP 429**, with a `Retry-After` header in seconds. The account made more than 1,000 requests in the last rolling hour, counted across all its keys. Wait `Retry-After` seconds, then retry; rejected requests do not count against the limit. Pack up to 100 identifiers into one request to use fewer requests. See [Rate Limits](#rate-limits).

#### ERR_INVALID_PARAMS

**HTTP 400.** A parameter is malformed or over a limit. The `message` names the parameter. Common causes:

- More than 100 identifiers in `ids` (or in `identifiers` on `POST /products/batch`). Split the request.
- A price-history window longer than 366 days, or a `start`/`end` that is not `YYYY-MM-DD`.
- A `schedule` other than `hourly`, `daily` or `weekly`.
- A webhook without a `url` or `events`, an unknown event type, or more than 5 webhooks on the account.

No credits are charged.

#### ERR_IDENTIFIER_REQUIRED

**HTTP 400.** No identifiers were found. Identifiers go in the `ids` query parameter, comma-separated, whatever their type: `?ids=611247373064,B07GV2S1GS`. Parameters named `barcode=`, `upc=`, `asin=` or `url=` are not read. `GET /products/reviews` takes a single `id`. URL-encode product URLs and names.

#### ERR_PRODUCT_NOT_FOUND

**HTTP 404.** None of the identifiers matched a product. The `message` says what was tried: a barcode whose check digit fails (usually a missing or extra digit), a barcode that is not in the catalog yet, or other identifiers to try (ASIN, model number, product URL). When some identifiers match and some don't, you get a 200 with the matches only; use each product's `match.identifier` to see which ones came back. Not-found costs nothing.

#### ERR_ENDPOINT_NOT_FOUND

**HTTP 404.** The batch job (`GET /batch/{batchId}`) or webhook (`/webhooks/{id}`) does not exist or belongs to another account. Batch ids come from the `batch.id` of an asynchronous `POST /products/batch`; webhook ids from `GET /webhooks`.

#### ERR_METHOD_NOT_ALLOWED

**HTTP 405.** The endpoint exists but is not available to this caller. The playground's Live Sandbox only serves the sample products and endpoints it lists; use your own key for everything else.

#### ERR_INTERNAL

**HTTP 500.** An unexpected failure on our side. Any credits recorded for the request are reversed. Retry with exponential backoff; if it keeps happening, email support@shopsavvy.com with the `request_id`.

### Rate Limits

Each account can make **1,000 requests per rolling hour**, counted across all of its API keys. Rate limits are separate from credits: a request that costs 0 credits still counts as one request. To fetch many products without using up requests, pass up to 100 comma-separated identifiers in one call or use `POST /products/batch`.

Every authenticated response includes these headers:

| Header | Description |
|--------|-------------|
| `X-RateLimit-Limit` | Requests allowed per rolling hour. |
| `X-RateLimit-Remaining` | Requests left after this one. |
| `X-RateLimit-Reset` | Seconds until your oldest request in the window ages out and frees a slot. |

The same remaining count is in `meta.rate_limit_remaining` on every response, error responses included:

```json
{
  "meta": {
    "credits_used": 2,
    "credits_remaining": 998,
    "rate_limit_remaining": 958
  }
}
```

When you run out, the API answers **HTTP 429** with error code `ERR_RATE_LIMIT` and a `Retry-After` header (in seconds). Wait that long before retrying. Requests rejected with 429 don't count against your limit, so retrying won't extend the wait. If you need a higher limit, contact business@shopsavvy.com.

### Versioning & Deprecation

The API is versioned in the path: every endpoint lives under `https://api.shopsavvy.com/v1`. The current and only version is **v1**.

**What can change within v1 without notice** (write your client to tolerate these):

- New endpoints, new optional parameters, and new fields on response objects. Ignore fields you don't recognize.
- New values in open-ended fields, such as a new `condition_grade`, a new webhook event type you have not subscribed to, or a new `match.by` value.
- More specific error `message` and `action` text. Error `code` values do not change.

**What is announced first:** anything that could break a working integration, such as removing or renaming a field or endpoint, changing a field's type, or tightening a request limit. These are posted in the [changelog](https://shopsavvy.com/data/changelog) (also available as an [RSS feed](https://shopsavvy.com/data/changelog.xml)) before they take effect, and marked deprecated in these docs while the old behavior still works. A change that cannot be made compatibly ships under a new version path, with v1 kept running alongside it.

| Stage | What it means |
|-------|---------------|
| Current | Documented and recommended. |
| Deprecated | Still works and still supported, marked in these docs and the changelog with its replacement. Move to the replacement. |
| Removed | Answers with an error. Only after a deprecation period announced in the changelog. |

#### Legacy paths

Older SDK versions call these paths. They are supported and behave exactly like their replacements; use the replacements in new code.

| Legacy path | Use instead |
|-------------|-------------|
| `GET /v1/products/details` | `GET /v1/products` |
| `GET /v1/products/history` | `GET /v1/products/offers/history` |
| `POST /v1/products/schedule` | `PUT /v1/products/scheduled` |
| `DELETE /v1/products/schedule` | `DELETE /v1/products/scheduled` |

The price-history parameters `start_date` and `end_date` are likewise accepted as aliases for `start` and `end`.

### OpenAPI Specification

The full API description is published as OpenAPI 3.0 at:

```
https://api.shopsavvy.com/v1/openapi.json
```

It needs no API key. It lists every endpoint with its parameters, response schemas, error responses and credit cost (in each operation's `x-credit-cost`), so you can:

- Import it into Postman or Insomnia: **Import > Link** and paste the URL.
- Or download the ready-made [Postman collection](https://shopsavvy.com/templates/data-api-postman-collection), with one request per endpoint and your key as a collection variable.
- Generate a client: `npx @openapitools/openapi-generator-cli generate -i https://api.shopsavvy.com/v1/openapi.json -g python -o shopsavvy-client` (or use one of the [official SDKs](#sdks--libraries)).
- Point an agent or tool at it. It is also listed in [`/.well-known/api-catalog`](https://shopsavvy.com/.well-known/api-catalog) and [`/apis.json`](https://shopsavvy.com/apis.json).

---

## Quick Reference: All Endpoints

| Method | Endpoint | Description | Cost |
|--------|----------|-------------|------|
| `GET` | `/products?ids={identifiers}` | Get product details | 1 credit/product found |
| `GET` | `/products?ids={identifiers}&format=csv` | Get product details in CSV | 1 credit/product found |
| `GET` | `/products/search?q={query}` | Search products by keyword | 1 credit/product returned |
| `GET` | `/products/offers?ids={identifiers}` | Get offers from all retailers | 3 credits/product |
| `GET` | `/products/offers?ids={identifiers}&retailer={domain}` | Get offers from single retailer | 2 credits/product |
| `GET` | `/products/offers?ids={identifiers}&format=csv` | Get offers in CSV format | 3 or 2 credits/product |
| `GET` | `/products/offers/history?ids={identifiers}&start={date}&end={date}` | Get price history | Offer cost per product + 1 credit/day per request (0 when no offers found) |
| `GET` | `/products/reviews?id={identifier}` | Get TLDR review for a product | 1 credit (0 if no review) |
| `POST` | `/products/batch` | Batch product lookup (sync ≤20, async >20) | 1 credit/product found |
| `GET` | `/batch/{batchId}` | Poll an async batch job for results | 0 credits |
| `PUT` | `/products/scheduled?ids={identifiers}&schedule={interval}` | Enable scheduled monitoring | 1 credit/product |
| `PUT` | `/products/scheduled?ids={identifiers}&schedule={interval}` | Update monitoring schedule (same call as scheduling; updates in place) | 1 credit/product |
| `DELETE` | `/products/scheduled?ids={identifiers}` | Disable scheduled monitoring | 0 credits |
| `GET` | `/products/scheduled` | View all scheduled products | 0 credits |
| `GET` | `/deals?sort={sort}&limit={n}` | Browse current deals | 1 credit/10 deals |
| `GET` | `/usage` | Get usage statistics | 0 credits |
| `POST` | `/webhooks` | Register a webhook | 0 credits |
| `GET` | `/webhooks` | List your webhooks | 0 credits |
| `PUT` | `/webhooks/{id}` | Update a webhook (url, events, is_active) | 0 credits |
| `POST` | `/webhooks/{id}/test` | Send a test event to a webhook | 0 credits |
| `DELETE` | `/webhooks/{id}` | Delete a webhook | 0 credits |

**Base URL:** `https://api.shopsavvy.com/v1`

**Authentication:** `Authorization: Bearer ss_live_your_api_key_here`

**Supported Identifiers:** UPC, EAN, ISBN, GTIN, Amazon ASIN, Model Number, Product Name, URL at any retailer, ShopSavvy Product ID

**Schedule Intervals:** `"hourly"`, `"daily"`, `"weekly"`

**Response Formats:** JSON (default), CSV (add `&format=csv`)
