Home / Blog / Scheduling Amazon Product API Pulls with an Apache Airflow DAG

Scheduling Amazon Product API Pulls with an Apache Airflow DAG

Wrap the Python quickstart's sellermagnet.py and retry.py, unchanged, in an Airflow DAG that checks Amazon Buy Box prices on a schedule. The real decision: keep Airflow's own task retries and the client's already-capped 429/500/502/503 retries from doubling up, use AirflowFailException to stop a run on a bad key without wasting an Airflow-level retry on it, and pass each task's rows to the next one through XCom.

December 01, 2026
7 min read
SellerMagnet Team
Share & Bookmark
Blueprint of an Airflow DAG with three PythonOperator tasks calling the SellerMagnet product lookup API and passing rows through XCom

To schedule Amazon product API pulls with Apache Airflow, wrap the Python quickstart's sellermagnet.py and retry.py - unchanged - in a DAG of PythonOperator tasks, and pass each task's results to the next one through XCom. The part that actually needs a decision is retries: retry.py's get_with_retry already retries a 429/500/502/503 response up to 4 times with backoff before a task callable ever returns, so Airflow's own retries must not retry the same failure again on top of that - every extra 502/503 attempt is a billed call. This DAG keeps the two apart with AirflowFailException for the one failure worth stopping a run for outright: a bad key.

Key Takeaways

  • sellermagnet.py and retry.py are reused byte-identical from the Python quickstart; the DAG only adds tasks.py (business logic) and price_watch_dag.py (Airflow wiring).
  • get_with_retry already retries 429/500/502/503 up to 4 attempts with backoff before a task returns; Airflow's default_args["retries"] must cover a different failure class (worker/XCom/process failures) or it doubles an already-capped, partly billed retry budget.
  • A 401 (bad/expired key or zero credits) fails every remaining row the same way, so fetch_prices raises AuthFailure on the first one and the task wrapper turns it into AirflowFailException - stopping the task instance with no further Airflow retry at all.
  • fetch_prices' return value is auto-pushed as XCom; check_price_drops and build_report both read it back with ti.xcom_pull(task_ids="fetch_prices"), the standard PythonOperator pattern for passing data between tasks.
  • The watchlist is de-duplicated and ASIN-format-checked before any call: a repeated (asin, marketplaceId) pair would otherwise be billed twice, and /amazon-product-lookup bills a malformed ASIN too since it never validates the format itself.

Why can't Airflow's own retries just handle everything?

Because get_with_retry in retry.py already owns a capped retry policy for the failures the SellerMagnet API can hand back: it retries 429 (per-key concurrency cap, free, honours Retry-After), a 500 without Retry-After (refunded, retried once), and 502/503 (billed, retried up to the 4-attempt cap) - then raises the ApiError back to the caller once that budget is spent. If an Airflow task's own retries also retried that same ApiError, the task would run the whole 4-attempt, partly-billed client retry cycle again on the next Airflow attempt, and again on the one after that. fetch_prices in tasks.py avoids the question for most rows by never raising in the first place - a row's exhausted retry is absorbed into that row's error field, so the task still succeeds and nothing retries it at any layer.

Install the one dependency the quickstart's client needs; Airflow itself is assumed to already be running.

pip install requests

sellermagnet.py - unchanged from the Python quickstart (new_session, get, lookup)

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)


def lookup(session: requests.Session, asin: str, marketplace_id: str) -> dict:
    p = get(session, "amazon-product-lookup", asin=asin, marketplaceId=marketplace_id)["productInfo"]
    price = p["buyBoxInfo"].get("price")
    return {
        "asin": p["asin"],
        "title": p["title"],
        "price": price if isinstance(price, (int, float)) else None,   # "N/A" = no featured offer
        "currency": p["buyBoxInfo"].get("currencyCode"),
        "rank": ((p.get("bestsellerRanks") or {}).get("main_category") or {}).get("rank") or None,
        "url": p["link"],
    }


if __name__ == "__main__":
    print(lookup(new_session(), "B0CL61F39H", "ATVPDKIKX0DER"))

retry.py - unchanged from the Python quickstart: retries only 429/500(once)/502/503

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))
SellerMagnet API status codes, billing, and what this DAG does with each.
StatusMeaningBilledThis DAG's reaction
200successYesuse the row
400 (gate)bad parameter, e.g. an unsupported marketplaceIdNoreported as a row error
401 / 403bad/expired key, or zero creditsNoAuthFailure -> AirflowFailException, run stops
404ASIN/seller not on this marketplaceYesreported as a row error
429per-key concurrency capNoretried, honours Retry-After
500 (no Retry-After)internal errorNo, refundedretried once by the client
502upstream scrape errorYesretried, capped at 4 attempts
503per-marketplace circuit breakerYesretried, capped at 4 attempts

