To load Amazon product API data into Snowflake, flatten the lookup, offers and statistics responses into one row shape keyed by (asin, marketplace_id, source, day), write that batch as NDJSON to a local file, PUT it into an internal stage with snowflake-connector-python, COPY INTO a staging table by column name, and MERGE the staging table into a typed main table. The MERGE's join key is also the dedupe-on-reload key: running the same batch twice, or a batch with an updated price for a day already stored, changes rows in place instead of duplicating them.
Key Takeaways
- PUT uploads a local file to an internal stage for free; COPY INTO and MERGE are both billed as warehouse compute, the same as any query.
- Flatten lookup, offers and statistics into ONE row shape - (asin, marketplace_id, source, day, metric_value, captured_at) - so a single staging table and a single MERGE cover all three.
- Statistics prices arrive as integer minor units (cents) except on amazon.co.jp, which has no minor unit; lookup and offers already arrive as decimal units - convert statistics once before writing a row, never mix units in the same column.
- MATCH_BY_COLUMN_NAME on COPY INTO loads NDJSON into a typed table by field name, with no $1:field SELECT transform needed, as long as the JSON keys match the table's column names.
- Two points that land on the same day (statistics can record more than one) must collapse to the last value BEFORE the MERGE runs, or a staging side that matches one target row twice raises Snowflake's 'multiple rows matched' error instead of silently picking one.
Why PUT and COPY INTO instead of inserting rows one at a time?
A Python INSERT per row means one round trip per row, and Amazon's three endpoints already cost one credit per call before a single byte reaches the warehouse. PUT stages a local file - in this case a short-lived NDJSON batch, deleted or overwritten on the next run - into an internal stage with no warehouse compute at all; COPY INTO then loads the whole file in one statement. For a job that runs on a schedule (hourly, daily) rather than needing a row queryable within milliseconds, this is both the simpler and the cheaper path; Snowflake's streaming ingestion APIs exist for that sub-second case, not for a batch pull like this one.
| Step | Cost | Why it matters here |
|---|---|---|
| PUT (file upload to an internal stage) | Free | No warehouse or compute credits for the upload itself. |
| COPY INTO (file load into a table) | Warehouse credits for the load, billed by compute time | The staging table's write path for this post; small NDJSON batches cost very little. |
| MERGE / UPDATE / DELETE (DML) | Warehouse credits for the statement, same as any query | This is what applies the dedupe-on-reload key; it never re-runs PUT or COPY. |
| SELECT (query) | Warehouse credits for the query | Reporting against amazon_snapshots. |
What row shape covers lookup, offers and statistics at once?
Lookup gives one live price per product; offers gives one live Buy Box total; statistics gives the full recorded history of four price series plus sales rank. Instead of three table shapes, flatten all three into rows of (asin, marketplace_id, source, day, metric_value, captured_at), where source names where the point came from: lookup, offers_buybox, stats_buybox, stats_fba, stats_fbm, stats_amazon, stats_rank. One staging table, one MERGE, covers every source.
schema.sql - one typed table plus its disposable staging table
CREATE TABLE IF NOT EXISTS amazon_snapshots (
asin VARCHAR NOT NULL,
marketplace_id VARCHAR NOT NULL,
source VARCHAR NOT NULL, -- lookup | offers_buybox | stats_buybox | stats_fba | stats_fbm
-- | stats_amazon | stats_rank
day DATE NOT NULL,
metric_value FLOAT NOT NULL, -- decimal currency units, or a rank for source = stats_rank
captured_at TIMESTAMP_NTZ NOT NULL
);
-- recreated by TRUNCATE before every load; never queried directly by a report
CREATE TABLE IF NOT EXISTS amazon_snapshots_staging LIKE amazon_snapshots;
get_with_retry() and ApiError are the Python quickstart's helpers, unchanged. rows_for_product calls all three endpoints for one (asin, marketplace_id) pair and treats statistics' free gate 400 - every marketplace outside the 11 history-enabled marketplaces answers it that way - as a recorded skip, not a failure that drops the lookup and offers rows it already has.
warehouse.py - flatten three endpoints into one row shape
import json
import re
from datetime import date, datetime, timezone
from retry import get_with_retry
from sellermagnet import ApiError
ASIN_RE = re.compile(r"^[A-Z0-9]{10}$")
# JPY has no minor unit (statistics returns whole yen already); every other marketplace's statistics
# series is in integer minor units (cents, pence, ...) and needs /100 to become decimal currency units,
# the same unit lookup/offers already use.
JPY_MARKETPLACE = "A1VC38T7YXB528" # amazon.co.jp
STATS_SERIES = {"stats_buybox": "buyBoxPriceHistory", "stats_fba": "lowestFBAPriceHistory",
"stats_fbm": "lowestFBMPriceHistory", "stats_amazon": "amazonAsSellerPriceHistory"}
MERGE_SQL = """MERGE INTO {main} AS T
USING {staging} AS S
ON T.asin = S.asin AND T.marketplace_id = S.marketplace_id AND T.source = S.source AND T.day = S.day
WHEN MATCHED THEN UPDATE SET metric_value = S.metric_value, captured_at = S.captured_at
WHEN NOT MATCHED THEN INSERT (asin, marketplace_id, source, day, metric_value, captured_at)
VALUES (S.asin, S.marketplace_id, S.source, S.day, S.metric_value, S.captured_at)"""
def _minor_to_decimal(minor: int, marketplace_id: str) -> float:
return float(minor) if marketplace_id == JPY_MARKETPLACE else round(minor / 100, 2)
def flatten_lookup(data: dict, asin: str, marketplace_id: str, today: date, captured_at: str) -> list[dict]:
"""One row for the live featured-offer price, or none when it reads "N/A" (no featured offer)."""
price = data["productInfo"]["buyBoxInfo"].get("price")
if not isinstance(price, (int, float)): # "N/A": not a price of 0
return []
return [{"asin": asin, "marketplace_id": marketplace_id, "source": "lookup", "day": today.isoformat(),
"metric_value": float(price), "captured_at": captured_at}]
def flatten_offers(data: dict, asin: str, marketplace_id: str, today: date, captured_at: str) -> list[dict]:
"""One row for the live Buy Box total price. buyBox.totalPrice is price+shipping as an UNROUNDED
float (can read 444.97999999999996); round it once, here, before it ever reaches a table."""
buy_box = data.get("buyBox") or {}
total = buy_box.get("totalPrice")
if not isinstance(total, (int, float)): # {} when no featured offer / buyBoxSuppressed
return []
return [{"asin": asin, "marketplace_id": marketplace_id, "source": "offers_buybox", "day": today.isoformat(),
"metric_value": round(float(total), 2), "captured_at": captured_at}]
def flatten_statistics(data: dict, asin: str, marketplace_id: str, captured_at: str) -> list[dict]:
"""Every recorded price-history point across the four series, plus sales-rank points. Points with a
negative minor-unit value are already dropped upstream; salesRankHistory keeps -1 ("no rank
recorded"), which must be filtered here."""
stats = data.get("stats") or {}
rows = []
for source, key in STATS_SERIES.items():
for day, minor in stats.get(key) or []:
rows.append({"asin": asin, "marketplace_id": marketplace_id, "source": source, "day": day[:10],
"metric_value": _minor_to_decimal(minor, marketplace_id), "captured_at": captured_at})
for ts, rank in stats.get("salesRankHistory") or []:
if rank >= 1: # -1 = no rank recorded at that time
rows.append({"asin": asin, "marketplace_id": marketplace_id, "source": "stats_rank", "day": ts[:10],
"metric_value": float(rank), "captured_at": captured_at})
return rows
def rows_for_product(session, asin: str, marketplace_id: str, now: datetime) -> tuple[list[dict], list[dict]]:
"""Pull lookup + offers + statistics for one product. Statistics answers a free gate 400 on the 12
marketplaces outside the 11 history-enabled marketplaces - that failure is recorded and skipped, never
raised, so a batch across all 23 marketplaces still stages the rows the other two endpoints did return."""
today, captured_at = now.date(), now.isoformat(timespec="seconds")
rows, failures = [], []
lookup = get_with_retry(session, "amazon-product-lookup", asin=asin, marketplaceId=marketplace_id)
rows += flatten_lookup(lookup, asin, marketplace_id, today, captured_at)
offers = get_with_retry(session, "amazon-product-offers", asin=asin, marketplaceId=marketplace_id)
rows += flatten_offers(offers, asin, marketplace_id, today, captured_at)
try:
stats = get_with_retry(session, "amazon-product-statistics", asin=asin, marketplaceId=marketplace_id)
rows += flatten_statistics(stats, asin, marketplace_id, captured_at)
except ApiError as err: # free 400 (no history here), 404, ...
failures.append({"asin": asin, "marketplace_id": marketplace_id, "endpoint": "amazon-product-statistics",
"status": err.status, "message": str(err)})
return rows, failures
def collect_batch(session, asin_marketplace_pairs: list[tuple[str, str]], now: datetime
) -> tuple[list[dict], list[dict]]:
"""One bad ASIN never loses the rest of the batch: a malformed ASIN is filtered BEFORE any call (no
endpoint here validates the ASIN format, so skipping locally saves the credit), and a
lookup/offers failure for one pair is recorded instead of raised."""
rows, failures = [], []
for asin, marketplace_id in asin_marketplace_pairs:
if not ASIN_RE.match(asin):
failures.append({"asin": asin, "marketplace_id": marketplace_id, "endpoint": "local-validation",
"status": 0, "message": "malformed ASIN, skipped before any call"})
continue
try:
got, stats_failures = rows_for_product(session, asin, marketplace_id, now)
rows += got
failures += stats_failures
except ApiError as err: # lookup or offers itself failed
failures.append({"asin": asin, "marketplace_id": marketplace_id, "endpoint": "amazon-product-lookup",
"status": err.status, "message": str(err)})
return dedupe_rows(rows), failures
def dedupe_rows(rows: list[dict]) -> list[dict]:
"""Collapse rows sharing the natural key (asin, marketplace_id, source, day) to the LAST one before
they ever reach Snowflake: several statistics points can share a date, and a MERGE whose staging side
matches the same target row twice raises 'multiple rows matched' instead of silently picking one."""
by_key = {}
for row in rows:
by_key[(row["asin"], row["marketplace_id"], row["source"], row["day"])] = row
return list(by_key.values())

