· Charlotte Will · Amazon API  · 8 min read

Building a Custom Data Warehouse for Enhanced Business Insights Using Amazon SP-API

Discover how to build a custom data warehouse using Amazon SP-API for enhanced business insights. This comprehensive guide walks you through each step, from defining your data requirements to setting up real-time analytics. Learn practical techniques to integrate and analyze data effectively, improving your e-commerce business's performance and decision-making capabilities.

Discover how to build a custom data warehouse using Amazon SP-API for enhanced business insights. This comprehensive guide walks you through each step, from defining your data requirements to setting up real-time analytics. Learn practical techniques to integrate and analyze data effectively, improving your e-commerce business's performance and decision-making capabilities.

Introduction

Amazon’s Selling Partner API hands over data in whatever form it comes, usually flat report files or order records. It does not hand over a place to put that data, so a question like “which ASINs lost the Buy Box last month” gets answered by downloading three months of files again.

That layer is the custom data warehouse.

Deciding what goes in the warehouse

Start with the question, not the endpoint. “Which listings lost the Buy Box last month” wants a daily price and Buy Box figure for every ASIN. “Which products should I reorder” wants units on hand next to sales velocity. Each question implies a grain, and two grains cannot share a table.

A fact table holds the measured numbers. Dimension tables hold what you slice by: the ASIN with its title and brand, the date with its week and month.

Keep a raw layer of the original files too. A report type can change its columns without notice, and the old file is the only copy you will have.

Designing the warehouse schema

A star schema handles it: one fact table at daily-ASIN grain, one dimension table. The (asin, date_key) primary key keeps the joins cheap and makes re-loading a day an upsert.

DDL = """
CREATE TABLE dim_asin (
    asin TEXT PRIMARY KEY,
    brand TEXT
);
CREATE TABLE fact_listing_daily (
    asin TEXT REFERENCES dim_asin (asin),
    date_key DATE NOT NULL,
    sessions INTEGER,
    revenue NUMERIC(12, 2),
    buy_box_wins INTEGER,
    PRIMARY KEY (asin, date_key)
);
CREATE TABLE etl_watermark (
    pipeline TEXT PRIMARY KEY,
    watermark DATE NOT NULL
);
"""

ON CONFLICT needs a unique constraint to hang off, so the primary key doubles as the guard that makes a retry safe. Index every column because it might be filtered on later.

Authenticating and calling SP-API

One cleanup first: Amazon announced the end of life for the Marketplace Web Service in July 2022 and stopped serving its last sections on April 1, 2024, so any code path still calling MWS has to be rewritten against SP-API.

Every call carries a Login with Amazon access token and a SigV4 signature, and your application needs a data access role saying what it may touch. Roles live in your developer profile: a reporting pipeline normally asks for Inventory and Order Tracking.

import time

import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest

HOSTS = {
    "NA": ("https://sellingpartnerapi-na.amazon.com", "us-east-1"),
    "EU": ("https://sellingpartnerapi-eu.amazon.com", "eu-west-1"),
}
DATA_ACCESS_ROLE = "Inventory and Order Tracking"


def sp_api_get(path, *, marketplace, token, credentials):
    """Call an SP-API GET endpoint with SigV4 signing."""
    host, region = HOSTS[marketplace]
    request = AWSRequest(method="GET", url=host + path, headers={
        "x-amz-access-token": token,
        "x-amz-date": time.strftime("%Y%m%dT%H%M%SZ", time.gmtime()),
    })
    SigV4Auth(credentials, "sellingpartnerapi", region).add_auth(request)
    response = requests.send(request.prepare(), timeout=60)
    if response.status_code == 429:
        time.sleep(int(response.headers.get("Retry-After", "5")))
        response = requests.send(request.prepare(), timeout=60)
    response.raise_for_status()
    return response.json()

The endpoint and signing region travel as a pair: signing a European request for us-east-1 produces a 403 that reads like a broken credential. A 429 is answered by sleeping the window Amazon names in Retry-After.

Building the incremental load

Reports are the backbone of most SP-API pipelines, and they are asynchronous. You request one, it processes in the background, and you collect it when the status flips to DONE. A loader that pulls the last 30 days nightly also works, but it spends the report quota you negotiated for. The efficient version keeps a watermark and asks only for what follows.

import csv
import gzip
import time


def fetch_report_rows(token, credentials, *, marketplace):
    """Request a report, wait for it, and return the parsed rows."""
    call = lambda p: sp_api_get(p, marketplace=marketplace, token=token,
                                 credentials=credentials)
    report_id = call("/reports/2021-06-30/reports")["reportId"]
    while True:
        status = call(f"/reports/2021-06-30/reports/{report_id}")["status"]
        if status == "DONE":
            break
        if status in ("FATAL", "CANCELLED"):
            raise RuntimeError(f"report {report_id} ended as {status}")
        time.sleep(60)
    doc = call(f"/reports/2021-06-30/documents/{status['reportDocumentId']}")
    payload = requests.get(doc["url"], timeout=120).content
    if doc.get("compressionAlgorithm") == "GZIP":
        payload = gzip.decompress(payload)
    return list(csv.DictReader(payload.decode("utf-8").splitlines(),
                                delimiter="\t"))

The document arrives as a pre-signed URL, sometimes gzip compressed, usually tab separated values with a header row. The response names the compression.

Loading on a schedule needs a runner, and How to Automate Data Analysis with Amazon SP-API covers how to set one up.

from datetime import date
from decimal import Decimal