What does tasks.py actually do with the watchlist?

fetch_prices first de-dupes the watchlist by (asin, marketplaceId) - a repeated pair would otherwise be billed twice for the same lookup - then drops anything that isn't a 10-character ASIN before making a call at all, because /amazon-product-lookup does not validate the ASIN format itself and would bill a malformed one like any other request. For everything left, it calls get_with_retry directly (not lookup(), which calls the unretried get()) and re-does lookup()'s own parsing so the Buy Box price - or the string "N/A" when there's no featured offer - comes back as a number or None, never a 0 that could look like a price drop. A 401 is the one exception it lets escape, as AuthFailure, because the remaining rows would all fail the identical way.

tasks.py - the three PythonOperator callables, no Airflow import, tested standalone

"""Task callables for the Amazon price-watch Airflow DAG.

No Airflow import here on purpose: each function takes a duck-typed `ti`
(TaskInstance) exposing only the real Airflow interface it needs
(`xcom_pull(task_ids=...)`; a return value is auto-pushed as XCom by the
PythonOperator that calls it), so the business logic is testable without
Airflow installed and stays reusable if the DAG is ever rebuilt on another
scheduler.
"""
import re

from retry import get_with_retry
from sellermagnet import ApiError, new_session

ASIN_RE = re.compile(r"^[A-Z0-9]{10}$")


class AuthFailure(Exception):
    """A 401 (bad/expired key, or zero credits): stop the run, don't spend the rest of the watchlist."""


def fetch_prices(ti, watchlist):
    """Task 1: look up every (asin, marketplaceId) pair once and push the rows for task 2 via XCom.

    De-dupes the watchlist first (a repeated pair would otherwise pay for the same lookup twice) and
    filters out anything that isn't a 10-char ASIN before calling: /amazon-product-lookup does not
    validate the ASIN format itself, so a malformed one would still be billed like a real request.
    """
    seen = set()
    deduped = []
    for row in watchlist:
        key = (row["asin"], row["marketplaceId"])
        if key in seen:
            continue
        seen.add(key)
        deduped.append(row)

    session = new_session()
    rows = []
    for row in deduped:
        asin, marketplace_id = row["asin"], row["marketplaceId"]
        if not ASIN_RE.match(asin):
            rows.append({"asin": asin, "marketplaceId": marketplace_id, "price": None, "error": "malformed_asin"})
            continue
        try:
            data = get_with_retry(session, "amazon-product-lookup", asin=asin, marketplaceId=marketplace_id)
        except ApiError as err:
            if err.status == 401:
                # Free, but every remaining lookup would fail the identical way for no reason: stop the
                # task now (the DAG turns this into AirflowFailException) instead of 1-by-1 repeats.
                raise AuthFailure(f"{asin}/{marketplace_id}: {err}") from err
            # Any other ApiError (404 billed, a free 400 gate, or 500/502/503 whose 4 client-side
            # attempts are already exhausted) is reported per row - one bad ASIN must not lose the
            # rest of the watchlist's already-paid-for lookups.
            rows.append({"asin": asin, "marketplaceId": marketplace_id, "price": None, "error": str(err)})
            continue
        info = data["productInfo"]
        price = info["buyBoxInfo"].get("price")
        rows.append({
            "asin": info["asin"],
            "marketplaceId": marketplace_id,
            # "N/A" (no featured offer) must not be read as a price of 0 or as a price drop.
            "price": price if isinstance(price, (int, float)) else None,
            "error": None,
        })
    return rows


def check_price_drops(ti, threshold):
    """Task 2: pull task 1's rows via XCom and flag the ones priced below `threshold`."""
    rows = ti.xcom_pull(task_ids="fetch_prices")
    return [row for row in rows if row["error"] is None and row["price"] is not None and row["price"] < threshold]


def build_report(ti):
    """Task 3: pull both earlier XComs and build the summary a paging/alerting step would read."""
    rows = ti.xcom_pull(task_ids="fetch_prices")
    alerts = ti.xcom_pull(task_ids="check_price_drops")
    errors = [row for row in rows if row["error"] is not None]
    return {
        "checked": len(rows),
        "errors": [{"asin": row["asin"], "marketplaceId": row["marketplaceId"], "error": row["error"]}
                   for row in errors],
        "alerts": [{"asin": row["asin"], "marketplaceId": row["marketplaceId"], "price": row["price"]}
                   for row in alerts],
    }