How do PUT, COPY INTO and MERGE fit together in Python?
stage_and_merge truncates the staging table first, so a re-run after a crash never appends on top of a half-finished previous load, then runs the three statements in order. MATCH_BY_COLUMN_NAME='CASE_INSENSITIVE' tells COPY INTO to match each NDJSON object's keys to the staging table's column names directly - there is no $1:field positional transform to keep in sync with the Python row shape, as long as the field names agree.
warehouse.py - stage_and_merge: PUT, COPY INTO, MERGE
def stage_and_merge(cur, local_path: str, stage: str, staging_table: str, main_table: str) -> int:
"""PUT the local NDJSON file into `stage`, COPY it into the staging table by column name, then MERGE
into the typed main table. OVERWRITE=TRUE on PUT means a re-run after a crash just re-uploads the same
staged filename; TRUNCATE on the staging table before COPY means a re-run never appends on top of a
half-finished previous load.
"""
cur.execute(f"TRUNCATE TABLE {staging_table}")
cur.execute(f"PUT file://{local_path} @{stage} AUTO_COMPRESS=TRUE OVERWRITE=TRUE")
cur.execute(f"COPY INTO {staging_table} FROM @{stage} "
f"FILE_FORMAT=(TYPE=JSON) MATCH_BY_COLUMN_NAME='CASE_INSENSITIVE' "
f"ON_ERROR='ABORT_STATEMENT' PURGE=TRUE")
cur.execute(MERGE_SQL.format(main=main_table, staging=staging_table))
return cur.rowcount
Dedupe in Python before the MERGE, not after
A statistics series can record two points on the same calendar day. If both land in the staging table, the MERGE's staging side matches the same target row twice, and Snowflake raises an error instead of picking one - it never silently keeps the last. dedupe_rows() collapses the batch to one row per (asin, marketplace_id, source, day) - the same key the MERGE joins on - before the file is ever written.
How does the dedupe-on-reload key avoid duplicating a re-run?
MERGE ... USING staging ON (asin, marketplace_id, source, day) WHEN MATCHED THEN UPDATE ... WHEN NOT MATCHED THEN INSERT is the same upsert idea as ON CONFLICT DO UPDATE in your own Postgres or SQLite database (see the database guide) or a BigQuery MERGE (see the BigQuery guide), just running against Snowflake's own compute. Because the join key matches the table's own natural key, re-staging the same day's prices twice changes nothing, and a re-run with an updated price for a day already stored only updates that one row.
test_warehouse.py - the ported MERGE logic verified standalone
def test_matches_sql_semantics(self):
target = {("B0CL61F39H", US, "stats_buybox", "2026-11-18"):
{"asin": "B0CL61F39H", "marketplace_id": US, "source": "stats_buybox",
"day": "2026-11-18", "metric_value": 418.0, "captured_at": "old"}}
source = [{"asin": "B0CL61F39H", "marketplace_id": US, "source": "stats_buybox",
"day": "2026-11-18", "metric_value": 400.0, "captured_at": "new"}, # UPDATE
{"asin": "B0CL61F39H", "marketplace_id": US, "source": "stats_buybox",
"day": "2026-11-19", "metric_value": 418.0, "captured_at": "new"}] # INSERT
merged = simulate_merge(target, source)
self.assertEqual(len(merged), 2)
self.assertEqual(merged[("B0CL61F39H", US, "stats_buybox", "2026-11-18")]["metric_value"], 400.0)
self.assertEqual(merged[("B0CL61F39H", US, "stats_buybox", "2026-11-19")]["metric_value"], 418.0)
What does the example run output?
Two ASINs, one on amazon.com (full history) and one on amazon.nl (no history, no featured offer right now). The amazon.nl product contributes only its rounded offers row; its statistics call answers the free gate 400 and is reported, not raised.
main.py - pull a short batch, stage it, MERGE into Snowflake
"""main.py - pull lookup/offers/statistics for a short ASIN batch, stage it and MERGE into Snowflake.
Run after: pip install snowflake-connector-python; export SNOWFLAKE_* env vars for connect().
"""
from datetime import datetime, timezone
import snowflake.connector
from sellermagnet import new_session
from warehouse import collect_batch, stage_and_merge, write_ndjson
ASINS = [("B0CL61F39H", "ATVPDKIKX0DER"), ("B0D1XD1ZV3", "A1805IZSGTT6HS")]
session = new_session()
now = datetime.now(timezone.utc)
rows, failures = collect_batch(session, ASINS, now)
write_ndjson(rows, "/tmp/amazon_snapshots_batch.ndjson")
conn = snowflake.connector.connect(account="...", user="...", password="...", warehouse="...",
database="sm_warehouse", schema="amazon")
cur = conn.cursor()
affected = stage_and_merge(cur, "/tmp/amazon_snapshots_batch.ndjson", "@amazon_stage",
"amazon_snapshots_staging", "amazon_snapshots")
print(f"staged {len(rows)} rows from {len(ASINS)} products, {len(failures)} endpoint failures")
print(f"MERGE affected {affected} rows in sm_warehouse.amazon.amazon_snapshots")
for f in failures:
print(" {} / {} / {}: HTTP {} - {}".format(f["asin"], f["marketplace_id"], f["endpoint"],
f["status"], f["message"]))
Output (illustrative fixture data, not a live account)
staged 6 rows from 2 products, 1 endpoint failures
MERGE affected 6 rows in sm_warehouse.amazon.amazon_snapshots
B0D1XD1ZV3 / A1805IZSGTT6HS / amazon-product-statistics: HTTP 400 - 400: This endpoint is not available for the requested marketplace.

