Build an eBay price checker in Python in 10 minutes
On this page (14 sections)
- What you need
- Step 1: make your first request
- Step 2: understand what comes back
- Step 3: narrow the search with parameters
- Step 4: drop listings that are not your item
- Step 5: compute the median with shipping
- Step 6: handle errors and retries
- The full script
- Step 7: export to CSV
- Step 8: check many items at once
- Ideas to take it further
- Test it on a few keywords first
- How the script decides what counts
- Frequently asked questions
You can build an eBay price checker in Python with about 60 lines of code: send a keyword to a sold listings API, drop the listings that are not your item, add shipping, and print the median sold price. This tutorial uses the SellerComps API (one key, up to 240 sold listings per request) and only the requests library.
By the end you will have a command line tool you run as python pricecheck.py "nintendo switch oled" that prints the number of sales, the median, the typical range and the most recent sales.
What you need
- Python 3.9 or newer,
- the
requestslibrary (pip install requests), - a SellerComps API key. The free plan includes 100 requests a month with no card, which is plenty for this tutorial.
Keep the key out of your code. Put it in an environment variable:
export SELLERCOMPS_KEY="YOUR_API_KEY"Step 1: make your first request
Every request goes to https://api.sellercomps.com/scrape with your key as a bearer token. The only required parameter is keyword:
import os
import requests
r = requests.get(
"https://api.sellercomps.com/scrape",
params={"keyword": "nintendo switch oled"},
headers={"Authorization": f"Bearer {os.environ['SELLERCOMPS_KEY']}"},
timeout=90,
)
data = r.json()
print(data["count"], data["results"][0]["title"], data["results"][0]["soldPrice"])Run it and you should see the number of sales returned, plus the title and price of the newest one. Searches usually answer in a few seconds, but use a timeout of at least 90 seconds as the errors guide suggests.
Step 2: understand what comes back
results is a list of sales, newest first. The fields you will use most:
| Field | Meaning |
|---|---|
title | The listing title |
soldPrice | What the buyer paid, as a decimal string |
shippingPrice | Shipping cost, "0" when free |
totalPrice | Price plus shipping |
endedAt | The day it sold, YYYY-MM-DD |
condition | The condition eBay recorded |
buyingFormat | auction or buyItNow |
url | Link to the listing |
Prices are strings, so convert them with float() before doing math. The response fields page lists every field.
Step 3: narrow the search with parameters
You can do a lot of the cleaning before the data even arrives:
itemCondition:any,neworused,buyingFormat:all,auction,buyItNoworacceptsOffers,minPriceandmaxPrice: drop cheap accessories and lots,soldAfter: only recent sales,YYYY-MM-DD,ebaySite:ebay.co.uk,ebay.deand 5 more countries,count: 1 to 240 results.
eBay's minus sign works in the keyword too: nintendo switch oled -case -game drops titles with those words.
Step 4: drop listings that are not your item
Even with a good keyword, some results are lots, parts or accessories. A short list of title words to skip handles most of them:
SKIP = ("lot of", "bundle", "for parts", "repair", "broken", "box only", "case only", "empty box")
def is_match(title: str) -> bool:
t = title.lower()
return not any(word in t for word in SKIP)Match whole phrases like "lot of" rather than single short words, so a title with "slot" or "pilot" is not dropped by mistake. Tune the list to the kind of item you check: for cards you might add "proxy" and "custom", for electronics "untested".
Step 5: compute the median with shipping
Use the total price (price plus shipping) and the median, so one strange sale does not move the answer much. Python's statistics module does the work:
import statistics
def summarize(sales):
prices = sorted(float(s["totalPrice"]) for s in sales)
result = {"count": len(prices), "median": statistics.median(prices)}
if len(prices) >= 4:
low, _, high = statistics.quantiles(prices, n=4)
result.update(low=low, high=high)
return resultlow and high here are the 25th and 75th percentiles: half of all sales fall between them, which is a more useful range than the absolute lowest and highest.
Step 6: handle errors and retries
Three answers need special handling:
- 404 means nothing matched. It is not counted against your requests. Treat it as "no sales".
- 429 means you are sending too fast. Wait for the
Retry-Afterheader, then try again. - 502, 503 and 504 mean the marketplace was slow or busy. Retry shortly. These are not counted either.
Failed requests never use your allowance, so retrying is free.
The full script
Put it all together in pricecheck.py:
import os
import statistics
import sys
import time
import requests
API = "https://api.sellercomps.com/scrape"
HEADERS = {"Authorization": f"Bearer {os.environ['SELLERCOMPS_KEY']}"}
RETRY = {429, 502, 503, 504}
SKIP = ("lot of", "bundle", "for parts", "repair", "broken", "box only", "case only", "empty box")
def sold(keyword, **params):
for attempt in range(4):
r = requests.get(API, params={"keyword": keyword, **params}, headers=HEADERS, timeout=90)
if r.status_code == 404:
return []
if r.status_code in RETRY:
time.sleep(float(r.headers.get("Retry-After", 2 ** attempt)))
continue
r.raise_for_status()
return r.json()["results"]
r.raise_for_status()
def is_match(title):
t = title.lower()
return not any(word in t for word in SKIP)
def main():
keyword = " ".join(sys.argv[1:]) or "nintendo switch oled"
sales = [s for s in sold(keyword, itemCondition="used", count=240) if is_match(s["title"])]
if not sales:
print(f"No sales found for {keyword!r}")
return
prices = sorted(float(s["totalPrice"]) for s in sales)
print(f"{keyword}: {len(prices)} sales")
print(f"Median sold price: {statistics.median(prices):.2f} {sales[0]['soldCurrency']}")
if len(prices) >= 4:
q = statistics.quantiles(prices, n=4)
print(f"Typical range: {q[0]:.2f} to {q[-1]:.2f}")
print("Latest sales:")
for s in sales[:5]:
print(f" {s['endedAt']} {float(s['totalPrice']):>8.2f} {s['title'][:60]}")
if __name__ == "__main__":
main()Run it:
python pricecheck.py "nintendo switch oled"Step 7: export to CSV
Want the sales in a spreadsheet? Add format=csv and save the file instead of parsing JSON:
r = requests.get(API, params={"keyword": "nintendo switch oled", "format": "csv"}, headers=HEADERS, timeout=90)
r.raise_for_status()
with open("switch-oled-sold.csv", "wb") as f:
f.write(r.content)Each row is one sale with the same fields as the JSON.
Step 8: check many items at once
To price a whole list, send them as one batch job instead of looping. POST /scrape/batch takes up to 100 keywords and returns a job id. You then read the results with GET /scrape/batch/{jobId}, and finished keywords appear while the rest are still running. Each keyword that succeeds uses one request.
Ideas to take it further
- Other marketplaces.
GET /sold?source=tcgplayer(orstockx,poshmark,grailed,mercariand more) returns sold data from other marketplaces in one shared row format, with asummarythat already includes the median. See every marketplace. - Active listings. Add
sold=falseto see what you would be competing against right now. - Best Offer prices. Add
bestOfferPrice=trueto get the accepted price on Best Offer sales. Our post on eBay Best Offer prices explains why it matters. - A Discord or Telegram bot that answers "what is this worth" in a chat.
- A nightly job that prices your inventory and writes the result to a database.
Test it on a few keywords first
Before you trust the numbers, run the script on three or four items you know well:
- An item that sells often, so you get the full 240 results.
- An item that rarely sells, to see how it handles a short list.
- A keyword that should find nothing, to check the "No sales found" path.
- A keyword that mixes in accessories, to see whether your skip list catches them.
Open a few of the printed listing links and compare them with what you would pick by hand. If the script keeps lots or parts you would drop, add those words to the skip list. If it drops real sales, make the phrases more specific. Because searches with no results and retries are not counted, this kind of testing barely touches your monthly requests.
Keep your key safe
- Read the key from an environment variable, as the script does, and never commit it to a repository.
- If you share the tool with others, give each person their own key so usage is tracked per person.
- If a key leaks, create a new one in the dashboard and delete the old one.
How the script decides what counts
The script makes three decisions you may want to change for your own items. It uses itemCondition="used", so new items are left out; switch it to new or any to match what you sell. It uses totalPrice, so shipping is included; use soldPrice if you always charge shipping separately. And it takes the median of every matching sale returned; add soldAfter if you only want the last few weeks.
Frequently asked questions
Is there an official eBay API for sold prices in Python?
eBay's own sold data API, Marketplace Insights, is limited to approved partners, and the old findCompletedItems call was retired. A sold listings API like SellerComps works from Python with only the requests library.
How many sold listings does one request return?
Up to 240, newest first. Use the page parameter to read further.
Why use the median instead of the average?
One unusual sale can pull an average a long way. The median stays close to what most buyers paid.
Do failed requests count against my plan?
No. Searches with no results (404) and marketplace errors (502, 503, 504) are not counted.
Can I run this for free?
Yes. The free plan includes 100 requests a month with no card, and each request returns up to 240 sold listings.
Ethan Parker writes about pricing with real sold data at SellerComps.