当前位置: 首页 > Skill >

SiYuan Note

SiYuan Note

SiYuan Note

思源笔记 API 客户端 - 完整的笔记本、文档与块管理

1.0.3 2026.11.23 860
获取Skill文件查看使用说明
作 者:江舟 许可证: 更新时间:2026.11.23
本文目录展开

SiYuan Note (思源笔记)

A clean API client for SiYuan Note, providing access to your notes via the local HTTP API.

ClawHub: https://clawhub.ai/weiwei2027/siyuan
Install: clawhub install siyuan
Version: 1.0.1

Prerequisites

  • SiYuan running with API enabled (Settings → About → API)
  • API token from SiYuan settings

Configuration

  1. Get your API token from SiYuan: Settings → About → API → Copy Token

  2. Create/edit ~/.openclaw/workspace/skills/siyuan/config.yaml:

siyuan:
  base_url: "http://127.0.0.1:6806"  # Check SiYuan settings for actual port
  token: "your-api-token-here"       # Paste your token here
  timeout: 30
  retry: 3

Note: SiYuan may use different ports on restart (default 6806, but could be 34669, etc.). Check the current port in SiYuan settings.

Python Client API

Initialize Client

from siyuan_client import SiYuanClient

# Use config.yaml settings
client = SiYuanClient()

# Or explicit configuration
client = SiYuanClient(
    base_url="http://127.0.0.1:6806",
    token="your-token"
)

System Operations

# Get system version
version = client.system_version()
print(f"SiYuan v{version}")

# Get current time
timestamp = client.current_time()

Notebook Operations

# List all notebooks
notebooks = client.list_notebooks()
for nb in notebooks:
    print(f"{nb['name']}: {nb['id']}")

# Create new notebook
new_nb = client.create_notebook("我的新项目")

# Open/close notebook (load/unload from memory)
client.open_notebook("notebook-id")
client.close_notebook("notebook-id")

# Rename notebook
client.rename_notebook("notebook-id", "新名称")

# Get/set notebook configuration
conf = client.get_notebook_conf("notebook-id")
client.set_notebook_conf("notebook-id", {"dailyNoteSavePath": "/daily"})

# Remove notebook
client.remove_notebook("notebook-id")

Document Operations

# Export document as Markdown
result = client.export_md_content("doc-id")
print(result['hPath'])      # Human-readable path
print(result['content'])    # Markdown content

# Create new document
new_doc = client.create_doc_with_md(
    notebook_id="notebook-id",
    path="folder/document-name",  # Supports nested paths
    markdown="# TitlennContent here"
)

# Rename document
client.rename_doc("notebook-id", "/old-path", "新标题")
client.rename_doc_by_id("doc-id", "新标题")

# Get document paths
hpath = client.get_hpath_by_id("doc-id")  # Human-readable path
path_info = client.get_path_by_id("doc-id")  # Storage path
ids = client.get_ids_by_hpath("notebook-id", "/人类可读路径")

# Move documents by ID
client.move_docs_by_id(
    doc_ids=["doc-id-1", "doc-id-2"],
    to_id="target-notebook-or-doc-id"
)

# Move documents by path
client.move_docs(
    from_paths=["/path/to/doc1.sy", "/path/to/doc2.sy"],
    to_notebook="target-notebook-id",
    to_path="/subfolder"
)

# Remove document by notebook and path
client.remove_doc("notebook-id", "/path/to/doc.sy")

# Remove document by ID
client.remove_doc_by_id("doc-id")

Block Operations

# Insert blocks at specific position
blocks = client.insert_block(
    data_type="markdown",
    data="## New SectionnnSome content",
    parent_id="doc-id",      # Optional: parent block/document
    previous_id="block-id",  # Optional: insert after this block
    next_id="block-id"       # Optional: insert before this block
)

# Prepend to beginning of document
blocks = client.prepend_block(
    data_type="markdown",
    data="# Titlen",
    parent_id="doc-id"
)

# Append to end of document
blocks = client.append_block(
    data_type="markdown",
    data="n---nFooter here",
    parent_id="doc-id"
)

# Update block content
client.update_block(
    data_type="markdown",
    data="Updated content",
    block_id="block-id"
)

