Joplin 中文网 v3.3.4 已更新(2026-07-15)—— 新增富文本编辑器改进,优化同步性能,立即更新

Joplin API自动化操作入门:用脚本管理你的笔记

立即下载Joplin 中文网 全平台支持 · 官方最新版

什么是Joplin API

Joplin提供了两套自动化接口:

  1. Web Data API:基于HTTP协议的RESTful API,可被任何编程语言调用
  2. Joplin CLI:命令行工具,封装了常用的API调用

通过这些接口,你可以:

一、开启Web Data API

启用API服务

  1. 打开Joplin桌面客户端
  2. 进入 工具 → 选项 → Joplin Web Clipper
  3. 开启 “Enable Joplin Web Clipper Service” 选项
  4. 记录显示的端口(默认 41184)和API Token
  5. 点击“Check service status”验证服务正常

验证API可访问

使用curl测试API:

curl -X GET http://127.0.0.1:41184/ping?token=YOUR_TOKEN

返回 JoplinClipperServer 表示服务正常。

安全建议

二、Joplin CLI安装

安装方法

Joplin CLI是Node.js包,通过npm安装:

npm install -g joplin

验证安装

joplin --version

CLI配置

CLI默认会连接本地的Joplin Web Clipper服务。如果使用远程Joplin实例,可通过环境变量配置:

export JOPLIN_WEBCLIPPER_HOST=192.168.1.100
export JOPLIN_WEBCLIPPER_PORT=41184

三、API核心操作实战

1. 查询所有笔记本

curl http://127.0.0.1:41184/notebooks?token=YOUR_TOKEN | jq '.[] | .title'

返回示例:

"工作"
"学习笔记"
"生活"
"归档"

2. 在指定笔记本下创建笔记

使用 notes 端点:

curl -X POST http://127.0.0.1:41184/notes?token=YOUR_TOKEN \
  -H "Content-Type: application/json" \
  -d '{
    "title": "自动化笔记标题",
    "body": "# 标题\n\n这是通过API创建的笔记内容",
    "parent_id": "笔记本ID"
  }'

3. 更新笔记内容

curl -X PUT http://127.0.0.1:41184/notes/笔记ID?token=YOUR_TOKEN \
  -H "Content-Type: application/json" \
  -d '{
    "title": "新标题",
    "body": "更新后的内容"
  }'

4. 删除笔记

curl -X DELETE http://127.0.0.1:41184/notes/笔记ID?token=YOUR_TOKEN

5. 查询笔记列表

支持丰富的过滤条件:

# 查询最近修改的10条笔记
curl "http://127.0.0.1:41184/notes?token=YOUR_TOKEN&limit=10&order_by=updated_time&order_dir=DESC" | jq '.'

# 按标题搜索
curl "http://127.0.0.1:41184/notes?token=YOUR_TOKEN&query=关键词" | jq '.[] | .title'

6. 标签管理

# 添加标签到笔记
curl -X POST "http://127.0.0.1:41184/tags/笔记ID?token=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"tags": ["重要", "项目A"]}'

# 列出所有标签
curl "http://127.0.0.1:41184/tags?token=YOUR_TOKEN" | jq '.'

# 创建新标签
curl -X POST "http://127.0.0.1:41184/tags?token=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title": "新标签"}'

四、Python自动化脚本示例

环境准备

pip install requests

脚本示例:批量创建周报笔记

import requests
from datetime import datetime, timedelta

BASE_URL = "http://127.0.0.1:41184"
TOKEN = "YOUR_API_TOKEN"

def create_note(title, body, notebook_id):
    """创建笔记"""
    url = f"{BASE_URL}/notes?token={TOKEN}"
    payload = {
        "title": title,
        "body": body,
        "parent_id": notebook_id
    }
    response = requests.post(url, json=payload)
    return response.json()

def get_notebook_id(name):
    """获取笔记本ID"""
    url = f"{BASE_URL}/notebooks?token={TOKEN}&query={name}"
    notebooks = requests.get(url).json()
    return notebooks[0]['id'] if notebooks else None

