Home / Blog / Amazon Buy Box Price Monitoring with Datadog Custom Metrics

Amazon Buy Box Price Monitoring with Datadog Custom Metrics

Push Amazon Buy Box price, availability and offer-count metrics from the SellerMagnet API to Datadog as custom metrics via the v2 /series intake. sellermagnet.py / retry.py need zero changes from the Python quickstart. The real trap: Datadog's v2 payload wants an INTEGER metric type and a timestamp inside a strict +10min/-1h window, and a single bad timestamp in a batch can fail the whole POST, taking every other tracked ASIN's metrics down with it.

November 20, 2026
6 min read
SellerMagnet Team
Share & Bookmark
Terminal showing a Python price-watch script pushing Amazon Buy Box metrics to Datadog's v2 series API

To monitor an Amazon Buy Box price in Datadog, run a small Python script on a schedule that calls the SellerMagnet API, builds a Datadog v2 metrics payload, and POSTs it to https://api.datadoghq.com/api/v2/series with a DD-API-KEY header. The SellerMagnet client code is the unmodified Python quickstart's sellermagnet.py and retry.py. The part worth getting right on purpose: Datadog's v2 schema wants an INTEGER metric type, a strict timestamp window, and validates the whole request body as one unit, not point by point.

Key Takeaways

  • Datadog's v2 /series payload needs type as an INTEGER (3 = gauge); the older v1 endpoint takes the string "gauge" instead, so copying a v1 sample into a v2 body fails validation at once.
  • Auth is the DD-API-KEY header, never an Authorization: Bearer header and never a query parameter - verified against Datadog's own submit-metrics docs page.
  • A point's timestamp must sit inside +10 minutes / -1 hour of now or Datadog rejects it; this script checks every point against that window itself right before the push, dropping only the stale ones instead of risking the whole batch.
  • The v2 intake validates the ENTIRE request body as one unit, so this script builds one Datadog payload per run covering every ASIN and sends exactly one POST, never one POST per ASIN.
  • Datadog's own docs say metric submission is NOT rate limited; the 429 this pipeline actually has to retry on is SellerMagnet's free-tier concurrency cap, not Datadog's.

Why build one Datadog payload for the whole batch instead of one call per ASIN?

Datadog's v2 /series intake accepts or rejects the request body as a single unit - there is no documented per-point partial success. Sending one POST per ASIN would only add N chances for a transient network failure to leave half the watch list updated and half stale; one POST carrying every ASIN's series either lands as a whole or fails as a whole, which is easier to reason about and to alert on.

Install requests and set both API keys

python3 -m venv .venv
.venv/bin/pip install requests
export SELLERMAGNET_API_KEY="your-key-here"
export DD_API_KEY="your-datadog-key-here"

What does the exporter script actually push?

For every ASIN it calls /amazon-product-offers through the quickstart's retry logic, then builds up to four gauges per ASIN: the Buy Box price in cents, an availability flag, an FBA flag and the first-page offer count, each tagged asin:<ASIN> and marketplace:<marketplaceId>. A fifth gauge, the run's own last-success timestamp, is always added once per run. Every series gets type: 3 (gauge, as an int) and a single {timestamp, value} point, matching the v2 schema, not the older v1 string/pair format.

sellermagnet.py - unmodified from the Python quickstart

import os

import requests

API = "https://sellermagnet-api.com/api"


class ApiError(Exception):
    def __init__(self, status: int, message: str, retry_after: float = 0.0):
        super().__init__(f"{status}: {message}")
        self.status, self.retry_after = status, retry_after


def new_session() -> requests.Session:
    session = requests.Session()
    session.headers["X-Api-Key"] = os.environ["SELLERMAGNET_API_KEY"]
    return session


def get(session: requests.Session, endpoint: str, **params) -> dict:
    resp = session.get(f"{API}/{endpoint}", params=params, timeout=120)
    try:
        body = resp.json()
    except ValueError:                      # e.g. an HTML page from a proxy
        body = {}
    if resp.status_code == 200 and body.get("success"):
        return body["data"]
    try:
        wait = float(resp.headers.get("Retry-After", 0))
    except ValueError:
        wait = 0.0
    raise ApiError(resp.status_code, body.get("message", "request failed"), wait)

retry.py - unmodified from the Python quickstart

import random
import time

import requests

from sellermagnet import ApiError, get

RETRYABLE = {429, 500, 502, 503}


def get_with_retry(session, endpoint: str, attempts: int = 4, **params) -> dict:
    internal_errors = 0
    for attempt in range(1, attempts + 1):
        try:
            return get(session, endpoint, **params)
        except ApiError as err:
            internal_errors += err.status == 500
            if err.status not in RETRYABLE or attempt == attempts or internal_errors > 1:
                raise                      # a second 500 in a row: report it, don't loop
            backoff = min(2 ** attempt, 30) + random.uniform(0, 1)
            time.sleep(max(backoff, err.retry_after))
        except (requests.ConnectionError, requests.Timeout):
            if attempt == attempts:
                raise
            time.sleep(min(2 ** attempt, 30))

