Obsidian REST API 调用指南

Obsidian REST API 调用指南

更新日期: 2026-03-14 文档版本: 1.0 插件: Local REST API


目录

  1. 插件概述
  2. 安装配置
  3. 认证方式
  4. API 端点详解
  5. 调用示例
  6. 脚本自动化
  7. 与其他工具集成

一、插件概述

1.1 什么是 Local REST API?

Local REST API 是 Obsidian 的社区插件,为 Obsidian 提供完整的 REST API 接口:

特性 说明
协议 HTTPS(自签名证书)
认证 API Key
端口 默认 27124
下载量 260,000+

1.2 能做什么?

┌─────────────────────────────────────────────────────────────┐
│                Local REST API 功能                           │
├─────────────────────────────────────────────────────────────┤
│                                                             │
│  📝 笔记操作                                                 │
│     ├── 读取笔记内容                                         │
│     ├── 创建新笔记                                           │
│     ├── 更新笔记内容                                         │
│     ├── 删除笔记                                             │
│     └── 追加内容到笔记                                       │
│                                                             │
│  📂 文件夹操作                                               │
│     ├── 列出文件夹内容                                       │
│     └── 遍历仓库结构                                         │
│                                                             │
│  🔄 周期性笔记                                               │
│     ├── 日记/周记/月记                                       │
│     └── 按日期操作                                           │
│                                                             │
│  🔍 搜索                                                     │
│     ├── 全文搜索                                             │
│     └── 简单文本搜索                                         │
│                                                             │
│  ⚡ 命令执行                                                 │
│     ├── 获取命令列表                                         │
│     └── 执行命令                                             │
│                                                             │
└─────────────────────────────────────────────────────────────┘

二、安装配置

2.1 安装插件

  1. 打开 Obsidian 设置 → 第三方插件
  2. 浏览社区插件
  3. 搜索 "Local REST API"
  4. 安装并启用

2.2 获取 API Key

  1. 打开设置 → Local REST API
  2. 找到 API Key 字段
  3. 复制保存 API Key
┌─────────────────────────────────────────┐
│  Local REST API 设置                     │
├─────────────────────────────────────────┤
│                                         │
│  API Key: ***************************** │
│  [重新生成]                             │
│                                         │
│  Host: 127.0.0.1                        │
│  Port: 27124                            │
│                                         │
│  ☑ 启用 HTTPS                           │
│  ☑ 启用 API                             │
│                                         │
└─────────────────────────────────────────┘

2.3 证书信任

首次使用会生成自签名证书,需要添加信任:

macOS:

# 导出证书
curl -k https://127.0.0.1:27124/obsidian-local-rest-api.crt -o obsidian.crt

# 添加到钥匙串
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain obsidian.crt

或直接在浏览器访问:

https://127.0.0.1:27124/

然后手动信任证书。


三、认证方式

3.1 请求头认证

所有 API 请求必须携带 API Key:

curl -X GET https://127.0.0.1:27124/ \
  -H "Authorization: Bearer YOUR_API_KEY"

3.2 交互式文档认证

访问 https://127.0.0.1:27124/ 打开 Swagger UI:

  1. 点击 Authorize 按钮
  2. 输入 API Key
  3. 点击 Authorize 确认

四、API 端点详解

4.1 基础 URL

https://127.0.0.1:27124

4.2 系统端点

端点 方法 说明
/ GET 获取服务器信息
/openapi.yaml GET 获取 OpenAPI 文档
/obsidian-local-rest-api.crt GET 获取证书

4.3 当前文件端点 (/active)

端点 方法 说明
/active/ GET 获取当前打开文件的内容
/active/ POST 追加内容到当前文件
/active/ PUT 替换当前文件内容
/active/ PATCH 部分更新当前文件
/active/ DELETE 删除当前文件

4.4 仓库文件端点 (/vault)

端点 方法 说明
/vault/ GET 列出根目录文件
/vault/{path} GET 获取指定文件内容
/vault/{path} PUT 创建或替换文件
/vault/{path} POST 追加内容到文件
/vault/{path} PATCH 部分更新文件
/vault/{path} DELETE 删除文件
/vault/{dir}/ GET 列出目录内容

4.5 周期性笔记端点 (/periodic)

端点 方法 说明
/periodic/{period}/ GET 获取当前周期笔记
/periodic/{period}/ POST 追加到当前周期笔记
/periodic/{period}/{year}/{month}/{day}/ GET 获取指定日期笔记

period 可选值: daily, weekly, monthly, quarterly, yearly

端点 方法 说明
/search/ POST 高级搜索
/search/simple/ POST 简单文本搜索

4.7 命令端点 (/commands)

端点 方法 说明
/commands/ GET 获取所有可用命令
/commands/{commandId}/ POST 执行指定命令

4.8 打开文件端点 (/open)

端点 方法 说明
/open/{filename} POST 在 Obsidian 中打开文件

五、调用示例

5.1 获取服务器信息

