Tutorial2 min readUpdated Mar 22, 2026

Build a Price Comparison Tool with PriceFetch API

TL;DR

Use PriceFetch API to fetch prices from multiple retailers in parallel, compare them, and return the cheapest option. Under 100 lines of Python.

What We're Building

We're building a Python script that takes a product name, fetches its price from multiple retailers via PriceFetch API, and tells you where it's cheapest. The script handles concurrent requests, error handling, and outputs a clean comparison table.

The end result: you pass in product URLs from different retailers, and get back a sorted list of prices with retailer names, stock status, and direct links. This is the foundation for any price comparison app, deal aggregator, or competitive intelligence tool.

Try it yourself — 500 free API credits, no credit card required.

Start Free

Project Setup

You'll need Python 3.8+ and the `httpx` library for async HTTP requests. We use `httpx` over `requests` because PriceFetch returns fast enough that parallelizing requests makes a real difference.

Sign up at pricefetch.dev to get your API key. You get 500 free credits to start, which is plenty for building and testing this project.

bash
pip install httpx asyncio

# Create your project file
touch price_compare.py

Fetching Prices from PriceFetch

The core function hits the PriceFetch API for a single URL and returns structured price data. We wrap it in error handling because some products might be unavailable or the URL might be wrong. The API returns a clean JSON envelope with `success`, `data`, and `error` fields, so parsing is straightforward.

Note the `X-API-Key` header — this is required on every request. Store your key in an environment variable, never hardcode it.

python
import httpx
import asyncio
import os
from dataclasses import dataclass

API_KEY = os.environ["PRICEFETCH_API_KEY"]
BASE_URL = "https://api.pricefetch.dev/v1/price"

@dataclass
class PriceResult:
    url: str
    retailer: str
    price: float
    currency: str
    in_stock: bool

async def fetch_price(client: httpx.AsyncClient, url: str) -> PriceResult | None:
    """Fetch price for a single product URL."""
    try:
        response = await client.get(
            BASE_URL,
            params={"url": url},
            headers={"X-API-Key": API_KEY},
            timeout=15.0,
        )
        data = response.json()
        if not data["success"]:
            print(f"  Skipped {url}: {data['error']['message']}")
            return None
        d = data["data"]
        return PriceResult(
            url=d["url"],
            retailer=d["retailer"],
            price=d["price"],
            currency=d["currency"],
            in_stock=d["in_stock"],
        )
    except httpx.TimeoutException:
        print(f"  Timeout fetching {url}")
        return None

Comparing Prices Across Retailers

Now we fetch all URLs concurrently and sort by price. Using `asyncio.gather` lets us fire all requests at once instead of waiting for each one sequentially. For 5 retailers, this cuts total time from ~40 seconds to ~8 seconds.

The comparison function filters out failed lookups and out-of-stock items, then sorts by price ascending. Simple and effective.

python
async def compare_prices(urls: list[str]) -> list[PriceResult]:
    """Fetch prices for all URLs and return sorted by price."""
    async with httpx.AsyncClient() as client:
        tasks = [fetch_price(client, url) for url in urls]
        results = await asyncio.gather(*tasks)

    # Filter out failures and out-of-stock items
    valid = [r for r in results if r is not None and r.in_stock]
    return sorted(valid, key=lambda r: r.price)

def print_comparison(results: list[PriceResult]) -> None:
    """Print a formatted comparison table."""
    if not results:
        print("No prices found.")
        return

    print(f"\n{'Retailer':<12} {'Price':>10} {'Currency':<6} {'URL'}")
    print("-" * 70)
    for r in results:
        marker = " <-- cheapest" if r == results[0] else ""
        print(f"{r.retailer:<12} {r.price:>10.2f} {r.currency:<6} {r.url}{marker}")

# Example usage
urls = [
    "https://www.amazon.com/dp/B0CHX3QBCH",
    "https://www.walmart.com/ip/Sony-WH-1000XM5/1234567890",
    "https://www.newegg.com/p/0S6-00FF-00001",
]

results = asyncio.run(compare_prices(urls))
print_comparison(results)

Handling Multiple Currencies

When comparing across international retailers (e.g., amazon.com vs amazon.co.uk), you'll get prices in different currencies. PriceFetch returns the currency code with every response, so you can normalize them.

For a production tool, use a currency conversion API to normalize everything to a single currency before comparing. For quick comparisons within the same country, this isn't needed — just group by currency.

python
from collections import defaultdict

def group_by_currency(results: list[PriceResult]) -> dict[str, list[PriceResult]]:
    """Group results by currency for fair comparison."""
    groups: dict[str, list[PriceResult]] = defaultdict(list)
    for r in results:
        groups[r.currency].append(r)
    for currency in groups:
        groups[currency].sort(key=lambda r: r.price)
    return dict(groups)

# Usage
grouped = group_by_currency(results)
for currency, items in grouped.items():
    print(f"\n=== {currency} ===")
    print_comparison(items)

Next Steps

You now have a working price comparison engine in under 100 lines of Python. From here, you can extend it in several directions:

- Add a database to track prices over time (see our price tracking tutorial) - Build a web UI on top with Flask or FastAPI - Set up automated alerts when the cheapest price drops below a threshold - Add more product URLs dynamically from a spreadsheet or database

Each PriceFetch API call costs one credit, and you get 500 free credits on signup. For a comparison tool checking 5 retailers, that's 100 comparisons to build and test with.

Frequently asked questions

Start fetching prices — 500 free credits

Sign up in 30 seconds. No credit card required. One credit per successful API call.