Trimmed /amazon-product-offers response (example values)

{
  "success": true,
  "data": {
    "asin": "B0CL61F39H",
    "marketplaceId": "ATVPDKIKX0DER",
    "buyBox": {"sellerId": "Amazon", "totalPrice": 444.99, "fulfillmentType": "FBA"},
    "offers": [
      {"sellerId": "Amazon", "totalPrice": 444.99, "fulfillmentType": "FBA"},
      {"sellerId": "acme-llc", "totalPrice": 459.00, "fulfillmentType": "FBM"}
    ]
  }
}

dd_pricewatch.py - builds and pushes one Datadog v2 payload per run

"""Push Amazon Buy Box price/availability metrics from the SellerMagnet API to Datadog
as custom metrics via the v2 /api/v2/series intake.

Reuses sellermagnet.py / retry.py from the Python quickstart unchanged. Example:

    session = new_session()
    watch(session, asins, marketplace_id, dd_api_key=os.environ["DD_API_KEY"])
"""
import time

import requests

from retry import get_with_retry
from sellermagnet import ApiError, new_session

GAUGE = 3                # MetricIntakeType enum: 0 unspecified, 1 count, 2 rate, 3 gauge (v2 payloads
                          # use this INT, never the v1 string "gauge" -- a v1 code sample pasted into
                          # a v2 body is rejected by the intake's own schema validation)
MAX_PAST_S = 3600         # Datadog rejects a point older than 1h
MAX_FUTURE_S = 600        # or more than 10 min in the future


def series_url(site: str) -> str:
    return f"https://api.{site}/api/v2/series"


def _series(metric: str, ts: float, value: float, tags: list[str]) -> dict:
    return {
        "metric": metric,
        "type": GAUGE,
        "points": [{"timestamp": int(ts), "value": float(value)}],
        "tags": tags,
    }


def _in_window(ts: float, now: float) -> bool:
    return (now - ts) <= MAX_PAST_S and (ts - now) <= MAX_FUTURE_S


def watch(session, asins: list[str], marketplace_id: str, dd_api_key: str,
          dd_site: str = "datadoghq.com", clock=time.time) -> dict:
    """Fetch every ASIN's offers, build ONE Datadog series payload for the whole batch and push it
    in a SINGLE POST. Datadog's v2 /series intake accepts or rejects the whole request body, not
    one point at a time -- unlike a Prometheus Pushgateway's per-job replace, there is no partial
    success here. A point whose timestamp has drifted outside Datadog's own +10min/-1h window (a
    real risk after several SellerMagnet retry backoffs inside one run) would sink the WHOLE batch,
    so every point is checked against that window right before the push and dropped-and-logged
    instead, never sent and never allowed to fail the other ASINs' metrics.
    """
    if not dd_api_key:
        raise ValueError("DD_API_KEY is not set; refusing to build a payload with no key to send it")

    series: list[dict] = []
    for asin in asins:
        ts = clock()
        tags = [f"asin:{asin}", f"marketplace:{marketplace_id}"]
        try:
            data = get_with_retry(session, "amazon-product-offers", asin=asin, marketplaceId=marketplace_id)
        except ApiError as err:
            if err.status in (401, 403):
                raise                      # bad key or no credits: stop before pushing anything built so far
            series.append(_series("amazon.offers.available", ts, 0, tags))
            continue

        box = data.get("buyBox") or {}
        price = box.get("totalPrice")
        if price is not None:
            series.append(_series("amazon.buybox.price_cents", ts, round(float(price) * 100), tags))
            series.append(_series("amazon.buybox.is_fba", ts, 1 if box.get("fulfillmentType") == "FBA" else 0, tags))
        series.append(_series("amazon.offers.available", ts, 1 if box else 0, tags))
        series.append(_series("amazon.offers.count", ts, len(data.get("offers") or []), tags))

    now = clock()
    kept, skipped = [], []
    for s in series:
        if _in_window(s["points"][0]["timestamp"], now):
            kept.append(s)
        else:
            skipped.append(s["metric"])

    kept.append(_series("amazon.pricewatch.last_run_unixtime", now, now, [f"marketplace:{marketplace_id}"]))

    resp = requests.post(
        series_url(dd_site),
        json={"series": kept},
        headers={"DD-API-KEY": dd_api_key, "Content-Type": "application/json"},
        timeout=30,
    )
    if resp.status_code not in (200, 202):
        try:
            body = resp.json()
        except ValueError:
            body = {}
        raise ApiError(resp.status_code, str(body.get("errors") or "datadog metrics submit failed"))
    return {"pushed": len(kept), "skipped": skipped}