curl -X GET https://127.0.0.1:27124/ \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -k

响应:

{
  "obsidianVersion": "1.5.0",
  "pluginVersion": "3.4.6"
}

5.2 创建新笔记

curl -X PUT "https://127.0.0.1:27124/vault/Notes/NewNote.md" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: text/markdown" \
  -k \
  -d "# 新笔记

这是通过 API 创建的笔记内容。

## 标题二

更多内容..."

5.3 读取笔记内容

curl -X GET "https://127.0.0.1:27124/vault/Notes/NewNote.md" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -k

响应:

# 新笔记

这是通过 API 创建的笔记内容。

## 标题二

更多内容...

5.4 追加内容到笔记

curl -X POST "https://127.0.0.1:27124/vault/Notes/NewNote.md" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: text/markdown" \
  -k \
  -d "

## 追加的内容

这部分是通过 POST 请求追加的。"

5.5 部分更新笔记 (PATCH)

# 在指定位置插入内容
curl -X PATCH "https://127.0.0.1:27124/vault/Notes/NewNote.md" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -k \
  -d '{
    "operation": "append",
    "target": "heading",
    "targetValue": "标题二",
    "content": "\n这是插入到标题二下方的内容"
  }'

5.6 列出目录内容

curl -X GET "https://127.0.0.1:27124/vault/Notes/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -k

响应:

{
  "files": [
    "NewNote.md",
    "AnotherNote.md"
  ],
  "folders": [
    "SubFolder"
  ]
}

5.7 搜索笔记

# 简单搜索
curl -X POST "https://127.0.0.1:27124/search/simple/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -k \
  -d '{
    "query": "关键词"
  }'
# 高级搜索
curl -X POST "https://127.0.0.1:27124/search/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -k \
  -d '{
    "query": "tag:#工作",
    "contextLength": 100
  }'

5.8 获取周期性笔记

# 获取今日日记
curl -X GET "https://127.0.0.1:27124/periodic/daily/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -k

# 获取指定日期日记
curl -X GET "https://127.0.0.1:27124/periodic/daily/2026/03/14/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -k

5.9 追加到今日日记

curl -X POST "https://127.0.0.1:27124/periodic/daily/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: text/markdown" \
  -k \
  -d "

## 14:30 会议记录

- 讨论了项目进度
- 下周需要完成原型
"

5.10 执行命令

# 获取命令列表
curl -X GET "https://127.0.0.1:27124/commands/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -k

# 执行命令
curl -X POST "https://127.0.0.1:27124/commands/editor:save-file/" \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -k

六、脚本自动化

6.1 Python 脚本示例

#!/usr/bin/env python3
"""
Obsidian REST API Python 客户端
"""

import requests
from datetime import datetime

class ObsidianClient:
    def __init__(self, api_key: str, host: str = "127.0.0.1", port: int = 27124):
        self.base_url = f"https://{host}:{port}"
        self.headers = {"Authorization": f"Bearer {api_key}"}
        self.verify = False  # 自签名证书

    def _request(self, method: str, endpoint: str, **kwargs):
        url = f"{self.base_url}{endpoint}"
        kwargs["headers"] = {**self.headers, **kwargs.get("headers", {})}
        kwargs["verify"] = self.verify
        response = requests.request(method, url, **kwargs)
        response.raise_for_status()
        return response

    def get_note(self, path: str) -> str:
        """读取笔记内容"""
        response = self._request("GET", f"/vault/{path}")
        return response.text

    def create_note(self, path: str, content: str) -> bool:
        """创建或更新笔记"""
        self._request("PUT", f"/vault/{path}",
                     headers={"Content-Type": "text/markdown"},
                     data=content)
        return True

    def append_note(self, path: str, content: str) -> bool:
        """追加内容到笔记"""
        self._request("POST", f"/vault/{path}",
                     headers={"Content-Type": "text/markdown"},
                     data=content)
        return True

    def append_daily(self, content: str) -> bool:
        """追加到今日日记"""
        self._request("POST", "/periodic/daily/",
                     headers={"Content-Type": "text/markdown"},
                     data=content)
        return True

    def search(self, query: str) -> list:
        """搜索笔记"""
        response = self._request("POST", "/search/simple/",
                     json={"query": query})
        return response.json()

    def list_directory(self, path: str = "") -> dict:
        """列出目录内容"""
        endpoint = f"/vault/{path}/" if path else "/vault/"
        response = self._request("GET", endpoint)
        return response.json()


# 使用示例
if __name__ == "__main__":
    # 初始化客户端
    client = ObsidianClient(api_key="YOUR_API_KEY")

    # 创建新笔记
    client.create_note("Notes/API测试.md", f"""# API 测试笔记

创建时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}

这是一个通过 Python 脚本创建的笔记。
""")

    # 追加到今日日记
    client.append_daily(f"""
## {datetime.now().strftime("%H:%M")} 自动记录

- 完成了 API 测试
- 创建了测试笔记
""")

    # 搜索笔记
    results = client.search("API")
    print(f"找到 {len(results)} 条结果")

