Pierwsze kroki
Trzy kroki: zapisz klucz w zmiennej, wykonaj pierwsze wywołanie GET /v1/worlds i uruchom gotowy przykład.
Zanim zaczniesz
- Aktywny plan, skonfigurowany na stronie planów i opłacony w Tibia Coins.
- Twój klucz, pokazywany w panelu tylko raz. Trzymaj go w zmiennej środowiskowej, np.
TGM_API_KEY. - Miejsca nigdzie nie wpisujesz: ustala je pierwsze wywołanie danych wykonane kluczem (Klucz i miejsce).
Adres bazowy i uwierzytelnianie
Każde wywołanie trafia do https://data.tibiaglobalmarket.com z kluczem w nagłówku Authorization:
GET /v1/worlds HTTP/1.1
Host: data.tibiaglobalmarket.com
Authorization: Bearer tgm_live_<prefix>_<secret>400 KEY_IN_QUERY i trzeba go wymienić. API nie wysyła nagłówków CORS, więc wywołuj je ze swojego serwera lub komputera, nie z przeglądarki.Pierwsze wywołanie: ustal swoje miejsce
Uruchom to na maszynie, która będzie wywoływać API. Linia 1 prosi o klucz i zapisuje go w TGM_API_KEY; linia 2 wywołuje GET /v1/worlds (1 jednostka), które zwraca listę światów i, przy kluczu bez miejsca, ustala miejsce na tej maszynie.
- 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 oznacza światy z Twojego planu. Jeśli klucz ma już miejsce pod innym adresem, wywołanie dostaje 403 IP_NOT_ALLOWED, a seen_ip podaje adres, który widzieliśmy: uruchom skrypt na maszynie, która zajmuje miejsce, albo zwolnij miejsce w panelu.
Gotowy przykład
Każdy skrypt pobiera cały rynek jednego świata z Twojego planu do market-<World>.json i zachowuje jego ETag. Uruchom go ponownie: jeśli nic się nie zmieniło, odpowiedź to 304 Not Modified, za 0 jednostek.
#!/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())
- Odczytują klucz z
TGM_API_KEYi nigdy go nie wypisują. - Po
429lub503czekająRetry-Afteri ponawiają, najwyżej 3 razy. - Przy każdym innym błędzie wypisują
code,detailidocs_urli kończą działanie. - Odpowiedź z całym światem jest w gzipie: curl z
--compressedifetchw Node rozpakowują ją same; skrypt w Pythonie robi to ręcznie.
Odpowiedzi
Sukces to JSON z data i meta: meta.units to koszt, a meta.request_id identyfikuje wywołanie (przy całym świecie czytaj nagłówek X-Request-Id).
- Wartości w złocie to ciągi cyfr, np.
"1450000". - Daty są w ISO 8601, w UTC, i kończą się na
Z. - Nieznana wartość to
null; pusta lista to[]. item_idto identyfikator przedmiotu nadany przez grę.- Nieznany parametr zapytania dostaje
400 VALIDATION_FAILED. - W
v1mogą pojawiać się nowe pola: ignoruj te, których nie znasz.
Błędy przychodzą jako application/problem+json: czytaj code (Błędy).
Endpointy
| Endpoint | Moduł | Jednostki |
|---|---|---|
GET /v1/openapi.json | Publiczny, bez klucza | 0 |
GET /v1/worlds | base, w cenie | 1 |
GET /v1/categories | base, w cenie | 1 |
GET /v1/items?q=&category= | base, w cenie | 1 |
GET /v1/items/{item_id} | base, w cenie | 1 |
GET /v1/coins/resellers | base, w cenie | 1 |
GET /v1/coins/p2p?side=&world= | base, w cenie | 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 |
Wszystkie parametry i pola: GET /v1/openapi.json (OpenAPI 3.1, bez klucza).
Zapytania warunkowe
Odeślij ETag w If-None-Match: jeśli nic się nie zmieniło, dostaniesz 304 Not Modified, bez treści, za 0 jednostek. Prefiks W/ jest ignorowany.
GET /v1/worlds podaje world_updated_at i in_plan każdego świata; wywołuj go najwyżej raz na 5 minut.
Słowniczek
- Klucz
- Sekret, który identyfikuje Twoje konto w każdym wywołaniu, wysyłany w
Authorization: Bearer. - Prefiks
- Jawny początek klucza (8 znaków), który odróżnia klucze w panelu.
- Miejsce
- Adres, z którego używany jest klucz: jeden adres IPv4 albo jeden /64 IPv6, nigdy oba. Ustala je pierwsze wywołanie danych wykonane kluczem.
- Moduł
- Część API, którą wykupujesz, np.
market.basejest w każdym planie. - Świat w planie
- Świat gry wybrany do modułu
market, oznaczony przezin_planwGET /v1/worlds. - Jednostka
- Tyle wywołanie zużywa z dziennego limitu. Większość wywołań kosztuje 1.
- Limit dzienny
- 20 000 jednostek na klucz na dzień UTC.
- Limit na minutę
- 60 zapytań na klucz na minutę.
- Wersja danych
- Nieprzezroczysta wartość w
data_version, która identyfikuje wersję danych świata.partialma wartośćtrue, gdy ta wersja jest niepełna dla świata. - ETag
- Znacznik jednej wersji odpowiedzi. Odeślij go w
If-None-Match, aby dostać304, gdy nic się nie zmieniło. - Id wywołania
- Identyfikator jednego wywołania, w
X-Request-Id. Podawaj go, zgłaszając problem. - Cykl
- 30 dni, przez które trwa plan. Nie odnawia się sam.