Flow diagram from the price-watch script through the SellerMagnet API to one Datadog v2 series POST
Every ASIN's metrics are gathered first; Datadog sees exactly one POST per run, not one per ASIN.

Which SellerMagnet errors should stop the run versus just one ASIN?

A 401 or 403 means the key or the credit balance is the problem, not any one ASIN, so the whole run raises before anything is pushed to Datadog at all. Every other error (a billed 404, or 502/503 exhausted after the retry cap) marks only that ASIN unavailable and the batch carries on, the same convention as every other price-watch post in this series.

SellerMagnet API status codes, billing and this script's reaction.
StatusMeaningBilledReaction
200SuccessYesUse data
401 / 403Key or creditsNoStop the whole run before any Datadog push
404ASIN not on this marketplaceYesASIN marked unavailable, batch continues
429Concurrency capNoWait Retry-After, retried
500Internal errorNo, refundedRetry once
502 / 503Upstream / breakerYesWait, then retry, capped at 4, then ASIN marked unavailable

v1 versus v2: why a copied Datadog code sample can break silently

Datadog still documents both a v1 and a v2 metrics endpoint side by side, and they do not share a request shape. The v1 endpoint takes type as the string "gauge" and points as [timestamp, value] pairs; the current v2 endpoint this script uses takes type as an integer (0 unspecified, 1 count, 2 rate, 3 gauge) and points as {timestamp, value} objects. Pasting a v1 sample's body into a v2 POST fails the schema, and the error message names a field, not "you used the wrong API version" - worth checking first if a v2 POST that looks right keeps failing.

Table comparing the Datadog v1 and v2 metrics series request shape
v1 and v2 use different types for the same two fields; mixing a sample from one into the other's body fails validation.

One stale timestamp can sink the whole batch

Datadog rejects a point more than 10 minutes in the future or more than 1 hour in the past, and the v2 endpoint validates the whole request body as one unit, with no documented per-point partial success. A long SellerMagnet retry backoff inside one run can legitimately push one ASIN's captured timestamp close to that edge by the time the batch finally POSTs - check every point against the window yourself before building the request, and drop only the stale ones, rather than risk every other ASIN's fresh metrics on one slow retry.

What does the Datadog dashboard side look like?