6.2 Shell 脚本示例

#!/bin/bash
# obsidian-cli.sh - Obsidian REST API 命令行工具

API_KEY="YOUR_API_KEY"
BASE_URL="https://127.0.0.1:27124"

# 通用请求函数
obs_request() {
    local method=$1
    local endpoint=$2
    local data=$3
    local content_type=${4:-"application/json"}

    curl -X "$method" "$BASE_URL$endpoint" \
        -H "Authorization: Bearer $API_KEY" \
        -H "Content-Type: $content_type" \
        -k \
        ${data:+-d "$data"}
}

# 创建笔记
create_note() {
    local path=$1
    local content=$2
    obs_request "PUT" "/vault/$path" "$content" "text/markdown"
}

# 读取笔记
read_note() {
    local path=$1
    obs_request "GET" "/vault/$path"
}

# 追加到日记
append_daily() {
    local content=$1
    obs_request "POST" "/periodic/daily/" "$content" "text/markdown"
}

# 搜索
search() {
    local query=$1
    obs_request "POST" "/search/simple/" "{\"query\":\"$query\"}"
}

# 命令行入口
case "$1" in
    create)
        create_note "$2" "$3"
        ;;
    read)
        read_note "$2"
        ;;
    daily)
        append_daily "$2"
        ;;
    search)
        search "$2"
        ;;
    *)
        echo "用法: $0 {create|read|daily|search} ..."
        ;;
esac

6.3 Node.js 脚本示例

// obsidian-client.js
const axios = require('axios');
const https = require('https');

class ObsidianClient {
    constructor(apiKey, host = '127.0.0.1', port = 27124) {
        this.client = axios.create({
            baseURL: `https://${host}:${port}`,
            headers: { 'Authorization': `Bearer ${apiKey}` },
            httpsAgent: new https.Agent({ rejectUnauthorized: false })
        });
    }

    // 创建笔记
    async createNote(path, content) {
        await this.client.put(`/vault/${path}`, content, {
            headers: { 'Content-Type': 'text/markdown' }
        });
    }

    // 读取笔记
    async getNote(path) {
        const response = await this.client.get(`/vault/${path}`);
        return response.data;
    }

    // 追加到日记
    async appendDaily(content) {
        await this.client.post('/periodic/daily/', content, {
            headers: { 'Content-Type': 'text/markdown' }
        });
    }

    // 搜索
    async search(query) {
        const response = await this.client.post('/search/simple/', { query });
        return response.data;
    }
}

module.exports = ObsidianClient;

七、与其他工具集成

7.1 与 Claude Code 集成

# 在 Claude Code 中使用

1. 创建 MCP 服务器配置:

{
  "obsidian": {
    "command": "node",
    "args": ["/path/to/obsidian-mcp-server.js"],
    "env": {
      "OBSIDIAN_API_KEY": "your-api-key",
      "OBSIDIAN_PORT": "27124"
    }
  }
}

2. Claude Code 可以直接读写你的 Obsidian 笔记

7.2 与 Shortcuts (macOS) 集成

创建快捷指令:
1. 获取剪贴板内容
2. 请求 REST API (POST /periodic/daily/)
3. 显示确认通知

7.3 与 Raycast 集成

// Raycast Extension
import { showToast, Toast } from "@raycast/api";

export default async function AppendToDaily() {
    const content = "## 自动记录\n\n来自 Raycast";

    await fetch("https://127.0.0.1:27124/periodic/daily/", {
        method: "POST",
        headers: {
            "Authorization": "Bearer YOUR_API_KEY",
            "Content-Type": "text/markdown"
        },
        body: content
    });

    showToast(Toast.Style.Success, "已追加到日记");
}

7.4 与 Obsidian Web 扩展集成

Obsidian Web 是配套的浏览器扩展:

  1. 安装 Obsidian Web
  2. 配置 API Key
  3. 在浏览器中一键保存网页到 Obsidian

八、错误处理

HTTP 状态码 说明 处理方式
200 成功 -
400 请求格式错误 检查请求参数
401 认证失败 检查 API Key
404 文件不存在 检查文件路径
500 服务器错误 检查 Obsidian 状态

九、安全注意事项

  1. API Key 保密
  2. 不要将 API Key 提交到版本控制
  3. 定期重新生成 API Key

  4. 网络限制

  5. 默认仅监听 127.0.0.1
  6. 如需远程访问,使用 VPN 或 SSH 隧道

  7. 证书管理

  8. 自签名证书需要手动信任
  9. 生产环境建议使用正式证书

十、参考资源

  • GitHub: https://github.com/coddingtonbear/obsidian-local-rest-api
  • 交互式文档: https://coddingtonbear.github.io/obsidian-local-rest-api/
  • 插件市场: https://obsidian.md/plugins?id=obsidian-local-rest-api

文档生成时间: 2026-03-14