# 主程序
if __name__ == "__main__":
    weekly_notebook_id = get_notebook_id("周报")
    
    # 创建过去8周的周报模板
    for i in range(8, 0, -1):
        week_end = datetime.now() - timedelta(weeks=i)
        title = f"周报 - {week_end.strftime('%Y年第%W周')}"
        body = f"""# {title}

## 本周完成
- [ ] 任务1
- [ ] 任务2

## 下周计划
- [ ] 计划1
- [ ] 计划2

## 问题与反思
"""
        note = create_note(title, body, weekly_notebook_id)
        print(f"已创建: {note['title']}")

脚本示例:从RSS自动导入文章

import feedparser
import requests

def fetch_and_save(rss_url, notebook_id):
    """抓取RSS并保存为笔记"""
    feed = feedparser.parse(rss_url)
    
    for entry in feed.entries[:10]:  # 取最新10条
        title = entry.title
        link = entry.link
        content = entry.summary if hasattr(entry, 'summary') else entry.description
        
        body = f"""# {title}

**来源**: [{link}]({link})

**发布时间**: {entry.get('published', '未知')}

---

{content}
"""
        # 调用API创建笔记
        url = f"http://127.0.0.1:41184/notes?token=YOUR_TOKEN"
        requests.post(url, json={
            "title": f"[RSS] {title}",
            "body": body,
            "parent_id": notebook_id
        })

# 使用示例
notebook_id = "YOUR_NOTEBOOK_ID"
rss_sources = [
    "https://hnrss.org/newest",
    "https://www.ruanyifeng.com/blog/atom.xml"
]

for rss in rss_sources:
    fetch_and_save(rss, notebook_id)

五、JavaScript/Node.js集成

使用axios调用API

const axios = require('axios');

const BASE_URL = 'http://127.0.0.1:41184';
const TOKEN = 'YOUR_API_TOKEN';

class JoplinAPI {
  constructor(baseURL, token) {
    this.client = axios.create({
      baseURL: baseURL,
      params: { token }
    });
  }
  
  // 获取所有笔记本
  async getNotebooks() {
    const { data } = await this.client.get('/notebooks');
    return data;
  }
  
  // 创建笔记
  async createNote({ title, body, parentId, tags = [] }) {
    const note = await this.client.post('/notes', {
      title,
      body,
      parent_id: parentId
    });
    
    // 添加标签
    if (tags.length > 0) {
      await this.client.post(`/tags/${note.data.id}`, { tags });
    }
    
    return note.data;
  }
  
  // 搜索笔记
  async searchNotes(query) {
    const { data } = await this.client.get('/search', { params: { query } });
    return data;
  }
  
  // 导出笔记为Markdown文件
  async exportNote(noteId, format = 'md') {
    const { data } = await this.client.get(`/notes/${noteId}/${format === 'md' ? 'note' : ''}`);
    return data;
  }
}

// 使用示例
const joplin = new JoplinAPI(BASE_URL, TOKEN);

(async () => {
  const notebooks = await joplin.getNotebooks();
  console.log('笔记本:', notebooks.map(nb => nb.title));
  
  await joplin.createNote({
    title: '自动化创建的笔记',
    body: '# 这是内容\n\n支持**Markdown**',
    parentId: notebooks[0].id,
    tags: ['自动化', 'API']
  });
})();

六、Shell脚本实战案例

案例1:每日日志自动生成

#!/bin/bash
# daily_note.sh - 创建当日工作日志

TOKEN="YOUR_TOKEN"
NOTEBOOK_ID="笔记本ID"
DATE=$(date +%Y-%m-%d)
TITLE="${DATE} 工作日志"

BODY="# ${TITLE}

## 今日待办
- [ ]

## 工作记录

## 明日计划
- [ ]

## 总结与反思
"

curl -X POST "http://127.0.0.1:41184/notes?token=${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"title\": \"${TITLE}\",
    \"body\": $(echo "$BODY" | jq -Rs .),
    \"parent_id\": \"${NOTEBOOK_ID}\"
  }"

echo "✓ ${TITLE} 创建成功"

添加到crontab,每天18:00自动执行:

0 18 * * * /path/to/daily_note.sh

案例2:批量重命名笔记

#!/bin/bash
# rename_notes.sh - 按规则批量重命名

TOKEN="YOUR_TOKEN"
NOTEBOOK_ID="目标笔记本ID"

# 获取笔记列表
NOTES=$(curl -s "http://127.0.0.1:41184/notes?token=${TOKEN}&parent_id=${NOTEBOOK_ID}")

echo "$NOTES" | jq -c '.[]' | while read -r note; do
  ID=$(echo "$note" | jq -r '.id')
  OLD_TITLE=$(echo "$note" | jq -r '.title')
  NEW_TITLE="[重构] ${OLD_TITLE}"
  
  curl -X PUT "http://127.0.0.1:41184/notes/${ID}?token=${TOKEN}" \
    -H "Content-Type: application/json" \
    -d "{\"title\": \"${NEW_TITLE}\"}"
  
  echo "✓ 重命名: ${OLD_TITLE} → ${NEW_TITLE}"
done

七、常见应用场景

1. 读书笔记自动化

def import_book_notes(book_title, chapters, highlights):
    """导入读书笔记"""
    notebook_id = get_notebook_id("读书笔记")
    
    for chapter in chapters:
        body = f"# {chapter['title']}\n\n{chapter['content']}\n\n## 重点摘录\n\n"
        for h in highlights.get(chapter['title'], []):
            body += f"> {h}\n\n"
        
        create_note(f"{book_title} - {chapter['title']}", body, notebook_id)

2. Git Commit自动记录

# git hook: post-commit
COMMIT_MSG=$(git log -1 --pretty=%B)
BRANCH=$(git branch --show-current)

curl -X POST "http://127.0.0.1:41184/notes?token=${TOKEN}" \
  -H "Content-Type: application/json" \
  -d "{
    \"title\": \"[Git] ${BRANCH} - $(date +%H:%M)\",
    \"body\": \"## 提交信息\n\n${COMMIT_MSG}\",
    \"parent_id\": \"${DEV_NOTEBOOK}\"
  }"

3. 从其他笔记软件迁移

def migrate_from_evernote(evernote_export_xml):
    """从Evernote ENEX导入"""
    import xml.etree.ElementTree as ET
    
    tree = ET.parse(evernote_export_xml)
    root = tree.getroot()
    
    for note in root.findall('note'):
        title = note.find('title').text
        content = note.find('content').text
        
        # 转换为Markdown(HTML→MD)
        markdown_content = html_to_markdown(content)
        
        create_note(title, markdown_content, "迁移笔记本ID")

八、最佳实践与注意事项

API限制

数据安全

  1. 定期备份:通过API导出所有笔记
  2. Token管理:使用环境变量存储,不要硬编码
  3. 错误处理:网络中断时实现重试机制
  4. 日志记录:关键操作记录到日志文件

性能优化

# 批量操作示例
def batch_create_notes(notes_data, batch_size=50):
    """分批创建笔记"""
    for i in range(0, len(notes_data), batch_size):
        batch = notes_data[i:i+batch_size]
        with ThreadPoolExecutor(max_workers=5) as executor:
            executor.map(create_note_from_data, batch)
        time.sleep(1)  # 批次间暂停

九、调试技巧

开启Joplin日志

  1. 工具 → 选项 → 高级 → Show Advanced Settings
  2. 设置 debug.websocket 和 debug.webClipper 为 true
  3. 重启Joplin查看详细日志

使用Postman测试

  1. 创建新请求,URL为 http://127.0.0.1:41184
  2. 在Params中添加 token=YOUR_TOKEN
  3. 选择Method(GET/POST/PUT/DELETE)
  4. 在Body中填入JSON数据

十、总结

Joplin API为自动化笔记管理打开了无限可能:

建议从简单场景入手(如每日日志自动生成),逐步扩展到复杂的数据管道。Joplin的开源特性意味着你可以基于API构建完全属于自己的笔记系统。

相关资源

这篇教程有帮助吗?立即下载Joplin 中文网试试吧!

全平台支持 · 安全无毒 · 官方最新版