# Delete block
client.delete_block("block-id")

# Move block
client.move_block(
    block_id="block-id",
    previous_id="target-block-id",  # Optional: insert after this block
    parent_id="parent-block-id"     # Optional: set parent (at least one required)
)

# Fold/unfold (collapse/expand) blocks
client.fold_block("block-id")
client.unfold_block("block-id")

# Transfer block references
client.transfer_block_ref(
    from_id="source-block-id",
    to_id="target-block-id",
    ref_ids=["ref-1", "ref-2"]  # Optional: specific refs to transfer
)

# Get block in Kramdown format
kramdown = client.get_block_kramdown("block-id")

# Get child blocks
children = client.get_child_blocks("container-block-id")
for child in children:
    print(f"{child['type']}: {child['content'][:50]}")

Block Attributes

# Set custom attributes on a block
client.set_block_attrs("block-id", {
    "custom-key": "value",
    "custom-priority": "high",
    "custom-status": "done"
})

# Get all attributes of a block
attrs = client.get_block_attrs("block-id")
print(attrs.get("custom-key"))

Assets

# Upload asset files
result = client.upload_asset(
    file_paths=["/path/to/image.png", "/path/to/doc.pdf"],
    assets_dir_path="/assets/"
)
print(result['succMap'])  # Successfully uploaded files
print(result['errFiles'])  # Failed uploads

SQL Operations

# Execute SQL query
results = client.query_sql("""
    SELECT * FROM blocks 
    WHERE type = 'd' 
    ORDER BY updated DESC 
    LIMIT 10
""")

# Flush SQLite transaction to disk
client.flush_transaction()

Templates

# Render a template file
result = client.render_template(
    doc_id="doc-id",
    template_path="/data/templates/daily.md"
)
print(result['content'])

# Render Sprig template string
output = client.render_sprig('/daily note/{{now | date "2006/01"}}/{{now | date "2006-01-02"}}')

File Operations

# Read file content
content = client.get_file("/data/20210808180117-6v0mkxr/20200923234011-ieuun1p.sy")

# Create directory
client.put_file("/data/new-folder", is_dir=True)

# Upload file
with open("local-file.txt", "rb") as f:
    client.put_file("/data/new-folder/file.txt", file_content=f.read())

# List directory
files = client.read_dir("/data/20210808180117-6v0mkxr")
for f in files:
    print(f"{'[DIR]' if f['isDir'] else '[FILE]'} {f['name']}")

# Rename/move file
client.rename_file("/data/old-name.sy", "/data/new-name.sy")

# Remove file
client.remove_file("/data/unwanted-file.sy")

Export

# Export document as Markdown
result = client.export_md_content("doc-id")
print(result['hPath'])      # Human-readable path
print(result['content'])    # Markdown content

# Export multiple files/folders as zip
zip_path = client.export_resources(
    paths=["/conf/appearance/boot", "/conf/appearance/langs"],
    name="my-export"
)
print(f"Exported to: {zip_path}")

Conversion

# Run Pandoc conversion
# 1. Put input file
client.put_file("/temp/convert/pandoc/mydir/input.epub", file_content=epub_bytes)

# 2. Run conversion
work_dir = client.pandoc("mydir", ["--to", "markdown_strict", "input.epub", "-o", "output.md"])

# 3. Get output file
output = client.get_file("/temp/convert/pandoc/mydir/output.md")

Notifications

# Push message to SiYuan UI
msg_id = client.push_msg("Hello from API!")

# Push error message
err_id = client.push_err_msg("Something went wrong!", timeout=10000)

Network

# Forward HTTP request through SiYuan proxy
response = client.forward_proxy(
    url="https://api.example.com/data",
    method="GET",
    headers=[{"Authorization": "Bearer token"}]
)
print(response['body'])
print(response['status'])

System

# Get boot progress
progress = client.boot_progress()
print(f"Boot: {progress['progress']}% - {progress['details']}")

# Get system version
version = client.system_version()
print(f"SiYuan v{version}")

# Get current time (milliseconds)
timestamp = client.current_time()

SQL Query

