文件
← 首頁
指南

客戶端範例

一個最精簡的 JavaScript 客戶端。任何能發 HTTPS 請求的語言都適用相同模式。

const BASE = "https://learnfun.metaprint.io/api/public/v1";
const TOKEN = process.env.MY_APP_TOKEN;

async function api(path, init = {}) {
  const res = await fetch(BASE + path, {
    ...init,
    headers: {
      "content-type": "application/json",
      "authorization": `Bearer ${TOKEN}`,
      ...(init.headers ?? {}),
    },
  });
  if (!res.ok) throw new Error(`API ${res.status}: ${await res.text()}`);
  return res.json();
}

// 1. 探索 schema
const { tables } = await api("/schema");

// 2. 把目前使用者 upsert 進 people
await api("/people", {
  method: "POST",
  body: JSON.stringify({
    matchKey: "email",
    person: { full_name: "Ada", email: "ada@example.com" },
  }),
});

// 3. 寫一筆資料列
await api("/tables/quiz_results/rows", {
  method: "POST",
  body: JSON.stringify({ data: { student_id: "S001", score: 87 } }),
});