def load_incremental(conn, rows, *, pipeline, watermark_floor):
    """Load rows past the watermark, then advance it in one transaction."""
    row = conn.execute("SELECT watermark FROM etl_watermark WHERE pipeline = %s",
                       (pipeline,)).fetchone()
    watermark = row[0] if row else watermark_floor
    fresh = [r for r in rows if date.fromisoformat(r["date"]) > watermark]
    if not fresh:
        return 0
    values = [(r["asin"], date.fromisoformat(r["date"]), int(r["sessions"]),
               Decimal(r["revenue"]), int(r["buy_box_wins"])) for r in fresh]
    latest = max(date.fromisoformat(r["date"]) for r in fresh)
    with conn.cursor() as cur:
        cur.executemany(
            "INSERT INTO fact_listing_daily (asin, date_key, sessions, revenue,"
            " buy_box_wins) VALUES (%s, %s, %s, %s, %s) ON CONFLICT (asin,"
            " date_key) DO UPDATE SET revenue = EXCLUDED.revenue", values)
        cur.execute(
            "INSERT INTO etl_watermark (pipeline, watermark) VALUES (%s, %s)"
            " ON CONFLICT (pipeline) DO UPDATE SET watermark = GREATEST("
            " etl_watermark.watermark, EXCLUDED.watermark)", (pipeline, latest))
    conn.commit()
    return len(fresh)

A watermark only moves forward inside the same transaction as the data. If the process dies mid-load, the transaction rolls back and the next run asks for the same window again. Moving the watermark first would leave a hole.

Real-time refresh works the same way. The Notifications API pushes events to an SQS queue, and Data Kiosk runs GraphQL queries whose results land in object storage.

Validating data quality before you trust it

Silently accepting bad data is the failure mode that matters here, because every downstream number inherits the error and nobody knows to look. These checks belong in the load path.

def validate_load(conn, *, pipeline):
    """Return the problems found in the most recent load."""
    problems = []
    orphans = conn.execute(
        "SELECT count(*) FROM fact_listing_daily f"
        " LEFT JOIN dim_asin d USING (asin) WHERE d.asin IS NULL"
    ).fetchone()[0]
    if orphans:
        problems.append(f"{orphans} fact rows have no dimension row")
    stale = conn.execute("SELECT now() - watermark FROM etl_watermark"
                         " WHERE pipeline = %s", (pipeline,)).fetchone()
    if stale is None or stale[0].days > 1:
        problems.append("watermark is more than a day behind")
    return problems

The orphan check catches the most trouble in practice. A report that adds a column, or an ASIN that arrives without its dimension row, trips it on the first run. Counting rows against last week catches the quiet failure where the file parsed but came back empty.

Querying the warehouse for business insights

Once the fact table is loaded, the business questions turn into SQL. Useful metrics come from joining the facts to the dimensions and aggregating at the grain you report on.

LISTING_METRICS = """
SELECT f.asin, d.brand,
       round(sum(f.revenue), 2) AS revenue_90d,
       sum(f.sessions) AS sessions_90d,
       round(100.0 * sum(f.buy_box_wins) / nullif(sum(f.sessions), 0), 1)
           AS buy_box_pct
FROM fact_listing_daily f JOIN dim_asin d USING (asin)
WHERE f.date_key >= current_date - interval '90 days'
GROUP BY f.asin, d.brand
HAVING sum(f.revenue) > 0
ORDER BY revenue_90d DESC LIMIT 50
"""


def top_listings(conn):
    """Return the highest revenue listings for the last 90 days."""
    return conn.execute(LISTING_METRICS).fetchall()

Storing sessions and buy_box_wins separately lets you track Buy Box win rate. Revenue alone cannot tell you whether a listing is healthy or holding its price while traffic drains away.

The layer above the warehouse has its own problems. Building Custom Dashboards for Real-Time Market Data Using Amazon SP-API covers how a dashboard reads such a schema.

What a custom warehouse actually costs

Then there is the cost, which gets underestimated. A custom warehouse buys query flexibility and full history, and lets the schema match how your business works. It costs engineering time to build, then ongoing time to own: storage, backups, schema migrations, and who gets woken up when a load fails at three in the morning.

Vendored reporting tools hand you dashboards sooner and cost you the flexibility. For a seller with a handful of ASINs, the tool is the better buy. For a catalog in the thousands, the warehouse pays for itself.

Conclusion

The shape that works is a star schema at a daily grain, an upsert loader that tracks a watermark, validation that runs before the watermark moves, and a query layer that aggregates rather than counts rows.

Where the data comes from matters as much as where it lands. Advanced Techniques for Data Integration with Amazon SP-API covers joining report types into one load, and How to Use Amazon SP-API for Automated Data Collection covers the request patterns.

FAQs

  1. Do I need my own warehouse, or can I use Amazon’s reporting? Amazon’s reports answer the questions their dashboards were built for. A warehouse earns its place when you need history across years or want to join report types together.

  2. How often should I pull data from SP-API? Once a day for anything on a daily cycle, which covers most sales and inventory reports. Use the Notifications API or Data Kiosk for data that changes during the day.

  3. What is a watermark and why does the load need one? A watermark is the date of the last data you loaded completely. It lets the next run request only what is new instead of re-downloading a window you hold, and makes a failed run safe to repeat.

  4. Is a custom data warehouse expensive to run? Storage is the smallest part of the bill. The real cost is engineering time to build it and the maintenance that follows: backups, schema migrations. A small catalog often gets more from Amazon’s own reporting.

  5. Which SP-API data access role does a reporting pipeline need? Inventory and Order Tracking covers the FBA sales and order tracking reports, and it is where most warehouses start. Selling Partner Insights adds Seller Central metrics, and Brand Analytics adds search term data.

    Back to Blog

    Related Posts

    View All Posts »
    What is Amazon Vendor Central API?

    What is Amazon Vendor Central API?

    Discover how Amazon Vendor Central API can revolutionize your vendor operations on Amazon. Learn about its features, benefits, and practical uses in this comprehensive guide.