# Execute SQL query (read-only recommended)
results = client.query_sql("""
    SELECT * FROM blocks 
    WHERE content LIKE '%关键词%'
    ORDER BY updated DESC 
    LIMIT 10
""")
for block in results:
    print(f"{block['content'][:100]}...")

CLI Tools

All tools are located in tools/ directory and depend on siyuan_client.py.

List

# List all notebooks
python3 tools/list.py --notebooks

# List documents in a notebook
python3 tools/list.py --docs "notebook-id"

# Output as JSON
python3 tools/list.py -n -j

Read

# Read document content
python3 tools/read.py 20240602141622-l7ou7t7

# Save to file
python3 tools/read.py 20240602141622-l7ou7t7 -o ~/doc.md

# Show document metadata
python3 tools/read.py 20240602141622-l7ou7t7 --info

Search

# Search by keyword
python3 tools/search.py "keyword"

# Limit results
python3 tools/search.py "keyword" -l 50

# Raw SQL query
python3 tools/search.py "SELECT * FROM blocks WHERE type='d' LIMIT 10" --sql

Export

# Export all notebooks
python3 tools/export.py -o ~/backup/

# Export specific notebook
python3 tools/export.py -n "工作" -o ~/backup/

# Export single document
python3 tools/export.py -d 20240602141622-l7ou7t7 -o ~/doc.md

Create

# Create notebook
python3 tools/create.py --notebook "New Project"

# Create document
python3 tools/create.py --doc notebook-id /readme "# HellonnWorld"

# Create with nested path
python3 tools/create.py --doc notebook-id /folder/doc "## TitlenContent"

Delete

# Delete notebook
python3 tools/delete.py --notebook notebook-id

# Delete document
python3 tools/delete.py --doc doc-id

# Delete block
python3 tools/delete.py --block block-id

# Skip confirmation
python3 tools/delete.py --doc doc-id --yes

Move

# Move single document
python3 tools/move.py --doc doc-id --to-notebook target-nb-id

# Move multiple documents
python3 tools/move.py --docs id1 id2 id3 --to-notebook target-nb-id

# Move by path
python3 tools/move.py --from-paths /doc1.sy /doc2.sy --to-nb target-nb --to-path /folder/

Update

# Update a block
python3 tools/update.py --block block-id --markdown "New content"

# Append to document
python3 tools/update.py --append doc-id --markdown "nnFooter"

# Prepend to document
python3 tools/update.py --prepend doc-id --markdown "# Headern"

# Insert block
python3 tools/update.py --insert "New paragraph" --parent doc-id

Safety Features

  • ✅ All write operations are logged
  • ✅ Automatic retry with exponential backoff
  • ✅ Connection health checks
  • ✅ Comprehensive error handling
  • ✅ Read-only by default for queries

Troubleshooting

Connection Refused

  1. Check if SiYuan is running
  2. Verify API is enabled in Settings → About → API
  3. Check the correct port in config.yaml

Authentication Failed

  1. Get fresh token from SiYuan: Settings → About → API
  2. Update config.yaml with new token

Port Changes

SiYuan may use different ports on restart. Check current port:

ss -tlnp | grep SiYuan

Then update config.yaml accordingly.

API Reference

  • Local API Documentation: See API.md in this directory (downloaded from official repo)
  • Online API Docs: https://www.siyuan-note.club/apis
  • Official Repository: https://github.com/siyuan-note/siyuan

Changelog

v1.0.0 (2026-03-20)

  • Added complete API client with automatic retry
  • Added 8 CLI tools for all common operations
  • Added bilingual documentation (Chinese/English)
  • Added configuration file support
  • Production-ready with comprehensive error handling

v0.5.0 (2026-03-18)

  • Initial release

推荐文章

更多
PHP时间戳与日期字符串相互转换方法详解

本文介绍PHP中时间数值(Unix时间戳)与日期字符串之间的相互转换方法。通过strtotime和date函数,实现将当前时间、指定日期转换为时间戳,以及将时间戳格式化为可读的日期时间字符串,并提供相关在线计算工具推荐。

2025.11.30 1,034
PHP日期转时间戳时区偏差怎么解决

