Primeiros passos
Três passos: guarde a chave numa variável, faça a primeira chamada com GET /v1/worlds e rode o exemplo pronto.
Antes de começar
- Um plano ativo, montado na página de planos e pago em Tibia Coins.
- A sua chave, mostrada uma única vez no painel. Guarde-a numa variável de ambiente, como
TGM_API_KEY. - Nada a digitar para o lugar: a primeira chamada de dados feita com a chave define o lugar (Chave e lugar).
URL base e autenticação
Toda chamada vai para https://data.tibiaglobalmarket.com com a chave no cabeçalho Authorization:
GET /v1/worlds HTTP/1.1
Host: data.tibiaglobalmarket.com
Authorization: Bearer tgm_live_<prefix>_<secret>400 KEY_IN_QUERY e precisa ser trocada. A API não manda cabeçalhos de CORS, então chame do seu servidor ou computador, não do navegador.Primeira chamada: defina o seu lugar
Rode isto na máquina que vai chamar a API. A linha 1 pede a chave e guarda em TGM_API_KEY; a linha 2 chama GET /v1/worlds (1 unidade), que lista os mundos e, numa chave ainda sem lugar, define o lugar nesta máquina.
- 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 marca os mundos do seu plano. Se a chave já tiver lugar em outro endereço, a chamada recebe 403 IP_NOT_ALLOWED com o endereço que vimos em seen_ip: rode o script na máquina que ocupa o lugar, ou libere o lugar no painel.
Exemplo pronto
Cada script baixa o mercado inteiro de um mundo do seu plano para market-<World>.json e guarda o ETag. Rode de novo: se nada mudou, a resposta é 304 Not Modified, por 0 unidades.
#!/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())
- Leem a chave de
TGM_API_KEYe nunca a imprimem. - Diante de
429ou503, esperam oRetry-Aftere tentam de novo, no máximo 3 vezes. - Diante de qualquer outro erro, mostram
code,detailedocs_urle param. - A resposta do mundo inteiro vem em gzip: o curl com
--compressede ofetchdo Node descompactam sozinhos; o script em Python faz isso à mão.
Respostas
O sucesso é um JSON com data e meta: meta.units é o custo e meta.request_id identifica a chamada (na resposta do mundo inteiro, leia o cabeçalho X-Request-Id).
- Valores em gold são strings de dígitos, como
"1450000". - Datas seguem a ISO 8601, em UTC, e terminam em
Z. - Valor desconhecido vem como
null; lista vazia, como[]. item_idé o id do item no próprio jogo.- Parâmetro de query desconhecido recebe
400 VALIDATION_FAILED. - Campos novos podem aparecer na
v1: ignore os que você não conhece.
Os erros vêm como application/problem+json: leia o code (Erros).
Endpoints
| Endpoint | Módulo | Unidades |
|---|---|---|
GET /v1/openapi.json | Público, sem chave | 0 |
GET /v1/worlds | base, incluso | 1 |
GET /v1/categories | base, incluso | 1 |
GET /v1/items?q=&category= | base, incluso | 1 |
GET /v1/items/{item_id} | base, incluso | 1 |
GET /v1/coins/resellers | base, incluso | 1 |
GET /v1/coins/p2p?side=&world= | base, incluso | 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 |
Todos os parâmetros e campos: GET /v1/openapi.json (OpenAPI 3.1, sem chave).
Requisições condicionais
Devolva o ETag em If-None-Match: se nada mudou, você recebe 304 Not Modified, sem corpo, por 0 unidades. O prefixo W/ é ignorado.
GET /v1/worlds traz world_updated_at e in_plan de cada mundo; consulte no máximo uma vez a cada 5 minutos.
Glossário
- Chave
- O segredo que identifica a sua conta em cada chamada, enviado em
Authorization: Bearer. - Prefixo
- A parte pública do início da chave (8 caracteres), que distingue as chaves no painel.
- Lugar
- O endereço de onde a chave é usada: um IPv4 ou um /64 IPv6, nunca os dois. A primeira chamada de dados feita com a chave define o lugar.
- Módulo
- Uma parte da API que você contrata, como
market. Obasevem com qualquer plano. - Mundo do plano
- Um mundo do jogo escolhido para o seu módulo
market, marcado comin_planemGET /v1/worlds. - Unidade
- O quanto uma chamada gasta da cota diária. A maioria das chamadas custa 1.
- Cota diária
- 20.000 unidades por chave por dia UTC.
- Limite por minuto
- 60 requisições por chave por minuto.
- Versão dos dados
- Um valor opaco em
data_versionque identifica a versão dos dados de um mundo.partialétruequando essa versão está incompleta para o mundo. - ETag
- Uma etiqueta de uma versão da resposta. Devolva-a em
If-None-Matchpara receber304quando nada mudou. - Id da requisição
- O id de uma chamada, em
X-Request-Id. Informe-o ao relatar um problema. - Ciclo
- Os 30 dias que um plano dura. Ele não se renova sozinho.