---
title: "Build an ETL Pipeline in Python for Web Data | Perceptlayer"
description: "An ETL pipeline in Python for web data: extract Google Shopping prices with retries, transform to typed rows, load into SQLite idempotently, run daily."
url: https://perceptlayer.com/blog/etl-pipeline-python-web-data
---

[Blog](https://perceptlayer.com/blog) / [Data engineering](https://perceptlayer.com/blog/category/data-engineering)

# Build an ETL Pipeline in Python for Web Data

13 Oct 2026 Updated 25 Oct 2026 Perceptlayer 6 min read

An ETL pipeline in Python is three functions and a scheduler: extract data from a source, transform it into clean, typed rows, and load those rows into a database, run on a timer. This tutorial builds one for web data with `requests` and the standard library's `sqlite3`: it pulls Google Shopping prices from an API with retries, keeps the raw responses, turns each result into a typed row, and upserts the rows so a re-run never duplicates anything. The complete pipeline is about 130 lines, and we ran it on a recorded API response.

## Key takeaways

-   Extract with retries on 429 and 503 only, waiting the `Retry-After` seconds; any other error is raised for that query, and the run moves on to the next one.
-   Land the raw JSON before transforming it. A transform bug then costs a re-run over files, not new API calls.
-   Transform into typed rows and check them: the recorded response priced one listing at `"$17.50/mo"`, which `extracted_price` turns into `17.5`, so the pipeline flags monthly prices.
-   Load with `INSERT … ON CONFLICT DO UPDATE` on a key of date, query, country, product and seller. Running the job twice on one day leaves 3 rows, not 6.
-   Each query is 1 credit per successful call: 50 queries a day is 1,500 credits a month.

## What does an ETL pipeline in Python need?

An ETL pipeline needs a source to extract from, rules to transform with, a store to load into, and something to run it on a schedule. Here the source is `GET /v1/google-shopping/search`, which returns product offers as JSON for a query `q`; the transform turns each offer into a row with a fixed type per column; the store is SQLite, which ships with Python; and the scheduler is cron.

```bash
pip install requests
export API_KEY=sk_live_...
```

That's the only dependency. We ran the code with Python 3.13; the [`sqlite3` module](https://docs.python.org/3/library/sqlite3.html) comes with Python, and the upsert syntax needs SQLite 3.24 or later ( [SQLite: UPSERT](https://www.sqlite.org/lang_upsert.html), 2026). Get a key free at [/signup](https://perceptlayer.com/signup).

Why bother with three stages rather than one script that fetches and inserts? Because each stage fails differently. An extract fails when the network or the source does; a transform fails when the data surprises you; a load fails on constraints. Keeping them apart means you can re-run one without repeating the others, and you can test each with fixtures.

## How do you build the pipeline, step by step?

The whole pipeline is one file, `etl.py`, with one section per stage and a `run()` function that ties them together. It extracts each configured query, lands the raw response on disk, transforms it into rows and loads them in one transaction. The four steps after the code explain each stage and the choice behind it.

```python
"""Daily ETL: Google Shopping prices -> SQLite."""
import json
import os
import sqlite3
import sys
import time
from datetime import datetime, timezone
from pathlib import Path

import requests

API = "https://api.perceptlayer.com"
QUERIES = [("iphone 15", "us"), ("pixel 9", "us")]
RAW_DIR = Path("raw")
DB_PATH = "prices.db"

# --- Extract -----------------------------------------------------------------

def extract(query, gl, max_attempts=4):
    """One search, retried on 429/503. Returns the parsed JSON response."""
    params = {"q": query, "gl": gl, "hl": "en"}
    for attempt in range(1, max_attempts + 1):
        resp = requests.get(
            f"{API}/v1/google-shopping/search",
            params=params,
            headers={"X-API-Key": os.environ["API_KEY"]},
            timeout=90,
        )
        if resp.status_code == 200:
            return resp.json()
        if resp.status_code in (429, 503) and attempt < max_attempts:
            time.sleep(int(resp.headers.get("Retry-After", 2 ** attempt)))
            continue
        error = resp.json().get("error", {})
        raise RuntimeError(f"{resp.status_code} {error.get('code')}: {error.get('message')}")

def land_raw(payload, query, gl, run_at):
    """Keep the untouched response, so a bad transform can be re-run without new calls."""
    RAW_DIR.mkdir(exist_ok=True)
    path = RAW_DIR / f"{run_at:%Y-%m-%d}_{gl}_{query.replace(' ', '-')}.json"
    path.write_text(json.dumps(payload))
    return path

# --- Transform ---------------------------------------------------------------

def transform(payload, query, gl, run_at):
    rows, skipped = [], 0
    for item in payload.get("shopping_results", []):
        price = item.get("extracted_price")
        if not item.get("product_id") or not isinstance(price, (int, float)):
            skipped += 1
            continue
        rows.append({
            "observed_on": run_at.date().isoformat(),
            "query": query,
            "gl": gl,
            "product_id": item["product_id"],
            "seller": item.get("source") or "",
            "title": item.get("title"),
            "price": float(price),
            "price_text": item.get("price"),
            "monthly": int("/mo" in (item.get("price") or "")),  # instalment, not a purchase price
            "rating": item.get("rating"),
            "reviews": item.get("reviews"),
            "position": item.get("position"),
        })
    return rows, skipped

# --- Load --------------------------------------------------------------------

SCHEMA = """
CREATE TABLE IF NOT EXISTS shopping_prices (
  observed_on TEXT NOT NULL,
  query       TEXT NOT NULL,
  gl          TEXT NOT NULL,
  product_id  TEXT NOT NULL,
  seller      TEXT NOT NULL,
  title       TEXT,
  price       REAL NOT NULL,
  price_text  TEXT,
  monthly     INTEGER NOT NULL,
  rating      REAL,
  reviews     INTEGER,
  position    INTEGER,
  PRIMARY KEY (observed_on, query, gl, product_id, seller)
)
"""

UPSERT = """
INSERT INTO shopping_prices
  (observed_on, query, gl, product_id, seller, title, price, price_text, monthly, rating, reviews, position)
VALUES
  (:observed_on, :query, :gl, :product_id, :seller, :title, :price, :price_text, :monthly, :rating, :reviews, :position)
ON CONFLICT (observed_on, query, gl, product_id, seller) DO UPDATE SET
  title = excluded.title, price = excluded.price, price_text = excluded.price_text, monthly = excluded.monthly,
  rating = excluded.rating, reviews = excluded.reviews, position = excluded.position
"""

def load(conn, rows):
    with conn:  # one transaction per batch: all rows or none
        conn.executemany(UPSERT, rows)

# --- Run ---------------------------------------------------------------------

def run():
    run_at = datetime.now(timezone.utc)
    conn = sqlite3.connect(DB_PATH)
    conn.execute(SCHEMA)
    failures = 0
    for query, gl in QUERIES:
        try:
            payload = extract(query, gl)
        except Exception as exc:  # one failed query shouldn't stop the others
            failures += 1
            print(f"extract failed for {query!r}/{gl}: {exc}", file=sys.stderr)
            continue
        land_raw(payload, query, gl, run_at)
        rows, skipped = transform(payload, query, gl, run_at)
        load(conn, rows)
        print(f"{query!r}/{gl}: loaded {len(rows)} rows, skipped {skipped}")
    conn.close()
    return failures

if __name__ == "__main__":
    sys.exit(1 if run() else 0)
```

### Step 1: extract with retries

`extract()` makes one request per query and retries only what's worth retrying: 429 (rate limited) and 503 (temporarily unavailable), waiting the seconds in `Retry-After`. Anything else, such as a 422 for a bad parameter, raises at once with the API's error `code` and `message`. A failed call costs nothing and returns `X-Credits-Used: 0`, so a retry after an error doesn't double the bill. [Handle Web Data API Errors in Python](https://perceptlayer.com/blog/handle-web-data-api-errors-python) covers the full set of status codes.

### Step 2: land the raw response

`land_raw()` writes the untouched JSON to `raw/2026-10-25_us_iphone-15.json` before anything else touches it. It's the cheapest insurance in the pipeline: when you change the transform next month, you replay the files instead of re-buying the data. For larger volumes, [Save API JSON to Parquet in Python](https://perceptlayer.com/blog/save-api-json-to-parquet-python) covers a columnar format.

### Step 3: transform into typed rows

`transform()` keeps the fields worth keeping and gives each a type: `price` from `extracted_price` as a float, `rating` as a float, `reviews` and `position` as integers. It skips offers with no `product_id` or no numeric price and counts them, so a sudden jump in skipped rows shows up in the log.

The transform is also where data checks go, and the recording shows why. This is the response, trimmed:

```json
{
  "search_parameters": { "q": "iphone 15", "gl": "us", "hl": "en", "start": 0, "device": "desktop" },
  "shopping_results": [
    {
      "position": 1,
      "title": "Apple iPhone 15",
      "source": "Walmart - Wireless Source",
      "rating": 4.7,
      "reviews": 45000,
      "product_id": "4263606017411565992",
      "price": "$393.73",
      "extracted_price": 393.73,
      …
    },
    …
    {
      "position": 3,
      "title": "Apple iPhone 15 - Black - 128GB (with 36 monthly payments + plan)",
      "source": "T-Mobile",
      "product_id": "8345423428288821281",
      "price": "$17.50/mo",
      "extracted_price": 17.5,
      …
    }
  ],
  "pagination": { "current_page": 1, "start": 0, "next_start": 10 }
}
```

The third offer is a monthly instalment, and its `extracted_price` of `17.5` would read as the cheapest iPhone 15 in the data. The pipeline keeps it, keeps the original text in `price_text`, and sets `monthly = 1` so analysis can exclude it. Expect more cases like this; [Normalise Prices Across Currencies and Sources](https://perceptlayer.com/blog/normalize-prices-multiple-currencies) covers currencies and units.

### Step 4: load idempotently

`load()` upserts every row in one transaction. The primary key is the day, the query, the country, the product and the seller, so a second run on the same day updates the same rows instead of adding new ones. That makes the job safe to re-run after a failure, which you will do. Postgres has the same `ON CONFLICT` syntax; [Loading API JSON into Postgres](https://perceptlayer.com/blog/load-web-data-json-into-postgres) adapts it, and [Incremental API Data Pulls](https://perceptlayer.com/blog/incremental-api-data-pulls) covers fetching only what's new.

## What does a run produce?

We ran the pipeline with `extract()` replaced by a function returning the recorded response for `iphone 15` in the US, twice in a row. Both runs printed `'iphone 15'/us: loaded 3 rows, skipped 0`, and the table held 3 rows, not 6:

```text
('2026-10-25', '4263606017411565992', 'Walmart - Wireless Source', 393.73, '$393.73', 0)
('2026-10-25', '4379032623638529631', 'Best Buy', 441.0, '$441.00', 0)
('2026-10-25', '8345423428288821281', 'T-Mobile', 17.5, '$17.50/mo', 1)
```

A purchase-price query then leaves out the instalment:

```sql
SELECT seller, price, price_text
FROM shopping_prices
WHERE monthly = 0 AND query = 'iphone 15' AND observed_on = '2026-10-25'
ORDER BY price;
```

which returned `('Walmart - Wireless Source', 393.73, '$393.73')` and `('Best Buy', 441.0, '$441.00')`. We also tested `extract()` with a mocked 429 followed by a 200, which retried once and returned the 3 results, and a mocked 422, which raised `422 invalid_parameters: 'q' is required`. We didn't call the live API.

## How do you schedule it and keep it healthy?

Schedule it with cron on any machine that stays on, and make the job tell you when it fails. The script exits with status 1 if any query failed, which cron, systemd or a CI runner can alert on. A daily run at 06:15:

```bash
15 6 * * * cd /opt/prices && API_KEY=sk_live_... /usr/bin/python3 etl.py >> etl.log 2>&1
```

Three checks catch most problems before anyone reads a dashboard:

1.  **Row counts.** Log rows loaded and skipped per query, and alert when a query that usually loads 20 rows loads 0.
2.  **Failed queries.** The exit status covers them; the log line says which query and why.
3.  **Spend.** Every successful response reports `X-Credits-Used` and `X-Credits-Remaining`. Log the remaining balance each run so a top-up never comes as a surprise; when the balance is empty, calls return `insufficient_credits` (402).

### What does it cost to run?

Each query is one call, and each successful call costs 1 credit. Deeper results cost one call per page: pass `start` from `pagination.next_start`.

| Job | Calls a month | Credits |
| --- | --- | --- |
| 30 queries, daily | 30 × 30 | 900; the 100 free credits cover the first 3 days, the Starter pack's 10,000 the next 11 months |
| 50 queries, daily | 50 × 30 | 1,500 |
| 200 queries in 3 countries, daily | 200 × 3 × 30 | 18,000, inside the Build pack's 50,000 |

See [pricing](https://perceptlayer.com/pricing) for what credits cost. Requests run at 1 a second on a free account, so the 100 free queries take under 2 minutes; the [rate limits docs](https://docs.perceptlayer.com/rate-limits) list faster rates.

To adapt the pipeline to another source, change `extract()`'s endpoint and parameters and rewrite `transform()` for its fields; the land and load stages stay the same. Run a query in the playground on the [Google Shopping API page](https://perceptlayer.com/apis/google-shopping) first to see the fields you'll map.

## APIs in this post

-   [Google Shopping **1 credit per call** · 4 endpoints](https://perceptlayer.com/apis/google-shopping)

## Frequently asked questions

### Should I use pandas for an ETL pipeline in Python?

Use it when the transform is tabular work, such as joins, group-bys and reshaping, on data that fits in memory. For row-by-row cleaning of API responses, plain dictionaries are simpler, have no dependency and make the types explicit. Many pipelines use both: dictionaries to build rows, pandas or SQL for the analysis afterwards.

### Do I need Airflow to schedule an ETL pipeline?

Not for one job. Cron, a systemd timer or a scheduled CI workflow runs a daily script reliably. An orchestrator such as Airflow or Dagster earns its setup when you have many jobs with dependencies between them, need backfills, or want retries and alerts managed in one place.

### How do I make an ETL load idempotent?

Give every row a natural key that identifies one observation, such as date, query, country, product and seller, make it the primary key, and load with an upsert ( `INSERT … ON CONFLICT DO UPDATE`). Wrap each batch in a transaction so a failure leaves nothing half-written. Then re-running a day replaces that day's rows instead of duplicating them.

### What happens if the API call fails mid-run?

That query raises, the run logs it and moves on to the next query, and the script exits with status 1 at the end so your scheduler can alert. A failed call costs nothing. Because loads are idempotent, re-running the whole job later fills the gap without duplicating the queries that worked.

### Where should the raw responses be stored?

Anywhere cheap and durable: a local folder for a small job, object storage such as S3 for anything you need to keep. Name files by date, country and query so a replay can pick the right ones, and set a retention period. Raw responses are your only record of exactly what the source returned on a given day.

etl python data pipeline sqlite web data

## More from the blog

1.  [Data engineering](https://perceptlayer.com/blog/category/data-engineering) 10 Aug 2026 Perceptlayer 7 min read
    
    ## [Web Data to a Warehouse: Loading API JSON into Postgres](https://perceptlayer.com/blog/load-web-data-json-into-postgres)
    
    Land AutoScout24 search JSON in a Postgres JSONB table, flatten it with a view, then upsert on listing\_id. Code and credit cost per refresh.
    
2.  [Data engineering](https://perceptlayer.com/blog/category/data-engineering) 26 Oct 2026 Perceptlayer 7 min read
    
    ## [API Pagination: Cursors, Pages and Offsets in Practice](https://perceptlayer.com/blog/api-pagination-patterns)
    
    Offset, page-number and cursor pagination with recorded responses from Indeed, Craigslist and Google Play, a loop that stops correctly, and 1 credit per page.
    
3.  [Data engineering](https://perceptlayer.com/blog/category/data-engineering) 25 Oct 2026 Perceptlayer 7 min read
    
    ## [API Rate Limiting: How Limits Work and How to Stay Under](https://perceptlayer.com/blog/api-rate-limiting-explained)
    
    API rate limiting from the client side: per-minute limits, the RateLimit and Retry-After headers, and a Python pacer that runs 3,000 searches in 50 minutes.