A timeseries widget on avg:amazon.buybox.price_cents{asin:B0CL61F39H} / 100 plots the dollar price directly from the pushed gauge. A monitor comparing the current value against itself one hour ago (Datadog's own anomaly or change monitor types) needs no extra storage in the script at all - Datadog already has the history once the points are in.

Real output from the tested harness (fakehttp.py faking requests.Session.get and requests.post; no real Datadog or SellerMagnet calls)

PASS 1 happy path: 1 Datadog POST for the whole run
PASS 1 happy path: price_cents = 44499 (float cents rounded)
PASS 1 happy path: series type is the INT 3 (v2 gauge), never the v1 string 'gauge'
PASS 1 happy path: available=1
PASS 1 happy path: is_fba=1
PASS 1 happy path: offers.count=3
PASS 1 happy path: DD-API-KEY header sent, not Authorization
PASS 1 happy path: tags carry asin and marketplace
PASS 5 no buybox: available=0
PASS 5 no buybox: no price_cents series emitted at all (not a 0 value)
PASS 6 fbm buybox: is_fba=0
PASS 7 zero price: price_cents series present with value 0 (not skipped)
PASS 7 zero price: available=1 (a real $0 offer is not 'no offer')
PASS 8 404: single Datadog POST for the 2-ASIN batch
PASS 8 404: gone ASIN marked unavailable
PASS 8 404: sibling ASIN still fully recorded
PASS 9 429-then-ok: 2 SellerMagnet attempts
PASS 9 429-then-ok: final price recorded
PASS 10 500-then-ok: 2 attempts, final price recorded
PASS 11 502 exhausted: B0DOWN capped at 4 attempts
PASS 11 502 exhausted: B0DOWN marked unavailable, B0OK2 still recorded
PASS 12 401 aborts: raised ApiError(401)
PASS 12 401 aborts: zero Datadog POSTs made
PASS 13 empty DD key: raised ValueError before any call
PASS 14 datadog 403: raised ApiError(403) with the real Datadog message
PASS 15 datadog 400 non-json body: raised ApiError(400), .json() ValueError handled
PASS 16 stale timestamp: B0STALE's points dropped before the push, not sent to Datadog
PASS 16 stale timestamp: B0FRESH's metrics still pushed in the SAME single POST
PASS 16 stale timestamp: still exactly 1 Datadog POST for the whole batch
PASS 17 empty batch: last_run_unixtime gauge still pushed
PASS 17 empty batch: still exactly 1 Datadog POST (never zero POSTs for a legit empty run)
PASS 18 eu site: posts to api.datadoghq.eu, not api.datadoghq.com
PASS 19 5-asin batch: exactly 1 Datadog POST, never 1-per-asin
PASS 19 5-asin batch: all 5 ASINs' available series present in that one POST
34 passed, 0 failed

A real $0.00 Buy Box price is deliberately kept visible rather than hidden: amazon.offers.available is set to 1 and amazon.buybox.price_cents is sent as 0, so a dashboard viewer sees a genuine zero rather than a gap that looks identical to "no data for this ASIN". Only a response with no featured offer at all sets availability to 0 and skips the price series entirely.

Frequently Asked Questions

Why DD-API-KEY instead of an Authorization header?

Datadog's metrics intake authenticates with a DD-API-KEY header, not a bearer token. Sending an Authorization: Bearer header instead gets a 403, which looks identical to a genuinely wrong key unless you already know which header name Datadog expects.

Why does the script send one Datadog POST for the whole batch instead of one per ASIN?

The v2 /series intake accepts or rejects the entire request body as one unit, so there is nothing to gain from splitting it, and a lot to lose: N separate POSTs is N chances to hit a transient network error and end up with half the watch list updated and half stale.

What happens if one ASIN's timestamp is outside Datadog's +10min/-1h window?

Nothing fails silently and nothing fails loudly for the wrong series: this script checks every point's timestamp against that window itself, right before building the request, and drops only the stale points. Sending a request with even one bad timestamp risks a 400 on the whole payload, taking every other ASIN's fresh metrics down with it.

Is a real $0.00 Buy Box price sent as a missing value?

No. amazon.offers.available is set to 1 and amazon.buybox.price_cents is sent as 0, so a Datadog dashboard shows a genuine zero. Only a response with no buyBox at all (no featured offer) skips the price series and sets availability to 0.

Does Datadog rate-limit metric submissions like it rate-limits other APIs?

No. Datadog's own rate-limit documentation says explicitly that metric/data point submission is not rate limited. The 429 this script actually has to handle is SellerMagnet's, on the /amazon-product-offers calls, not Datadog's.

Bottom line: build one Datadog v2 payload per run covering every tracked ASIN, send it as a single POST with the DD-API-KEY header and type: 3 for every gauge, and check each point's timestamp against Datadog's own +10min/-1h window before it is ever sent. The retry and error-handling pattern underneath is identical to the Python quickstart and the Discord price-drop alert posts; the rate limits and error handling guide covers the concurrency cap this script's retry policy respects. Every endpoint is on the API documentation page, and a free account includes 150 credits to try it.

Related Articles

Continue exploring topics related to this article.

Terminal showing an Apache Airflow DAG checking an Amazon Buy Box price via the SellerMagnet API
Python Amazon API Airflow

Amazon Price Tracking in Apache Airflow: XCom, Variables and the catchup Trap

Run a daily Amazon Buy Box price check as an Apache Airflow TaskFlow DAG. The SellerMagnet side is unchanged from the Python quickstart (sellermagnet.py/retry.py, byte-identical); the real content is Airflow-specific: the API key as a Connection instead of a bare environment variable, the price baseline in a Variable (the only state the DAG needs), XCom carrying just a small dict between tasks (never the raw response), and a catchup default that quietly flips between Airflow 2.x and Airflow 3.

Nov 20, 2026 Read
Terminal window showing the Amazon Buy Box lost alert a Python script sent as an SMS via Twilio
Amazon API Buy Box Alerts

Amazon Buy Box Lost Alert via SMS: Poll Offers, Confirm, Then Text Yourself with Twilio

Get an Amazon Buy Box lost alert as a text message: poll the live offer listing for each ASIN, compare the featured offer's sellerId with yours, confirm the change on a second check, then send one SMS per run with Twilio's Messages API. Covers the one thing a webhook alert does not have to: Twilio's 2xx answer confirms the message was queued, not that it was delivered.

Nov 19, 2026 Read
Terminal showing a Python price-watch script pushing Amazon Buy Box metrics to a Prometheus Pushgateway for Grafana
Python Amazon API Monitoring

Amazon Buy Box Price Monitoring in Grafana via Prometheus Pushgateway

Push Amazon Buy Box price, availability and offer-count metrics from the SellerMagnet API to a Prometheus Pushgateway, then graph and alert on them in Grafana. sellermagnet.py / retry.py need zero changes from the Python quickstart. The real trap: using push_to_gateway (PUT, a full replace) instead of pushadd_to_gateway (POST, a merge) is what makes a dropped ASIN disappear from the dashboard instead of freezing there forever.

Nov 19, 2026 Read
Back to Blog

Ready to Extract Amazon Data at Scale?

Start building with SellerMagnet API today. Real-time product data, competitive pricing, and review analytics at your fingertips.

150 free API credits • No credit card required • Cancel anytime