eBay Get Multiple Items by Item ID: Budget a 40-ID Batch Before You Run It
You have 40 eBay item IDs, you send them in one request, and you expect one request's worth of bill. Break that assumption first. The items-batch operation does accept a comma-separated list, but its response reports meta.requested and meta.upstream_calls, and in a batch they move together. People searching for "eBay API get multiple items by item ID" usually arrive because the marketplace's own multi-item lookups are restricted or deprecated for them. This route needs only a platform API key, not an eBay developer account or OAuth tokens, yet whether it fits is arithmetic you can do before sending anything.
Forty IDs in one request is still forty page fetches
items-batch is a POST with a JSON body. item_ids is required: a comma-separated string of the digits after /itm/ in a listing address. domain is optional and picks the site and currency. The operation overview states up to 40 IDs per request, while the item_ids field note says 15. Treat that conflict as open until tested on your data.
The cost model is stated plainly: one lookup per ID, priced like a single item-detail call. Forty IDs cost what forty separate listing lookups cost; the batch buys concurrency, not a discount.
Run this two-ID request first. Copying it sends nothing; running it spends lookups, and the key sits in the URL, so keep that URL out of logs and screenshots.
curl --request POST \
'https://api.opendata-api.com/api/project/ebay/items-batch?key=YOUR_API_KEY' \
--header 'Content-Type: application/json' \
--data '{"domain":"com","item_ids":"287070621317,301782776848"}'
Read meta.requested against meta.upstream_calls before scaling
A reply has three layers: the HTTP status, the gateway's code, message and data, and inside that data the operation's own ok, meta and data. Only the last holds the counters. In the recorded two-ID run the operation reported ok true, meta.requested 2, meta.upstream_calls 2, meta.concurrency 8 and meta.latency_ms near 3,800, with two active records and an empty not_found. meta.billing_note repeats that billing is per item ID.
Diagnose before you scale. If upstream_calls differs from the number of IDs you sent, your budget model is wrong; stop:
meta = result["meta"]
if meta["requested"] != len(sent) or meta["upstream_calls"] != len(sent):
raise RuntimeError("billing counters disagree with the chunk; stop")
Try 2 IDs, then 8, then your real slice size; the recorded probe covered only 2.
The six-ID card lane: search with (id1,id2,...)
The operation notes describe a cheaper path for IDs you merely watch. Call search with a query in eBay's own OR syntax, such as (287070621317,301782776848). The whole call counts as one billed lookup and returns listing cards (item_id, title, price, condition, shipping, image, url), not full records: no item specifics, seller object or return policy. The notes measured about six IDs per call, with a seventh dropped.
Two cautions. These figures come from the notes, not from the recorded probe. And a dropped seventh ID looks exactly like an ended listing, so never send more than six, and compare the returned item_id values with what you sent. The body is just {"domain": "com", "query": "(287070621317,301782776848)"} posted to search.
Decide which IDs earn a full record
Take a 120-ID nightly price check: the card lane needs 20 search calls, the full lane 120 lookups. Route by the question:
- Card lane: has the price moved, is the listing still returned, what are the condition and shipping texts? Cards carry
price,conditionandshipping. - Full lane: you need
item_specifics,brand,mpn, the seller block,return_policy,quantity_sold,watchers, or auction fields such asbidsandcurrent_bid. Even then expect nulls: the first recorded item had no seller feedback figures or category path.
The script below applies one rule: send every ID through the card lane, then escalate only IDs whose price differs from your last snapshot or that the card lane did not return.
Chunk at 40, then book not_found apart from errors
Slice the list yourself: 40 is the overview's ceiling, 15 the item_ids note's. Because cost is per ID, slice size changes latency and the blast radius of a failure, not the bill. Start at 15, never exceed 40, and raise it only after meta.requested echoes your count.
Every slice ends in one of three states; a ledger that merges them hides the spend:
- Resolved: the ID appears in
data.items. not_found: ended, removed or invalid. They still count inmeta.upstream_calls, so they were spent, but they are a finding about the listing, not a job failure. Do not retry them.- Error: the HTTP status, gateway
codeoroksays the call failed, so nothing is known about the IDs. Retrying is your call; until your dashboard says otherwise, book the lookups as spent.
The recorded run returned an empty not_found; the non-empty case is only documented, so test that branch against a hand-written response.
What the 4.1 s run saves: clock time, not calls
The operation notes measure 25.6 s for eight sequential item-detail calls against 4.1 s for the same eight IDs in one batch, about 6.2 times faster; the recorded two-ID run took about 3.8 s. These are the operation's own measurements, not guarantees. A batch blocks for seconds, so set a generous client timeout (the script uses 90 s).
Batch when the deadline is the problem, such as a nightly window or a waiting page. When the bill is the problem, batching changes nothing; the levers are the card lane and the escalation rule.
A batch runner that refuses to overspend
The script dedupes IDs, runs the card lane first, escalates only changed or missing IDs, refuses any slice that would break a cap, and exits if the counters disagree. It writes ledger.json (records, not_found, errors, unchecked IDs) and state.json, which remembers prices and ended IDs. On a first run there is no snapshot, so every ID escalates until the cap stops it. Set OPENDATA_API_KEY, review the caps, then run python refresh.py 287070621317 301782776848. It sends real requests.
"""Refresh eBay item IDs through a card lane and a full lane under a hard cap."""
import json
import os
import sys
import requests
URL = "https://api.opendata-api.com/api/project/ebay/{op}"
KEY = os.environ["OPENDATA_API_KEY"] # never hard-code or print the key
DOMAIN = "com"
CARD_SLICE = 6 # documented card-lane size; a seventh ID is dropped
FULL_SLICE = 15 # stricter documented limit; the overview says 40
MAX_CARD = 10 # search calls per run
MAX_FULL = 30 # full-record lookups per run (one per ID)
assert CARD_SLICE <= 6 and FULL_SLICE <= 40
ledger = {"card_calls": 0, "full_lookups": 0, "records": {},
"not_found": [], "errors": [], "unchecked": []}
def slices(seq, size):
return [seq[i:i + size] for i in range(0, len(seq), size)]
def post(op, body):
# Raise short errors so the key-bearing URL never reaches logs.
try:
resp = requests.post(URL.format(op=op), params={"key": KEY}, json=body, timeout=90)
reply = resp.json() if resp.status_code == 200 else {}
except (requests.RequestException, ValueError) as exc:
raise RuntimeError(type(exc).__name__) from None
if resp.status_code != 200:
raise RuntimeError(f"HTTP {resp.status_code}")
if str(reply.get("code")) != "200":
raise RuntimeError(f"gateway code {reply.get('code')}")
result = reply.get("data")
if not isinstance(result, dict) or result.get("ok") is not True:
raise RuntimeError("operation did not report success")
return result.get("meta") or {}, result.get("data") or {}
def card_lane(ids):
seen, answered = {}, set()
for chunk in slices(ids, CARD_SLICE):
if ledger["card_calls"] >= MAX_CARD:
ledger["unchecked"].extend(chunk)
continue
ledger["card_calls"] += 1
try:
_, data = post("search", {"domain": DOMAIN, "query": "(" + ",".join(chunk) + ")"})
except RuntimeError as exc:
ledger["errors"].append({"lane": "card", "ids": chunk, "error": str(exc)})
continue
answered.update(chunk)
for card in data.get("results") or []:
if isinstance(card, dict) and card.get("item_id") is not None:
seen[str(card["item_id"])] = (card.get("price") or {}).get("value")
return seen, answered
def full_lane(ids):
for chunk in slices(ids, FULL_SLICE):
if ledger["full_lookups"] + len(chunk) > MAX_FULL:
ledger["unchecked"].extend(chunk)
continue
ledger["full_lookups"] += len(chunk) # book first; a failed call may be billed
try:
meta, data = post("items-batch", {"domain": DOMAIN, "item_ids": ",".join(chunk)})
except RuntimeError as exc:
ledger["errors"].append({"lane": "full", "ids": chunk, "error": str(exc)})
continue
if meta.get("requested") != len(chunk) or meta.get("upstream_calls") != len(chunk):
sys.exit("billing counters disagree with the chunk; stopped")
for item in data.get("items") or []:
if isinstance(item, dict) and item.get("item_id") is not None:
ledger["records"][str(item["item_id"])] = item
ledger["not_found"].extend(str(i) for i in data.get("not_found") or [])
def main():
state = {"prices": {}, "gone": []}
if os.path.exists("state.json"):
with open("state.json") as fh:
state = json.load(fh)
# Skip IDs already booked as not_found; they only burn lookups again.
ids = [i for i in dict.fromkeys(sys.argv[1:]) if i not in state["gone"]]
seen, escalate = {}, []
try:
seen, answered = card_lane(ids)
escalate = [i for i in ids if i in answered
and (seen.get(i) is None or seen[i] != state["prices"].get(i))]
full_lane(escalate)
finally:
with open("ledger.json", "w") as fh:
json.dump(ledger, fh, indent=2)
for i, p in seen.items():
if p is not None and (i not in escalate or i in ledger["records"]):
state["prices"][i] = p
for i, item in ledger["records"].items():
value = (item.get("price") or {}).get("value")
if value is not None:
state["prices"][i] = value
state["gone"] = sorted(set(state["gone"]) | set(ledger["not_found"]))
with open("state.json", "w") as fh:
json.dump(state, fh)
print(f"card {ledger['card_calls']}/{MAX_CARD}, full {ledger['full_lookups']}/{MAX_FULL}, "
f"resolved {len(ledger['records'])}, not_found {len(ledger['not_found'])}, "
f"errors {len(ledger['errors'])}, unchecked {len(ledger['unchecked'])}")
if __name__ == "__main__":
main()