Every new set raises the same question: which cards are actually worth chasing? Pull-rate charts and hype videos give opinions. A price list gives a ranking. In this tutorial we'll write a Python script that takes a game and a set name, collects every card in that set, prices them all and prints the ten most valuable, plus a CSV file you can open in a spreadsheet.
What we'll build
You run one command:
python top_cards.py "Pokemon" "Delta Reign"
and get a table with the rank, card name, collector number, rarity and Near Mint market price, with the most expensive card first. The same script works for any game and set the API knows, so it is just as useful for a Magic set or a One Piece booster.
Here are a few cards the script would find near the top of Delta Reign:
Mega Rayquaza ex - 138/103ME06: Delta Reign$289.19Near Mint Holofoil
Mega Rayquaza ex - 141/103ME06: Delta Reign$210.62Near Mint HolofoilWhat you need
- Python 3.9 or newer and the
requestslibrary (pip install requests). - An API key from the dashboard, on the Starter plan or higher. The reason is the plan limits: a set has a couple of hundred cards, and the Free plan prices one card per request and allows 100 requests a day. Starter prices 20 cards per request and allows 1,000 cards a day, so a 200-card set costs about 200 of those cards and around a dozen requests.
- Two environment variables:
TCGPRICEAPI_KEYwith your key andTCGPRICEAPI_URLwith the API address.
The API has no sort option, so ranking happens in our script. That is a good thing for a tutorial: you decide what "most valuable" means.
Step 1: set up the connection and read your plan
Start with the imports, the two variables and a helper that stops cleanly if a limit is reached. A request over a limit gets a 429 answer with a Retry-After header, so we show it and quit instead of crashing.
import csv
import os
import sys
import requests
API = os.environ["TCGPRICEAPI_URL"].rstrip("/")
HEADERS = {"X-API-Key": os.environ["TCGPRICEAPI_KEY"]}
def call(method, path, **kwargs):
answer = requests.request(method, API + path, headers=HEADERS,
timeout=60, **kwargs)
if answer.status_code == 429:
wait = answer.headers.get("Retry-After", "a while")
raise SystemExit(f"Limit reached. Try again in {wait} seconds.")
answer.raise_for_status()
return answer.json()
Next, ask what your plan allows. GET /v1/usage is free and returns the limits, including how many cards one price request may contain. Reading it means the script keeps working if you move to a bigger plan.
def cards_per_request():
usage = call("GET", "/v1/usage")
return usage["limits"]["cards_per_request"]
Step 2: list every card in the set
GET /v1/cards searches without prices. It returns up to 100 cards per page, so we page through with offset until a page comes back shorter than the limit. Each result has card_id, name, set, number, rarity, game and image_url.
The set value must be the exact set name. If you're not sure of the spelling, GET /v1/sets?game=Pokemon lists every set for a game.
def cards_in_set(game, set_name):
cards, offset = [], 0
while True:
page = call("GET", "/v1/cards", params={
"game": game, "set": set_name, "limit": 100, "offset": offset})
cards.extend(page)
if len(page) < 100:
return cards
offset += 100
A set with 200 cards takes two or three search requests. Search results don't include prices, so this step costs requests but no price lookups.
Step 3: price the cards in bulk
POST /v1/cards/lookup takes a list of card_ids and returns the cards with all their SKUs. We ask for Near Mint so the comparison is fair, and send the ids in chunks that fit the plan's limit.
def price_cards(cards, chunk):
priced = []
ids = [c["card_id"] for c in cards]
for i in range(0, len(ids), chunk):
body = {"card_ids": ids[i:i + chunk], "condition": "Near Mint"}
answer = call("POST", "/v1/cards/lookup", json=body)
priced.extend(answer["cards"])
return priced
Because the ids come from the search in step 2, we never type an id by hand. Anything the API can't find would be listed under not_found, which we ignore here.
Step 4: pick one price per card
A card can have several SKUs: normal, holo, reverse holo and so on, each with its own market_price. For a ranking we use the highest Near Mint market price among a card's SKUs, since that is the printing collectors are usually chasing. Prices can be null, so those are skipped, and cards with no price at all drop out.
def best_price(card):
prices = [s["market_price"] for s in card["skus"]
if s["condition"] == "Near Mint"
and s["market_price"] is not None]
return max(prices) if prices else None
If you prefer the lowest price, or only foil printings, change this one function. Each SKU also carries printing, so a filter on sku["printing"] is a one-line change.
Step 5: rank, print and save
The last step ties everything together. It sorts by price, prints the top ten and writes the whole ranked set to a CSV file.
def main(game, set_name):
cards = cards_in_set(game, set_name)
if not cards:
raise SystemExit("No cards found. Check the game and set names "
"with GET /v1/sets.")
priced = price_cards(cards, cards_per_request())
rows = [(best_price(c), c) for c in priced]
rows = [(p, c) for p, c in rows if p is not None]
rows.sort(key=lambda r: r[0], reverse=True)
print(f"{len(rows)} priced cards in {set_name}\n")
print(f"{'#':>2} {'Card':<36} {'Number':<10} {'Rarity':<22} {'Price':>9}")
for rank, (price, c) in enumerate(rows[:10], start=1):
print(f"{rank:>2} {c['name']:<36.36} {c['number'] or '':<10} "
f"{c['rarity'] or '':<22.22} {price:>9.2f}")
with open("top_cards.csv", "w", newline="", encoding="utf-8") as f:
out = csv.writer(f)
out.writerow(["rank", "name", "number", "rarity", "price"])
for rank, (price, c) in enumerate(rows, start=1):
out.writerow([rank, c["name"], c["number"], c["rarity"], price])
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2])
The full script
Save the pieces in one file called top_cards.py, in this order: the imports and call, cards_per_request, cards_in_set, price_cards, best_price and main. Then run it:
export TCGPRICEAPI_KEY="your-key"
export TCGPRICEAPI_URL="https://tcgpriceapi.com"
python top_cards.py "Pokemon" "Delta Reign"
The prices are the market prices exactly as the API reports them, and market prices refresh every 6 hours. Running the script twice in one afternoon will give the same ranking, so there is no reason to run it more often than that.
Ideas to extend it
- Run it once a week and save each CSV with the date in the file name. Comparing two files shows which cards climbed and which fell, with no extra requests beyond the weekly run.
- Add the listing data. Each SKU has
listing_price_low,copies_listedandsellers, so you can flag cards that are expensive but have very few sellers. - Call
GET /v1/cards/{card_id}/history?timeframe=30dfor just your top ten to add a 30-day trend column. History requests take up to 1 card on Starter, so on Starter that is ten extra requests, and on Pro you can send all ten in one. - Turn the output into a Discord message, using the approach in our Discord price bot guide.
- Rank by rarity: group the rows by
rarityand show the top card of each, which is handy for a "what to look for in a pack" post.
What you could build
The same three calls (search a set, bulk price it, sort) power a lot of small products:
- A "top 10 chase cards" page for a store or content site that updates itself every time a new set is listed.
- A pre-release or post-release newsletter that ranks the cards of each new set on the day it launches.
- A booster box value estimator: add up the top cards and compare them with the box price, so shoppers can see whether a sealed purchase has been worth it so far.
- A set-by-set price report for a YouTube channel, spreadsheet or Discord server.
- A pricing sheet for a card shop that shows which cards in a new set deserve a display case.
Every paid plan, from Starter up, allows commercial use, so a site, newsletter or store tool built this way can earn money. If you want to check the idea first, the Explore pages show every set and card with prices and need no key.