Frequently Asked Questions
Do I need Snowpipe or streaming ingestion to load Amazon data?
No. PUT and COPY INTO handle a scheduled batch fine and cost nothing extra for the upload step; streaming ingestion exists for data that needs to be queryable within seconds of arriving, which a daily or hourly pull does not need.
Does MERGE on Snowflake work like ON CONFLICT DO UPDATE?
Yes, the same upsert idea: match on a key, UPDATE when matched, INSERT when not. Running the loader twice with the same data changes nothing.
Why flatten lookup, offers and statistics into one row shape instead of three tables?
One staging table and one MERGE statement then cover every source; a source column tells them apart, and queries filter on it the same way they would filter on a table name.
What happens if two rows in the same batch share the same key?
Snowflake's MERGE raises an error when the staging side matches one target row more than once. Dedupe the batch in Python to the last value per key before writing the file.
Which Amazon marketplaces have no statistics history?
The 12 outside the 11 history-enabled domains (amazon.com, .ca, .com.mx, .com.br, .co.uk, .de, .fr, .it, .es, .in, .co.jp); they answer a free gate 400, and lookup and offers still return data on all 23.
Bottom line: flatten lookup, offers and statistics into one row shape, PUT a local NDJSON batch into a stage for free, COPY it into a staging table by column name, then MERGE with a dedupe-on-reload key so a re-run or an updated price never duplicates a row. Try the pull side on the 150 credits a free account gets after e-mail verification.