Getting started
Three steps: keep your key in a variable, make a first call with GET /v1/worlds, then run the quickstart.
Before you start
- An active plan, built on the plan page and paid in Tibia Coins.
- Your key, shown only once in your panel. Keep it in an environment variable such as
TGM_API_KEY. - Nothing to type for your place: the first data call made with the key defines it (Key and place).
Base URL and authentication
Every call goes to https://data.tibiaglobalmarket.com with the key in the Authorization header:
GET /v1/worlds HTTP/1.1
Host: data.tibiaglobalmarket.com
Authorization: Bearer tgm_live_<prefix>_<secret>400 KEY_IN_QUERY and must be replaced. The API sends no CORS headers, so call it from your server or computer, not from a browser.First call: set your place
Run this on the machine that will call the API. Line 1 asks for your key and keeps it in TGM_API_KEY; line 2 calls GET /v1/worlds (1 unit), which lists the worlds and, on a key without a place, sets the place to this machine.
- 1
read -rsp "API key: " TGM_API_KEY && export TGM_API_KEY - 2
curl "https://data.tibiaglobalmarket.com/v1/worlds" -H "Authorization: Bearer $TGM_API_KEY"
- 1
$env:TGM_API_KEY = (Read-Host "API key").Trim() - 2
curl.exe "https://data.tibiaglobalmarket.com/v1/worlds" -H "Authorization: Bearer $env:TGM_API_KEY"
- 1
set /p "TGM_API_KEY=API key: " - 2
curl "https://data.tibiaglobalmarket.com/v1/worlds" -H "Authorization: Bearer %TGM_API_KEY%"
{
"data": [
{
"name": "Antica",
"pvp_type": "open",
"battleye": "yellow",
"location": "EU",
"in_plan": true,
"world_updated_at": "2026-11-17T09:12:00Z",
"data_version": "efd2cda81ebbb612",
"partial": false
}
],
"meta": {
"request_id": "req_01JD3Q6V7Y2K",
"units": 1,
"cached": false
}
}in_plan marks the worlds of your plan. If the key already has a place at another address, the call gets 403 IP_NOT_ALLOWED with the address we saw in seen_ip: run your script on the machine that holds the place, or release the place in your panel.
Quickstart
Each script downloads the whole market of one world in your plan to market-<World>.json and keeps its ETag. Run it again: if nothing changed, the answer is 304 Not Modified, for 0 units.
#!/usr/bin/env bash
# Tibia Global Market API: quickstart for bash + curl.
#
# Downloads the whole market of one world in your plan and keeps a copy in
# market-<World>.json. Run it again later: when nothing changed, the API
# answers 304 Not Modified, which costs 0 units, and the copy stays as it is.
#
# export TGM_API_KEY='...' # from your panel; never put it in a URL
# bash quickstart.sh Antica
set -u
BASE="${TGM_API_BASE:-https://data.tibiaglobalmarket.com}"
MAX_ATTEMPTS=3 # first call + 2 retries, only after 429 or 503
MAX_WAIT_SECONDS=60
WORLD="${1:-Antica}"
if [ -z "${TGM_API_KEY:-}" ]; then
echo "Set the TGM_API_KEY environment variable first." >&2
exit 2
fi
if ! [[ "$WORLD" =~ ^[A-Za-z]{2,30}$ ]]; then
echo "Not a world name: $WORLD" >&2
exit 2
fi
DATA_FILE="market-$WORLD.json"
ETAG_FILE="market-$WORLD.etag"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT
# One response header, without the trailing CR.
header() { grep -i "^$1:" "$TMP_DIR/headers" | tail -n 1 | cut -d' ' -f2- | tr -d '\r'; }
# One string field of the JSON error body (enough for problem+json; use jq for real work).
field() { tr -d '\n' < "$TMP_DIR/body" | sed -n "s/.*\"$1\" *: *\"\\([^\"]*\\)\".*/\\1/p"; }
ETAG=""
[ -f "$ETAG_FILE" ] && ETAG="$(cat "$ETAG_FILE")" # exactly as the last 200 sent it
for ATTEMPT in $(seq 1 "$MAX_ATTEMPTS"); do
ARGS=(--silent --show-error --compressed --max-time 60
--output "$TMP_DIR/body" --dump-header "$TMP_DIR/headers" --write-out '%{http_code}'
--header 'Accept: application/json' --header @-)
[ -n "$ETAG" ] && ARGS+=(--header "If-None-Match: $ETAG")
# The key goes to curl on stdin, so it never shows up in the process list.
if ! STATUS="$(printf 'Authorization: Bearer %s\n' "$TGM_API_KEY" | curl "${ARGS[@]}" "$BASE/v1/market/$WORLD")"; then
echo "Request failed." >&2
exit 1
fi
REQUEST_ID="$(header X-Request-Id)"
if [ "$STATUS" = "304" ]; then
echo "$WORLD: 304 not modified, 0 units. $DATA_FILE is still current."
exit 0
fi
if [ "$STATUS" = "200" ]; then
if ! header Content-Type | grep -qi json; then
echo "HTTP 200: the answer is not the API's JSON (request ${REQUEST_ID:--}). Stopping." >&2
exit 1
fi
cp "$TMP_DIR/body" "$DATA_FILE" # curl --compressed already removed the gzip layer
NEW_ETAG="$(header ETag)"
[ -n "$NEW_ETAG" ] && printf '%s' "$NEW_ETAG" > "$ETAG_FILE"
echo "$WORLD: saved $DATA_FILE ($(wc -c < "$DATA_FILE" | tr -d ' ') bytes), $(header X-Units-Charged) units, $(header X-Quota-Remaining) left today."
exit 0
fi
CODE=""
if header Content-Type | grep -qi json; then CODE="$(field code)"; fi
if [ -z "$CODE" ]; then
echo "HTTP $STATUS: the answer is not JSON (request ${REQUEST_ID:--}). Stopping." >&2
exit 1
fi
# Only 429 and 503 are worth another try, and only after Retry-After.
WAIT="$(header Retry-After)"
if { [ "$STATUS" = "429" ] || [ "$STATUS" = "503" ]; } && [ "$ATTEMPT" -lt "$MAX_ATTEMPTS" ] \
&& [[ "$WAIT" =~ ^[0-9]+$ ]] && [ "$WAIT" -le "$MAX_WAIT_SECONDS" ]; then
echo "HTTP $STATUS $CODE: waiting ${WAIT}s (attempt $ATTEMPT of $MAX_ATTEMPTS)." >&2
sleep "$WAIT"
continue
fi
# Anything else: stop and fix the cause. Never repeat a 401 or a 403.
echo "HTTP $STATUS $CODE: $(field detail) (request $(field request_id))" >&2
echo "See $(field docs_url)" >&2
exit 1
done
exit 1
// Tibia Global Market API: quickstart for Node.js 18+ (no dependencies).
//
// Downloads the whole market of one world in your plan and keeps a copy in
// market-<World>.json. Run it again later: when nothing changed, the API
// answers 304 Not Modified, which costs 0 units, and the copy stays as it is.
//
// export TGM_API_KEY='...' # from your panel; never put it in a URL
// node quickstart.mjs Antica
import { readFile, writeFile } from 'node:fs/promises';
const BASE = process.env.TGM_API_BASE || 'https://data.tibiaglobalmarket.com';
const MAX_ATTEMPTS = 3; // first call + 2 retries, only after 429 or 503
const MAX_WAIT_SECONDS = 60;
const apiKey = process.env.TGM_API_KEY;
const world = process.argv[2] || 'Antica';
if (!apiKey) {
console.error('Set the TGM_API_KEY environment variable first.');
process.exit(2);
}
if (!/^[A-Za-z]{2,30}$/.test(world)) {
console.error(`Not a world name: ${world}`);
process.exit(2);
}
const dataFile = `market-${world}.json`;
const etagFile = `market-${world}.etag`;
const sleep = (s) => new Promise((resolve) => setTimeout(resolve, s * 1000));
/** The problem+json body of an error, or null when the body is not JSON. */
async function readProblem(res) {
if (!/json/i.test(res.headers.get('content-type') || '')) return null;
try {
const body = await res.json();
return body && typeof body.code === 'string' ? body : null;
} catch {
return null;
}
}
async function main() {
// The ETag exactly as the last 200 sent it.
const etag = await readFile(etagFile, 'utf8').then((s) => s.trim(), () => '');
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
const headers = { Authorization: `Bearer ${apiKey}`, Accept: 'application/json' };
if (etag) headers['If-None-Match'] = etag;
const res = await fetch(`${BASE}/v1/market/${world}`, { headers });
const requestId = res.headers.get('x-request-id') || '-';
if (res.status === 304) {
console.log(`${world}: 304 not modified, 0 units. ${dataFile} is still current.`);
return 0;
}
if (res.status === 200) {
const text = await res.text(); // fetch already removed the gzip layer
let body = null;
try {
body = /json/i.test(res.headers.get('content-type') || '') ? JSON.parse(text) : null;
} catch {}
if (!body || !body.data) {
console.error(`HTTP 200: the answer is not the API's JSON (request ${requestId}). Stopping.`);
return 1;
}
await writeFile(dataFile, text);
const newEtag = res.headers.get('etag');
if (newEtag) await writeFile(etagFile, newEtag);
console.log(
`${world}: ${body.data.items.length} items, updated ${body.data.world_updated_at}, ` +
`${res.headers.get('x-units-charged')} units, ${res.headers.get('x-quota-remaining')} left today.`,
);
return 0;
}
const problem = await readProblem(res);
if (!problem) {
console.error(`HTTP ${res.status}: the answer is not JSON (request ${requestId}). Stopping.`);
return 1;
}
// Only 429 and 503 are worth another try, and only after Retry-After.
// No Retry-After header means no retry: there is no safe delay to wait.
const retryAfter = (res.headers.get('retry-after') || '').trim();
const wait = /^\d+$/.test(retryAfter) ? Number(retryAfter) : NaN;
const retryable = res.status === 429 || res.status === 503;
if (retryable && attempt < MAX_ATTEMPTS && wait <= MAX_WAIT_SECONDS) {
console.error(`HTTP ${res.status} ${problem.code}: waiting ${wait}s (attempt ${attempt} of ${MAX_ATTEMPTS}).`);
await sleep(wait);
continue;
}
// Anything else: stop and fix the cause. Never repeat a 401 or a 403.
console.error(`HTTP ${res.status} ${problem.code}: ${problem.detail} (request ${problem.request_id || requestId})`);
console.error(`See ${problem.docs_url}`);
return 1;
}
return 1;
}
try {
process.exitCode = await main();
} catch (err) {
console.error(`Request failed: ${err.cause?.message || err.message}`);
process.exitCode = 1;
}
#!/usr/bin/env python3
"""Tibia Global Market API: quickstart for Python 3.8+ (standard library only).
Downloads the whole market of one world in your plan and keeps a copy in
market-<World>.json. Run it again later: when nothing changed, the API
answers 304 Not Modified, which costs 0 units, and the copy stays as it is.
export TGM_API_KEY='...' # from your panel; never put it in a URL
python3 quickstart.py Antica
"""
import gzip
import json
import os
import re
import sys
import time
import urllib.error
import urllib.request
BASE = os.environ.get("TGM_API_BASE") or "https://data.tibiaglobalmarket.com"
MAX_ATTEMPTS = 3 # first call + 2 retries, only after 429 or 503
MAX_WAIT_SECONDS = 60
def read_body(res):
raw = res.read()
# The whole-world answer always comes gzip-compressed; urllib does not unpack it.
if (res.headers.get("Content-Encoding") or "").lower() == "gzip":
raw = gzip.decompress(raw)
return raw
def read_problem(err):
"""The problem+json body of an error, or None when the body is not JSON."""
if "json" not in (err.headers.get("Content-Type") or "").lower():
return None
try:
body = json.loads(read_body(err))
except (ValueError, OSError):
return None
return body if isinstance(body, dict) and isinstance(body.get("code"), str) else None
def main():
api_key = os.environ.get("TGM_API_KEY")
world = sys.argv[1] if len(sys.argv) > 1 else "Antica"
if not api_key:
print("Set the TGM_API_KEY environment variable first.", file=sys.stderr)
return 2
if not re.fullmatch(r"[A-Za-z]{2,30}", world):
print(f"Not a world name: {world}", file=sys.stderr)
return 2
data_file = f"market-{world}.json"
etag_file = f"market-{world}.etag"
etag = ""
if os.path.exists(etag_file):
with open(etag_file, encoding="utf-8") as f:
etag = f.read().strip() # the ETag exactly as the last 200 sent it
for attempt in range(1, MAX_ATTEMPTS + 1):
headers = {
"Authorization": f"Bearer {api_key}",
"Accept": "application/json",
"Accept-Encoding": "gzip",
"User-Agent": "tgm-quickstart-python/1.0",
}
if etag:
headers["If-None-Match"] = etag
req = urllib.request.Request(f"{BASE}/v1/market/{world}", headers=headers)
try:
with urllib.request.urlopen(req, timeout=60) as res:
body = None
if "json" in (res.headers.get("Content-Type") or "").lower():
try:
text = read_body(res).decode("utf-8")
body = json.loads(text)
except (ValueError, OSError):
body = None
if not isinstance(body, dict) or "data" not in body:
request_id = res.headers.get("X-Request-Id") or "-"
print(f"HTTP 200: the answer is not the API's JSON (request {request_id}). Stopping.", file=sys.stderr)
return 1
with open(data_file, "w", encoding="utf-8") as f:
f.write(text)
if res.headers.get("ETag"):
with open(etag_file, "w", encoding="utf-8") as f:
f.write(res.headers["ETag"])
print(
f"{world}: {len(body['data']['items'])} items, updated {body['data']['world_updated_at']}, "
f"{res.headers.get('X-Units-Charged')} units, {res.headers.get('X-Quota-Remaining')} left today."
)
return 0
except urllib.error.HTTPError as err:
# urllib reports every status that is not 2xx as an error, 304 included.
if err.code == 304:
print(f"{world}: 304 not modified, 0 units. {data_file} is still current.")
return 0
request_id = err.headers.get("X-Request-Id") or "-"
problem = read_problem(err)
if problem is None:
print(f"HTTP {err.code}: the answer is not JSON (request {request_id}). Stopping.", file=sys.stderr)
return 1
# Only 429 and 503 are worth another try, and only after Retry-After.
wait = err.headers.get("Retry-After") or ""
if err.code in (429, 503) and attempt < MAX_ATTEMPTS and wait.isdigit() and int(wait) <= MAX_WAIT_SECONDS:
print(f"HTTP {err.code} {problem['code']}: waiting {wait}s (attempt {attempt} of {MAX_ATTEMPTS}).", file=sys.stderr)
time.sleep(int(wait))
continue
# Anything else: stop and fix the cause. Never repeat a 401 or a 403.
print(
f"HTTP {err.code} {problem['code']}: {problem.get('detail')} (request {problem.get('request_id') or request_id})",
file=sys.stderr,
)
print(f"See {problem.get('docs_url')}", file=sys.stderr)
return 1
except urllib.error.URLError as err:
print(f"Request failed: {err.reason}", file=sys.stderr)
return 1
return 1
if __name__ == "__main__":
sys.exit(main())
- They read the key from
TGM_API_KEYand never print it. - On
429or503they waitRetry-Afterand retry, 3 attempts at most. - On any other error they print
code,detailanddocs_urland stop. - The whole-world answer is gzip: curl
--compressedand Nodefetchunpack it; the Python script does it by hand.
Responses
Success is JSON with data and meta: meta.units is the cost and meta.request_id identifies the call (on the whole-world answer, read the X-Request-Id header).
- Gold values are strings of digits, such as
"1450000". - Dates are ISO 8601 in UTC, ending in
Z. - Unknown values are
null; empty lists are[]. item_idis the game’s own item id.- Unknown query parameters get
400 VALIDATION_FAILED. - New fields can appear in
v1: ignore the ones you do not know.
Errors are application/problem+json: read code (Errors).
Endpoints
| Endpoint | Module | Units |
|---|---|---|
GET /v1/openapi.json | Public, no key | 0 |
GET /v1/worlds | base, included | 1 |
GET /v1/categories | base, included | 1 |
GET /v1/items?q=&category= | base, included | 1 |
GET /v1/items/{item_id} | base, included | 1 |
GET /v1/coins/resellers | base, included | 1 |
GET /v1/coins/p2p?side=&world= | base, included | 1 |
GET /v1/market/{world} | market | 10 (304: 0) |
GET /v1/market/{world}/items/{item_id} | market | 1 |
GET /v1/market/{world}/items/{item_id}/history?days= | market | 2 |
GET /v1/npc-profit?world=&min_profit= | npc-profit | 1 |
GET /v1/arbitrage?origin=&destination= | arbitrage | 1 |
GET /v1/bazaar/auctions?world=&vocation= | bazaar | 1 |
GET /v1/bazaar/auctions/{auction_id} | bazaar | 1 |
GET /v1/bazaar/characters/{name} | bazaar | 1 |
POST /v1/bazaar/characters/estimate | bazaar | 1 |
GET /v1/highscores?category=&world= | highscores | 1 |
GET /v1/highscores/characters/{name} | highscores | 1 |
GET /v1/highscores/movers?category= | highscores | 1 |
Every parameter and field: GET /v1/openapi.json (OpenAPI 3.1, no key).
Conditional requests
Send the ETag back in If-None-Match: if nothing changed you get 304 Not Modified, with no body, for 0 units. A W/ prefix is ignored.
GET /v1/worlds gives world_updated_at and in_plan for each world; call it at most once every 5 minutes.
Glossary
- Key
- The secret that identifies your account in every call, sent in
Authorization: Bearer. - Prefix
- The public first part of the key (8 characters), used to tell keys apart in your panel.
- Place
- The address the key is used from: one IPv4 address or one IPv6 /64, never both. The first data call made with the key defines it.
- Module
- A part of the API you subscribe to, such as
market.basecomes with any plan. - World in the plan
- A game world chosen for your
marketmodule, marked within_planinGET /v1/worlds. - Unit
- What a call costs against the daily quota. Most calls cost 1.
- Daily quota
- 20,000 units per key per UTC day.
- Rate limit
- 60 requests per key per minute.
- Data version
- An opaque value in
data_versionthat identifies the version of a world’s data.partialistruewhen that version is incomplete for the world. - ETag
- A tag for one version of an answer. Send it back in
If-None-Matchto get304when nothing has changed. - Request id
- The id of one call, in
X-Request-Id. Quote it when you report a problem. - Cycle
- The 30 days a plan lasts. It does not renew by itself.