Skip to content

您的第一个脚本 ​

只需约五分钟,您就能通过脚本创建一条笔记、安全地更新它,并把它移入废纸篓。

开始之前 ​

  1. 在 PalmNotes 中打开 设置 → 开发者,创建一个具有 notes:read 和 notes:write 权限范围的令牌。
  2. 把它保存在名为 PALMNOTES_TOKEN 的环境变量中。切勿粘贴到代码里,也不要提交到仓库。

脚本 ​

js
// first-script.mjs (Node 22+)
// Run: PALMNOTES_TOKEN=pn_pat_… node first-script.mjs
const BASE = 'https://notes-api.palmcode.cl/api/v1';
const auth = { Authorization: `Bearer ${process.env.PALMNOTES_TOKEN}`, 'Content-Type': 'application/json' };

async function api(path, init = {}) {
  for (let attempt = 0; attempt < 4; attempt++) {
    const res = await fetch(BASE + path, { ...init, headers: { ...auth, ...init.headers } });
    if (res.status === 429) { // rate limited: back off 1s, 2s, 4s…
      await new Promise((r) => setTimeout(r, 2 ** attempt * 1000));
      continue;
    }
    if (!res.ok) throw new Error(`${res.status} ${JSON.stringify(await res.json())}`);
    return res.status === 204 ? null : res.json();
  }
  throw new Error('Still rate limited, try again later');
}

const { data: note } = await api('/notes', {
  method: 'POST',
  body: JSON.stringify({ title: 'My first API note', content_markdown: '# Hello\n\nCreated from a script.', tags: ['api'] }),
});
console.log('created', note.id);

const { data: updated } = await api(`/notes/${note.id}`, {
  method: 'PATCH',
  headers: { 'If-Match': note.version },
  body: JSON.stringify({ content_markdown: '# Hello\n\nUpdated from a script.' }),
});
console.log('updated, new version', updated.version);

await api(`/notes/${note.id}`, { method: 'DELETE' }); // moves it to the trash
console.log('moved to trash');
python
# first_script.py (pip install requests)
# Run: PALMNOTES_TOKEN=pn_pat_… python first_script.py
import os, time, requests

BASE = "https://notes-api.palmcode.cl/api/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['PALMNOTES_TOKEN']}"}

def api(method, path, headers=None, **kwargs):
    for attempt in range(4):
        r = requests.request(method, BASE + path, headers={**HEADERS, **(headers or {})}, **kwargs)
        if r.status_code == 429:  # rate limited: back off 1s, 2s, 4s…
            time.sleep(2 ** attempt)
            continue
        r.raise_for_status()
        return None if r.status_code == 204 else r.json()
    raise RuntimeError("Still rate limited, try again later")

note = api("POST", "/notes", json={"title": "My first API note", "content_markdown": "# Hello\n\nCreated from a script.", "tags": ["api"]})["data"]
print("created", note["id"])

updated = api("PATCH", f"/notes/{note['id']}", headers={"If-Match": note["version"]}, json={"content_markdown": "# Hello\n\nUpdated from a script."})["data"]
print("updated, new version", updated["version"])

api("DELETE", f"/notes/{note['id']}")  # moves it to the trash
print("moved to trash")

它做了什么 ​

  1. 用 Markdown 创建一条笔记,并读取它的 id 和 version。
  2. 把 version 作为 If-Match 发送来更新它。如果期间有人编辑过这条笔记,API 会返回 409 version_conflict,而不是覆盖他们的修改。
  3. 删除它。默认是移入废纸篓,因此不会丢失任何内容。
  4. 当 API 返回 429 时退避重试(参见错误与速率限制)。

下一步 ​

  • 使用游标遍历全部笔记,见使用笔记。
  • 用 Webhook 响应变化,而不是反复轮询。
  • 不再需要时,请在 设置 → 开发者 中撤销该令牌。