Sequence diagram of the three Airflow tasks passing data forward through XCom, with the client's own retries happening inside fetch_prices before it ever returns
Each arrow after fetch_prices is an XCom pull by task_ids; the client's own retries all happen before fetch_prices returns anything.

What does the DAG file itself look like?

price_watch_dag.py is the only file that imports airflow. Its _fetch_prices wrapper is the split point: it catches AuthFailure and re-raises it as AirflowFailException, which marks the task instance FAILED immediately with no further Airflow-level retry - appropriate here because a second attempt against the same bad key cannot succeed. Everything else runs through default_args["retries"], reserved for failures get_with_retry never sees in the first place: the worker losing its network before a request leaves, an XCom backend write failing, or the process dying outright. A fresh worker genuinely can help with those, which is exactly why Airflow - not the client - owns retries for that class.

How is this different from the daily Buy Box tracker DAG?

If you've seen the Airflow Buy Box tracker post in this series, the SellerMagnet side is the same unchanged sellermagnet.py/retry.py - but the two DAGs solve different problems. That one tracks a single ASIN daily with the @task TaskFlow API, an Airflow Connection for the key, and a Variable for the price baseline, and lets Airflow's own retries re-run the whole task on a 401/403. This one runs a whole watchlist on the classic PythonOperator pattern, de-dupes and format-checks the batch before any call, and stops a run outright on a 401 with AirflowFailException instead of letting Airflow retry a failure that cannot succeed twice.

price_watch_dag.py - the DAG definition, default_args, and the AirflowFailException split

"""price_watch_dag.py - hourly Amazon price-drop watch, Airflow 2.x / PythonOperator.

Airflow's own task retries and the API client's own retries (get_with_retry in
retry.py, used by tasks.py) solve two different problems and must stay
separate: the client already retries a 429/500/502/503 response up to 4 times
with jittered backoff BEFORE a task callable ever returns. If Airflow's own
`retries` ALSO retried a failure that had already exhausted that budget, every
Airflow-level retry would spend another full client-side retry cycle underneath
it - the same double-retry get_with_retry.py is written to cap, just reintroduced
one layer up, and each of those extra attempts is a billed 502/503 call.

The split this DAG uses:
  - AirflowFailException marks the task instance FAILED immediately, with NO
    further Airflow-level retry: for AuthFailure (401, bad/expired key -
    retrying buys nothing, the next attempt fails the identical way) and for
    any row whose client-side retries are already exhausted inside
    fetch_prices (handled there; that path does not raise and the task still
    succeeds, see tasks.py). AuthFailure is the one case worth stopping the
    whole DAG run for.
  - default_args["retries"] (a plain exception, e.g. AirflowException) covers
    only what the client-side retry budget never sees: the worker losing its
    network before a request leaves, an XCom backend write failing, the
    Python process itself dying. A second attempt on a fresh worker can
    genuinely help there, which is why Airflow - not the client - owns retries
    for that class of failure.
"""
from datetime import datetime, timedelta

from airflow import DAG
from airflow.exceptions import AirflowFailException
from airflow.operators.python import PythonOperator

from tasks import AuthFailure, build_report, check_price_drops, fetch_prices

# Illustrative ASINs/marketplace. B0CL61F39H is listed twice on purpose: fetch_prices
# de-dupes it, so it is billed once, not twice. "SHORT" is not a 10-char ASIN and is
# filtered out before any call is made.
WATCHLIST = [
    {"asin": "B0CL61F39H", "marketplaceId": "ATVPDKIKX0DER"},
    {"asin": "B0CL61F39H", "marketplaceId": "ATVPDKIKX0DER"},
    {"asin": "B08N5WRWNW", "marketplaceId": "ATVPDKIKX0DER"},
    {"asin": "SHORT", "marketplaceId": "ATVPDKIKX0DER"},
]
PRICE_DROP_THRESHOLD = 20.00

default_args = {
    "owner": "amazon-ops",
    "retries": 2,                          # worker/XCom failures only - see the module docstring
    "retry_delay": timedelta(minutes=2),
}


def _fetch_prices(**context):
    try:
        return fetch_prices(context["ti"], WATCHLIST)
    except AuthFailure as err:
        raise AirflowFailException(str(err)) from err


def _check_price_drops(**context):
    return check_price_drops(context["ti"], PRICE_DROP_THRESHOLD)


def _build_report(**context):
    return build_report(context["ti"])


