跳到內容
主控台

快速開始

這頁用最少的步驟帶你呼叫 ExpTech API:先打一個不需要驗證的 HTTP API,再建立 API Token,最後開啟一條即時串流。使用前請先閱讀使用規範與服務條款。

  1. 呼叫第一個 API

    地震報告目前不需要 token。下面取得最近 5 筆中央氣象署地震報告:

    終端機視窗
    curl -sL "https://api.core.exptech.dev/api/v2/eq/report?limit=5"
    const res = await fetch("https://api.core.exptech.dev/api/v2/eq/report?limit=5");
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    const reports = await res.json();
    console.log(reports[0].loc, reports[0].mag);

    回應是 JSON 陣列,每筆是一則地震報告,欄位說明見地震報告。

    其他 host 與節點見伺服器與 Base URL。正式上線前,建議照該頁的做法在用戶端準備備援 host。

  2. 建立 API Token

    需要驗證的 API 與帶有用量紀錄的串流要用 API Token:

    • 登入 https://manager.exptech.com.tw/login(輸入電子郵件,點信中的登入連結)。
    • 到主控台的 API Token 頁面,選擇權限後建立。
    • Token 只會顯示一次,請立刻存起來。格式是 et_ 開頭的字串。

    權限的意義見權限,帶法與撤銷見 API Token。

  3. 開啟即時串流

    即時資料以 SSE(Server-Sent Events)傳送。下面連到地震報告串流 eq.report.v1:有新的地震報告時,伺服器會推送一則訊息。

    終端機視窗
    curl -N -H "Authorization: Bearer et_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" \
    "https://api.lb.exptech.dev/api/v1/trem/sse/report"

    瀏覽器的 EventSource 不能帶 header,token 要放在 query。每則資料是 gzip 壓縮後再 base64 編碼,要先解碼:

    const token = "et_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    const es = new EventSource(
    `https://api.lb.exptech.dev/api/v1/trem/sse/report?token=${encodeURIComponent(token)}`,
    );
    async function decode(base64) {
    const bytes = Uint8Array.from(atob(base64), (c) => c.charCodeAt(0));
    const stream = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip"));
    return JSON.parse(await new Response(stream).text());
    }
    es.onmessage = async (event) => {
    console.log(await decode(event.data));
    };

    eq.report.v1 是公開 topic,不帶 token 也能連;帶了 token 時,用量會計入你的帳號,可在主控台的用量統計查看。需要權限的 topic 則要求 token 有對應權限,而且帳號已在主控台的訂閱管理訂閱該資源,否則會被拒絕。訂閱與配額的計算見用量與配額。

    連線開頭的 event: info、每 60 秒的心跳、多個 topic 共用一條連線的寫法與重連方式,見即時串流。

  4. 下一步