在 PHP 中将日期字符串转换为时间戳时,若未显式指定时区,默认使用脚本配置的 date.timezone 或系统时区。当服务器时区与业务逻辑预期(如 UTC )不一致时,会产生偏差。解决核心是确保输入字符串携带明确时区信息,或在转换前统一设置时区上下文。

2026.10.24 1,031
PHP跨域配置:怎么安全地允许指定域名而非使用通配符

在 PHP 中安全地允许指定域名跨域,核心是解析请求头中的 Origin ,验证其是否在白名单内,然后动态设置 Access-Control-Allow-Origin 响应头。不要使用通配符 * ,也不要硬编码单一域名。

2025.03.29 1,019
JavaScript中利用replace结合正则实现replaceAll效果

JavaScript原生仅支持replace()进行单次或全局替换,缺乏类似Java的replaceAll()便捷方法。本文总结四种在JS中实现全量替换的方案:使用带g标志的正则、带gm标志的正则、扩展String原型以及split后join。通过对比代码示例,展示各方法的实现细节与适用场景,帮助开发者根据需求选择最优解。

2025.04.29 1,017
OpenAI的Jalapeno芯片未落地,教你分辨300兆瓦算力消息

OpenAI计划在SB Energy租赁的数据中心部署约300兆瓦自研Jalapeno推理芯片,但目前双方仍处于洽谈阶段,交易细节与上线时间表均未公布。本文带你按报道原文核实项目所处阶段,厘清芯片发布、电力功率与实际推理算力的边界,并将融资意向与签约、开工、投运节点分开追踪,避免误将规划容量计入现有算力。

2026.12.02 1,014
PHP实现基础文件上传:HTML表单与$_FILES处理流程

在 HTML 表单中设置 enctype="multipart/form-data" ,并在 PHP 后端通过 $_FILES 数组接收文件,调用 move_uploaded_file() 将临时文件移动到目标目录即可完成上传。

2026.09.07 1,014
Skill 文件
  • SKILL.md
    • SiYuan Note (思源笔记)
    • Prerequisites
    • Configuration
    • Python Client API
      • Initialize Client
      • System Operations
      • Notebook Operations
      • Document Operations
      • Block Operations
      • Block Attributes
      • Assets
      • SQL Operations
      • Templates
      • File Operations
      • Export
      • Conversion
      • Notifications
      • Network
      • System
      • SQL Query
    • CLI Tools
      • List
      • Read
      • Search
      • Export
      • Create
      • Delete
      • Move
      • Update
    • Safety Features
    • Troubleshooting
      • Connection Refused
      • Authentication Failed
      • Port Changes
    • API Reference
    • Changelog
      • v1.0.0 (2026-03-20)
      • v0.5.0 (2026-03-18)
  • 项目或源文件

相关 Skill

更多
思源受管工作区 思源受管工作区 WorkBuddy Skill for safely using SiYuan notes through the SiYuan v3.6.5+ HTTP API. Use when WorkBuddy needs to search, list, read, create, update, append, prepend, delete, or copy SiYuan note content while enforcing a single writable managed notebook and treating all other notebooks as read-only.
siyuan-task-skill siyuan-task-skill 通过 SiYuan Note 的 HTTP API 管理任务。创建、查询、更新和组织存储在「任务清单」文档(含 TASK 数据库)及其子文档中的任务及相关资料。适用于用户提及 SiYuan、任务管理或需要追踪工作事项的场景。
service-qa-coach service-qa-coach Review support quality for chat, email, phone, social DM, or marketplace service teams. Use when a team needs a QA scorecard, failure-mode analysis, coaching plan, calibration checklist, or service-improvement brief without live ticketing, CRM, or contact-center system access.
高中数学作业批改助手 高中数学作业批改助手 >图片识别 直接读取学生手写作答照片,识别公式、符号、步骤 🧮 自动推导 根据题目自动生成参考答案和评分细则,无需教师预设 📊 逐步给分 每个关键步骤独立评分,体现过程分 📝 结构化报告 输出含识别内容、参考答案、逐步评分、改进建议的完整报告 🗂 批量批改 支持一次性批改多道题,最终汇总得分表
Vibration Analysis Vibration Analysis 分析来自CMS趋势、RMS/峰值、频谱及SCADA报警的风机传动链(主轴、齿轮箱、发电机)振动数据。