with DAG(
    dag_id="amazon_price_watch",
    schedule="@hourly",
    start_date=datetime(2026, 1, 1),
    catchup=False,
    default_args=default_args,
    tags=["amazon-api"],
) as dag:
    fetch = PythonOperator(task_id="fetch_prices", python_callable=_fetch_prices)
    check = PythonOperator(task_id="check_price_drops", python_callable=_check_price_drops)
    report = PythonOperator(task_id="build_report", python_callable=_build_report)

    # XCom carries each task's return value forward: fetch_prices' row list -> check_price_drops'
    # alert list -> build_report's summary, each pulled by task_ids in tasks.py.
    fetch >> check >> report
Table splitting which failures the SellerMagnet client already retried from the ones Airflow's own retries are for
Only failures the client-side retry budget never saw get an Airflow-level retry; everything else is absorbed or fails the run outright.

Trimmed /amazon-product-lookup response (example values) - the fields fetch_prices reads

{
  "success": true,
  "data": {
    "productInfo": {
      "asin": "B0CL61F39H",
      "title": "Example wireless headphones",
      "buyBoxInfo": {
        "price": 42.0,
        "currencyCode": "USD"
      },
      "bestsellerRanks": {
        "main_category": {"rank": 12345}
      },
      "link": "https://www.amazon.com/dp/B0CL61F39H"
    }
  }
}

Real output from the tested harness (fakehttp.py faking requests.Session.get only, illustrative data)

dedupe: 3 rows not 4: PASS
dedupe: only 2 real HTTP calls: PASS
malformed ASIN filtered, no call made: PASS
good row has numeric price: PASS
price-drop threshold catches the 15.0 row only: PASS
report: checked == 3: PASS
report: 1 error (malformed): PASS
report: 1 alert: PASS
404: one call per ASIN, no retry: PASS
404: reported as error, second row still fetched: PASS
free 400 reported as error, not raised: PASS
500 retried once by the client, succeeds, 2 calls total: PASS
two 500s stop the client's own retry at attempt 2, not 4: PASS
exhausted retry reported as a row error, task does not crash: PASS
502 retried to the client's 4-attempt cap, each one billed: PASS
exhausted 502 reported, not raised: PASS
429 retried once and succeeds: PASS
backoff honours Retry-After (>=2s): PASS
timeout retried by the client, succeeds: PASS
N/A price parsed as None, not 0: PASS
a None price never triggers a price-drop alert: PASS
401 raises AuthFailure: PASS
401 stops after the first ASIN, no second lookup: PASS
non-retryable status hits the client once, reported: PASS
PASS: 24  FAIL: 0

Frequently Asked Questions

Should Airflow's own retries also retry a 502 from the SellerMagnet API?

No. get_with_retry in retry.py already retries 429/500/502/503 up to 4 times with backoff before the task callable returns. Airflow retrying the same failure again would run that whole capped cycle a second time, and every 502/503 attempt in it is billed.

Why does a 401 stop the whole DAG run instead of just failing one row?

A bad or expired key, or zero credits, fails identically for every remaining ASIN in the watchlist. fetch_prices raises AuthFailure on the first 401 it sees, and the task wrapper turns that into AirflowFailException so Airflow does not retry it either - the next attempt would fail the same way.

How do task.py's functions get tested without installing Airflow?

They take a duck-typed ti argument exposing only xcom_pull(task_ids=...), the same method Airflow's real TaskInstance offers a PythonOperator callable. A plain stub object with that one method is enough to drive and assert the business logic; the DAG file itself is the only place that imports airflow.

Where do check_price_drops and build_report get fetch_prices' results from?

Via XCom. fetch_prices returns a list, which the PythonOperator auto-pushes as that task's XCom return value; check_price_drops and build_report both call ti.xcom_pull(task_ids="fetch_prices") to read it back.

Why does the watchlist get de-duplicated before any API call?

/amazon-product-lookup bills every call it answers, duplicate pair or not. fetch_prices de-dupes the (asin, marketplaceId) list before looping, so a repeated row in the watchlist is looked up - and billed - once, not twice.

Why filter the ASIN format before calling the API instead of letting the API reject it?

/amazon-product-lookup does not validate the ASIN format at all; a malformed value is sent upstream and billed like a normal request. Checking it against a 10-character pattern first catches a guaranteed-bad call for free.

Bottom line: an Airflow DAG for Amazon product API pulls doesn't need a different client than the Python quickstart's sellermagnet.py and retry.py - the work is in not retrying the same failure at two layers, in stopping a run outright on a bad key instead of retrying it, and in passing rows between PythonOperator tasks the way Airflow already does it, through XCom. The Scheduler page covers automated/recurring calls at the account level if you'd rather not run your own Airflow instance for this; every endpoint used here is on the API documentation page, more runnable snippets are on the code examples page, the /amazon-product-lookup page covers every field this DAG reads, and a free account includes 150 credits to try it against real ASINs.

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