# Directory Structure
```
├── .gitignore
├── LICENSE
├── openapi.yaml
├── pyproject.toml
├── README.md
├── src
│ └── mcp_obsidian
│ ├── __init__.py
│ ├── obsidian.py
│ ├── server.py
│ └── tools.py
└── uv.lock
```
# Files
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
```
# Python-generated files
__pycache__/
*.py[oc]
build/
dist/
wheels/
*.egg-info
# Virtual environments
.venv
.env
```
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
```markdown
# MCP server for Obsidian
MCP server to interact with Obsidian via the Local REST API community plugin.
<a href="https://glama.ai/mcp/servers/3wko1bhuek"><img width="380" height="200" src="https://glama.ai/mcp/servers/3wko1bhuek/badge" alt="server for Obsidian MCP server" /></a>
## Components
### Tools
The server implements multiple tools to interact with Obsidian:
- list_files_in_vault: Lists all files and directories in the root directory of your Obsidian vault
- list_files_in_dir: Lists all files and directories in a specific Obsidian directory
- get_file_contents: Return the content of a single file in your vault.
- search: Search for documents matching a specified text query across all files in the vault
- patch_content: Insert content into an existing note relative to a heading, block reference, or frontmatter field.
- append_content: Append content to a new or existing file in the vault.
- delete_file: Delete a file or directory from your vault.
### Example prompts
Its good to first instruct Claude to use Obsidian. Then it will always call the tool.
The use prompts like this:
- Get the contents of the last architecture call note and summarize them
- Search for all files where Azure CosmosDb is mentioned and quickly explain to me the context in which it is mentioned
- Summarize the last meeting notes and put them into a new note 'summary meeting.md'. Add an introduction so that I can send it via email.
## Configuration
### Obsidian REST API Key
There are two ways to configure the environment with the Obsidian REST API Key.
1. Add to server config (preferred)
```json
{
"mcp-obsidian": {
"command": "uvx",
"args": [
"mcp-obsidian"
],
"env": {
"OBSIDIAN_API_KEY": "<your_api_key_here>",
"OBSIDIAN_HOST": "<your_obsidian_host>",
"OBSIDIAN_PORT": "<your_obsidian_port>"
}
}
}
```
Sometimes Claude has issues detecting the location of uv / uvx. You can use `which uvx` to find and paste the full path in above config in such cases.
2. Create a `.env` file in the working directory with the following required variables:
```
OBSIDIAN_API_KEY=your_api_key_here
OBSIDIAN_HOST=your_obsidian_host
OBSIDIAN_PORT=your_obsidian_port
```
Note:
- You can find the API key in the Obsidian plugin config
- Default port is 27124 if not specified
- Default host is 127.0.0.1 if not specified
## Quickstart
### Install
#### Obsidian REST API
You need the Obsidian REST API community plugin running: https://github.com/coddingtonbear/obsidian-local-rest-api
Install and enable it in the settings and copy the api key.
#### Claude Desktop
On MacOS: `~/Library/Application\ Support/Claude/claude_desktop_config.json`
On Windows: `%APPDATA%/Claude/claude_desktop_config.json`
<details>
<summary>Development/Unpublished Servers Configuration</summary>
```json
{
"mcpServers": {
"mcp-obsidian": {
"command": "uv",
"args": [
"--directory",
"<dir_to>/mcp-obsidian",
"run",
"mcp-obsidian"
],
"env": {
"OBSIDIAN_API_KEY": "<your_api_key_here>",
"OBSIDIAN_HOST": "<your_obsidian_host>",
"OBSIDIAN_PORT": "<your_obsidian_port>"
}
}
}
}
```
</details>
<details>
<summary>Published Servers Configuration</summary>
```json
{
"mcpServers": {
"mcp-obsidian": {
"command": "uvx",
"args": [
"mcp-obsidian"
],
"env": {
"OBSIDIAN_API_KEY": "<YOUR_OBSIDIAN_API_KEY>",
"OBSIDIAN_HOST": "<your_obsidian_host>",
"OBSIDIAN_PORT": "<your_obsidian_port>"
}
}
}
}
```
</details>
## Development
### Building
To prepare the package for distribution:
1. Sync dependencies and update lockfile:
```bash
uv sync
```
### Debugging
Since MCP servers run over stdio, debugging can be challenging. For the best debugging
experience, we strongly recommend using the [MCP Inspector](https://github.com/modelcontextprotocol/inspector).
You can launch the MCP Inspector via [`npm`](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm) with this command:
```bash
npx @modelcontextprotocol/inspector uv --directory /path/to/mcp-obsidian run mcp-obsidian
```
Upon launching, the Inspector will display a URL that you can access in your browser to begin debugging.
You can also watch the server logs with this command:
```bash
tail -n 20 -f ~/Library/Logs/Claude/mcp-server-mcp-obsidian.log
```
```
--------------------------------------------------------------------------------
/src/mcp_obsidian/__init__.py:
--------------------------------------------------------------------------------
```python
from . import server
import asyncio
def main():
"""Main entry point for the package."""
asyncio.run(server.main())
# Optionally expose other important items at package level
__all__ = ['main', 'server']
```
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
```toml
[project]
name = "mcp-obsidian"
version = "0.2.1"
description = "MCP server to work with Obsidian via the remote REST plugin"
readme = "README.md"
requires-python = ">=3.11"
dependencies = [
"mcp>=1.1.0",
"python-dotenv>=1.0.1",
"requests>=2.32.3",
]
[[project.authors]]
name = "Markus Pfundstein"
email = "[email protected]"
[build-system]
requires = [ "hatchling",]
build-backend = "hatchling.build"
[dependency-groups]
dev = [
"pyright>=1.1.389",
]
[project.scripts]
mcp-obsidian = "mcp_obsidian:main"
```
--------------------------------------------------------------------------------
/src/mcp_obsidian/server.py:
--------------------------------------------------------------------------------
```python
import json
import logging
from collections.abc import Sequence
from functools import lru_cache
from typing import Any
import os
from dotenv import load_dotenv
from mcp.server import Server
from mcp.types import (
Tool,
TextContent,
ImageContent,
EmbeddedResource,
)
load_dotenv()
from . import tools
# Load environment variables
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("mcp-obsidian")
api_key = os.getenv("OBSIDIAN_API_KEY")
if not api_key:
raise ValueError(f"OBSIDIAN_API_KEY environment variable required. Working directory: {os.getcwd()}")
app = Server("mcp-obsidian")
tool_handlers = {}
def add_tool_handler(tool_class: tools.ToolHandler):
global tool_handlers
tool_handlers[tool_class.name] = tool_class
def get_tool_handler(name: str) -> tools.ToolHandler | None:
if name not in tool_handlers:
return None
return tool_handlers[name]
add_tool_handler(tools.ListFilesInDirToolHandler())
add_tool_handler(tools.ListFilesInVaultToolHandler())
add_tool_handler(tools.GetFileContentsToolHandler())
add_tool_handler(tools.SearchToolHandler())
add_tool_handler(tools.PatchContentToolHandler())
add_tool_handler(tools.AppendContentToolHandler())
add_tool_handler(tools.PutContentToolHandler())
add_tool_handler(tools.DeleteFileToolHandler())
add_tool_handler(tools.ComplexSearchToolHandler())
add_tool_handler(tools.BatchGetFileContentsToolHandler())
add_tool_handler(tools.PeriodicNotesToolHandler())
add_tool_handler(tools.RecentPeriodicNotesToolHandler())
add_tool_handler(tools.RecentChangesToolHandler())
@app.list_tools()
async def list_tools() -> list[Tool]:
"""List available tools."""
return [th.get_tool_description() for th in tool_handlers.values()]
@app.call_tool()
async def call_tool(name: str, arguments: Any) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
"""Handle tool calls for command line run."""
if not isinstance(arguments, dict):
raise RuntimeError("arguments must be dictionary")
tool_handler = get_tool_handler(name)
if not tool_handler:
raise ValueError(f"Unknown tool: {name}")
try:
return tool_handler.run_tool(arguments)
except Exception as e:
logger.error(str(e))
raise RuntimeError(f"Caught Exception. Error: {str(e)}")
async def main():
# Import here to avoid issues with event loops
from mcp.server.stdio import stdio_server
async with stdio_server() as (read_stream, write_stream):
await app.run(
read_stream,
write_stream,
app.create_initialization_options()
)
```
--------------------------------------------------------------------------------
/src/mcp_obsidian/obsidian.py:
--------------------------------------------------------------------------------
```python
import requests
import urllib.parse
import os
from typing import Any
class Obsidian():
def __init__(
self,
api_key: str,
protocol: str = os.getenv('OBSIDIAN_PROTOCOL', 'https').lower(),
host: str = str(os.getenv('OBSIDIAN_HOST', '127.0.0.1')),
port: int = int(os.getenv('OBSIDIAN_PORT', '27124')),
verify_ssl: bool = False,
):
self.api_key = api_key
if protocol == 'http':
self.protocol = 'http'
else:
self.protocol = 'https' # Default to https for any other value, including 'https'
self.host = host
self.port = port
self.verify_ssl = verify_ssl
self.timeout = (3, 6)
def get_base_url(self) -> str:
return f'{self.protocol}://{self.host}:{self.port}'
def _get_headers(self) -> dict:
headers = {
'Authorization': f'Bearer {self.api_key}'
}
return headers
def _safe_call(self, f) -> Any:
try:
return f()
except requests.HTTPError as e:
error_data = e.response.json() if e.response.content else {}
code = error_data.get('errorCode', -1)
message = error_data.get('message', '<unknown>')
raise Exception(f"Error {code}: {message}")
except requests.exceptions.RequestException as e:
raise Exception(f"Request failed: {str(e)}")
def list_files_in_vault(self) -> Any:
url = f"{self.get_base_url()}/vault/"
def call_fn():
response = requests.get(url, headers=self._get_headers(), verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return response.json()['files']
return self._safe_call(call_fn)
def list_files_in_dir(self, dirpath: str) -> Any:
url = f"{self.get_base_url()}/vault/{dirpath}/"
def call_fn():
response = requests.get(url, headers=self._get_headers(), verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return response.json()['files']
return self._safe_call(call_fn)
def get_file_contents(self, filepath: str) -> Any:
url = f"{self.get_base_url()}/vault/{filepath}"
def call_fn():
response = requests.get(url, headers=self._get_headers(), verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return response.text
return self._safe_call(call_fn)
def get_batch_file_contents(self, filepaths: list[str]) -> str:
"""Get contents of multiple files and concatenate them with headers.
Args:
filepaths: List of file paths to read
Returns:
String containing all file contents with headers
"""
result = []
for filepath in filepaths:
try:
content = self.get_file_contents(filepath)
result.append(f"# {filepath}\n\n{content}\n\n---\n\n")
except Exception as e:
# Add error message but continue processing other files
result.append(f"# {filepath}\n\nError reading file: {str(e)}\n\n---\n\n")
return "".join(result)
def search(self, query: str, context_length: int = 100) -> Any:
url = f"{self.get_base_url()}/search/simple/"
params = {
'query': query,
'contextLength': context_length
}
def call_fn():
response = requests.post(url, headers=self._get_headers(), params=params, verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return response.json()
return self._safe_call(call_fn)
def append_content(self, filepath: str, content: str) -> Any:
url = f"{self.get_base_url()}/vault/{filepath}"
def call_fn():
response = requests.post(
url,
headers=self._get_headers() | {'Content-Type': 'text/markdown'},
data=content,
verify=self.verify_ssl,
timeout=self.timeout
)
response.raise_for_status()
return None
return self._safe_call(call_fn)
def patch_content(self, filepath: str, operation: str, target_type: str, target: str, content: str) -> Any:
url = f"{self.get_base_url()}/vault/{filepath}"
headers = self._get_headers() | {
'Content-Type': 'text/markdown',
'Operation': operation,
'Target-Type': target_type,
'Target': urllib.parse.quote(target)
}
def call_fn():
response = requests.patch(url, headers=headers, data=content, verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return None
return self._safe_call(call_fn)
def put_content(self, filepath: str, content: str) -> Any:
url = f"{self.get_base_url()}/vault/{filepath}"
def call_fn():
response = requests.put(
url,
headers=self._get_headers() | {'Content-Type': 'text/markdown'},
data=content,
verify=self.verify_ssl,
timeout=self.timeout
)
response.raise_for_status()
return None
return self._safe_call(call_fn)
def delete_file(self, filepath: str) -> Any:
"""Delete a file or directory from the vault.
Args:
filepath: Path to the file to delete (relative to vault root)
Returns:
None on success
"""
url = f"{self.get_base_url()}/vault/{filepath}"
def call_fn():
response = requests.delete(url, headers=self._get_headers(), verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return None
return self._safe_call(call_fn)
def search_json(self, query: dict) -> Any:
url = f"{self.get_base_url()}/search/"
headers = self._get_headers() | {
'Content-Type': 'application/vnd.olrapi.jsonlogic+json'
}
def call_fn():
response = requests.post(url, headers=headers, json=query, verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return response.json()
return self._safe_call(call_fn)
def get_periodic_note(self, period: str, type: str = "content") -> Any:
"""Get current periodic note for the specified period.
Args:
period: The period type (daily, weekly, monthly, quarterly, yearly)
type: Type of the data to get ('content' or 'metadata').
'content' returns just the content in Markdown format.
'metadata' includes note metadata (including paths, tags, etc.) and the content..
Returns:
Content of the periodic note
"""
url = f"{self.get_base_url()}/periodic/{period}/"
def call_fn():
headers = self._get_headers()
if type == "metadata":
headers['Accept'] = 'application/vnd.olrapi.note+json'
response = requests.get(url, headers=headers, verify=self.verify_ssl, timeout=self.timeout)
response.raise_for_status()
return response.text
return self._safe_call(call_fn)
def get_recent_periodic_notes(self, period: str, limit: int = 5, include_content: bool = False) -> Any:
"""Get most recent periodic notes for the specified period type.
Args:
period: The period type (daily, weekly, monthly, quarterly, yearly)
limit: Maximum number of notes to return (default: 5)
include_content: Whether to include note content (default: False)
Returns:
List of recent periodic notes
"""
url = f"{self.get_base_url()}/periodic/{period}/recent"
params = {
"limit": limit,
"includeContent": include_content
}
def call_fn():
response = requests.get(
url,
headers=self._get_headers(),
params=params,
verify=self.verify_ssl,
timeout=self.timeout
)
response.raise_for_status()
return response.json()
return self._safe_call(call_fn)
def get_recent_changes(self, limit: int = 10, days: int = 90) -> Any:
"""Get recently modified files in the vault.
Args:
limit: Maximum number of files to return (default: 10)
days: Only include files modified within this many days (default: 90)
Returns:
List of recently modified files with metadata
"""
# Build the DQL query
query_lines = [
"TABLE file.mtime",
f"WHERE file.mtime >= date(today) - dur({days} days)",
"SORT file.mtime DESC",
f"LIMIT {limit}"
]
# Join with proper DQL line breaks
dql_query = "\n".join(query_lines)
# Make the request to search endpoint
url = f"{self.get_base_url()}/search/"
headers = self._get_headers() | {
'Content-Type': 'application/vnd.olrapi.dataview.dql+txt'
}
def call_fn():
response = requests.post(
url,
headers=headers,
data=dql_query.encode('utf-8'),
verify=self.verify_ssl,
timeout=self.timeout
)
response.raise_for_status()
return response.json()
return self._safe_call(call_fn)
```
--------------------------------------------------------------------------------
/src/mcp_obsidian/tools.py:
--------------------------------------------------------------------------------
```python
from collections.abc import Sequence
from mcp.types import (
Tool,
TextContent,
ImageContent,
EmbeddedResource,
)
import json
import os
from . import obsidian
api_key = os.getenv("OBSIDIAN_API_KEY", "")
obsidian_host = os.getenv("OBSIDIAN_HOST", "127.0.0.1")
if api_key == "":
raise ValueError(f"OBSIDIAN_API_KEY environment variable required. Working directory: {os.getcwd()}")
TOOL_LIST_FILES_IN_VAULT = "obsidian_list_files_in_vault"
TOOL_LIST_FILES_IN_DIR = "obsidian_list_files_in_dir"
class ToolHandler():
def __init__(self, tool_name: str):
self.name = tool_name
def get_tool_description(self) -> Tool:
raise NotImplementedError()
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
raise NotImplementedError()
class ListFilesInVaultToolHandler(ToolHandler):
def __init__(self):
super().__init__(TOOL_LIST_FILES_IN_VAULT)
def get_tool_description(self):
return Tool(
name=self.name,
description="Lists all files and directories in the root directory of your Obsidian vault.",
inputSchema={
"type": "object",
"properties": {},
"required": []
},
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
files = api.list_files_in_vault()
return [
TextContent(
type="text",
text=json.dumps(files, indent=2)
)
]
class ListFilesInDirToolHandler(ToolHandler):
def __init__(self):
super().__init__(TOOL_LIST_FILES_IN_DIR)
def get_tool_description(self):
return Tool(
name=self.name,
description="Lists all files and directories that exist in a specific Obsidian directory.",
inputSchema={
"type": "object",
"properties": {
"dirpath": {
"type": "string",
"description": "Path to list files from (relative to your vault root). Note that empty directories will not be returned."
},
},
"required": ["dirpath"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "dirpath" not in args:
raise RuntimeError("dirpath argument missing in arguments")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
files = api.list_files_in_dir(args["dirpath"])
return [
TextContent(
type="text",
text=json.dumps(files, indent=2)
)
]
class GetFileContentsToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_get_file_contents")
def get_tool_description(self):
return Tool(
name=self.name,
description="Return the content of a single file in your vault.",
inputSchema={
"type": "object",
"properties": {
"filepath": {
"type": "string",
"description": "Path to the relevant file (relative to your vault root).",
"format": "path"
},
},
"required": ["filepath"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "filepath" not in args:
raise RuntimeError("filepath argument missing in arguments")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
content = api.get_file_contents(args["filepath"])
return [
TextContent(
type="text",
text=json.dumps(content, indent=2)
)
]
class SearchToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_simple_search")
def get_tool_description(self):
return Tool(
name=self.name,
description="""Simple search for documents matching a specified text query across all files in the vault.
Use this tool when you want to do a simple text search""",
inputSchema={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Text to a simple search for in the vault."
},
"context_length": {
"type": "integer",
"description": "How much context to return around the matching string (default: 100)",
"default": 100
}
},
"required": ["query"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "query" not in args:
raise RuntimeError("query argument missing in arguments")
context_length = args.get("context_length", 100)
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
results = api.search(args["query"], context_length)
formatted_results = []
for result in results:
formatted_matches = []
for match in result.get('matches', []):
context = match.get('context', '')
match_pos = match.get('match', {})
start = match_pos.get('start', 0)
end = match_pos.get('end', 0)
formatted_matches.append({
'context': context,
'match_position': {'start': start, 'end': end}
})
formatted_results.append({
'filename': result.get('filename', ''),
'score': result.get('score', 0),
'matches': formatted_matches
})
return [
TextContent(
type="text",
text=json.dumps(formatted_results, indent=2)
)
]
class AppendContentToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_append_content")
def get_tool_description(self):
return Tool(
name=self.name,
description="Append content to a new or existing file in the vault.",
inputSchema={
"type": "object",
"properties": {
"filepath": {
"type": "string",
"description": "Path to the file (relative to vault root)",
"format": "path"
},
"content": {
"type": "string",
"description": "Content to append to the file"
}
},
"required": ["filepath", "content"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "filepath" not in args or "content" not in args:
raise RuntimeError("filepath and content arguments required")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
api.append_content(args.get("filepath", ""), args["content"])
return [
TextContent(
type="text",
text=f"Successfully appended content to {args['filepath']}"
)
]
class PatchContentToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_patch_content")
def get_tool_description(self):
return Tool(
name=self.name,
description="Insert content into an existing note relative to a heading, block reference, or frontmatter field.",
inputSchema={
"type": "object",
"properties": {
"filepath": {
"type": "string",
"description": "Path to the file (relative to vault root)",
"format": "path"
},
"operation": {
"type": "string",
"description": "Operation to perform (append, prepend, or replace)",
"enum": ["append", "prepend", "replace"]
},
"target_type": {
"type": "string",
"description": "Type of target to patch",
"enum": ["heading", "block", "frontmatter"]
},
"target": {
"type": "string",
"description": "Target identifier (heading path, block reference, or frontmatter field)"
},
"content": {
"type": "string",
"description": "Content to insert"
}
},
"required": ["filepath", "operation", "target_type", "target", "content"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if not all(k in args for k in ["filepath", "operation", "target_type", "target", "content"]):
raise RuntimeError("filepath, operation, target_type, target and content arguments required")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
api.patch_content(
args.get("filepath", ""),
args.get("operation", ""),
args.get("target_type", ""),
args.get("target", ""),
args.get("content", "")
)
return [
TextContent(
type="text",
text=f"Successfully patched content in {args['filepath']}"
)
]
class PutContentToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_put_content")
def get_tool_description(self):
return Tool(
name=self.name,
description="Create a new file in your vault or update the content of an existing one in your vault.",
inputSchema={
"type": "object",
"properties": {
"filepath": {
"type": "string",
"description": "Path to the relevant file (relative to your vault root)",
"format": "path"
},
"content": {
"type": "string",
"description": "Content of the file you would like to upload"
}
},
"required": ["filepath", "content"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "filepath" not in args or "content" not in args:
raise RuntimeError("filepath and content arguments required")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
api.put_content(args.get("filepath", ""), args["content"])
return [
TextContent(
type="text",
text=f"Successfully uploaded content to {args['filepath']}"
)
]
class DeleteFileToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_delete_file")
def get_tool_description(self):
return Tool(
name=self.name,
description="Delete a file or directory from the vault.",
inputSchema={
"type": "object",
"properties": {
"filepath": {
"type": "string",
"description": "Path to the file or directory to delete (relative to vault root)",
"format": "path"
},
"confirm": {
"type": "boolean",
"description": "Confirmation to delete the file (must be true)",
"default": False
}
},
"required": ["filepath", "confirm"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "filepath" not in args:
raise RuntimeError("filepath argument missing in arguments")
if not args.get("confirm", False):
raise RuntimeError("confirm must be set to true to delete a file")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
api.delete_file(args["filepath"])
return [
TextContent(
type="text",
text=f"Successfully deleted {args['filepath']}"
)
]
class ComplexSearchToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_complex_search")
def get_tool_description(self):
return Tool(
name=self.name,
description="""Complex search for documents using a JsonLogic query.
Supports standard JsonLogic operators plus 'glob' and 'regexp' for pattern matching. Results must be non-falsy.
Use this tool when you want to do a complex search, e.g. for all documents with certain tags etc.
ALWAYS follow query syntax in examples.
Examples
1. Match all markdown files
{"glob": ["*.md", {"var": "path"}]}
2. Match all markdown files with 1221 substring inside them
{
"and": [
{ "glob": ["*.md", {"var": "path"}] },
{ "regexp": [".*1221.*", {"var": "content"}] }
]
}
3. Match all markdown files in Work folder containing name Keaton
{
"and": [
{ "glob": ["*.md", {"var": "path"}] },
{ "regexp": [".*Work.*", {"var": "path"}] },
{ "regexp": ["Keaton", {"var": "content"}] }
]
}
""",
inputSchema={
"type": "object",
"properties": {
"query": {
"type": "object",
"description": "JsonLogic query object. ALWAYS follow query syntax in examples. \
Example 1: {\"glob\": [\"*.md\", {\"var\": \"path\"}]} matches all markdown files \
Example 2: {\"and\": [{\"glob\": [\"*.md\", {\"var\": \"path\"}]}, {\"regexp\": [\".*1221.*\", {\"var\": \"content\"}]}]} matches all markdown files with 1221 substring inside them \
Example 3: {\"and\": [{\"glob\": [\"*.md\", {\"var\": \"path\"}]}, {\"regexp\": [\".*Work.*\", {\"var\": \"path\"}]}, {\"regexp\": [\"Keaton\", {\"var\": \"content\"}]}]} matches all markdown files in Work folder containing name Keaton \
"
}
},
"required": ["query"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "query" not in args:
raise RuntimeError("query argument missing in arguments")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
results = api.search_json(args.get("query", ""))
return [
TextContent(
type="text",
text=json.dumps(results, indent=2)
)
]
class BatchGetFileContentsToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_batch_get_file_contents")
def get_tool_description(self):
return Tool(
name=self.name,
description="Return the contents of multiple files in your vault, concatenated with headers.",
inputSchema={
"type": "object",
"properties": {
"filepaths": {
"type": "array",
"items": {
"type": "string",
"description": "Path to a file (relative to your vault root)",
"format": "path"
},
"description": "List of file paths to read"
},
},
"required": ["filepaths"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "filepaths" not in args:
raise RuntimeError("filepaths argument missing in arguments")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
content = api.get_batch_file_contents(args["filepaths"])
return [
TextContent(
type="text",
text=content
)
]
class PeriodicNotesToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_get_periodic_note")
def get_tool_description(self):
return Tool(
name=self.name,
description="Get current periodic note for the specified period.",
inputSchema={
"type": "object",
"properties": {
"period": {
"type": "string",
"description": "The period type (daily, weekly, monthly, quarterly, yearly)",
"enum": ["daily", "weekly", "monthly", "quarterly", "yearly"]
},
"type": {
"type": "string",
"description": "The type of data to get ('content' or 'metadata'). 'content' returns just the content in Markdown format. 'metadata' includes note metadata (including paths, tags, etc.) and the content.",
"default": "content",
"enum": ["content", "metadata"]
}
},
"required": ["period"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "period" not in args:
raise RuntimeError("period argument missing in arguments")
period = args["period"]
valid_periods = ["daily", "weekly", "monthly", "quarterly", "yearly"]
if period not in valid_periods:
raise RuntimeError(f"Invalid period: {period}. Must be one of: {', '.join(valid_periods)}")
type = args["type"] if "type" in args else "content"
valid_types = ["content", "metadata"]
if type not in valid_types:
raise RuntimeError(f"Invalid type: {type}. Must be one of: {', '.join(valid_types)}")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
content = api.get_periodic_note(period,type)
return [
TextContent(
type="text",
text=content
)
]
class RecentPeriodicNotesToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_get_recent_periodic_notes")
def get_tool_description(self):
return Tool(
name=self.name,
description="Get most recent periodic notes for the specified period type.",
inputSchema={
"type": "object",
"properties": {
"period": {
"type": "string",
"description": "The period type (daily, weekly, monthly, quarterly, yearly)",
"enum": ["daily", "weekly", "monthly", "quarterly", "yearly"]
},
"limit": {
"type": "integer",
"description": "Maximum number of notes to return (default: 5)",
"default": 5,
"minimum": 1,
"maximum": 50
},
"include_content": {
"type": "boolean",
"description": "Whether to include note content (default: false)",
"default": False
}
},
"required": ["period"]
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
if "period" not in args:
raise RuntimeError("period argument missing in arguments")
period = args["period"]
valid_periods = ["daily", "weekly", "monthly", "quarterly", "yearly"]
if period not in valid_periods:
raise RuntimeError(f"Invalid period: {period}. Must be one of: {', '.join(valid_periods)}")
limit = args.get("limit", 5)
if not isinstance(limit, int) or limit < 1:
raise RuntimeError(f"Invalid limit: {limit}. Must be a positive integer")
include_content = args.get("include_content", False)
if not isinstance(include_content, bool):
raise RuntimeError(f"Invalid include_content: {include_content}. Must be a boolean")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
results = api.get_recent_periodic_notes(period, limit, include_content)
return [
TextContent(
type="text",
text=json.dumps(results, indent=2)
)
]
class RecentChangesToolHandler(ToolHandler):
def __init__(self):
super().__init__("obsidian_get_recent_changes")
def get_tool_description(self):
return Tool(
name=self.name,
description="Get recently modified files in the vault.",
inputSchema={
"type": "object",
"properties": {
"limit": {
"type": "integer",
"description": "Maximum number of files to return (default: 10)",
"default": 10,
"minimum": 1,
"maximum": 100
},
"days": {
"type": "integer",
"description": "Only include files modified within this many days (default: 90)",
"minimum": 1,
"default": 90
}
}
}
)
def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
limit = args.get("limit", 10)
if not isinstance(limit, int) or limit < 1:
raise RuntimeError(f"Invalid limit: {limit}. Must be a positive integer")
days = args.get("days", 90)
if not isinstance(days, int) or days < 1:
raise RuntimeError(f"Invalid days: {days}. Must be a positive integer")
api = obsidian.Obsidian(api_key=api_key, host=obsidian_host)
results = api.get_recent_changes(limit, days)
return [
TextContent(
type="text",
text=json.dumps(results, indent=2)
)
]
```
--------------------------------------------------------------------------------
/openapi.yaml:
--------------------------------------------------------------------------------
```yaml
components:
schemas:
Error:
properties:
errorCode:
description: |
A 5-digit error code uniquely identifying this particular type of error.
example: 40149
type: "number"
message:
description: "Message describing the error."
example: "A brief description of the error."
type: "string"
type: "object"
NoteJson:
properties:
content:
type: "string"
frontmatter:
type: "object"
path:
type: "string"
stat:
properties:
ctime:
type: "number"
mtime:
type: "number"
size:
type: "number"
required:
- "ctime"
- "mtime"
- "size"
type: "object"
tags:
items:
type: "string"
type: "array"
required:
- "tags"
- "frontmatter"
- "stat"
- "path"
- "content"
type: "object"
securitySchemes:
apiKeyAuth:
description: |
Find your API Key in your Obsidian settings
in the "Local REST API" section under "Plugins".
scheme: "bearer"
type: "http"
info:
description: |
You can use this interface for trying out your Local REST API in Obsidian.
Before trying the below tools, you will want to make sure you press the "Authorize" button below and provide the API Key you are shown when you open the "Local REST API" section of your Obsidian settings. All requests to the API require a valid API Key; so you won't get very far without doing that.
When using this tool you may see browser security warnings due to your browser not trusting the self-signed certificate the plugin will generate on its first run. If you do, you can make those errors disappear by adding the certificate as a "Trusted Certificate" in your browser or operating system's settings.
title: "Local REST API for Obsidian"
version: "1.0"
openapi: "3.0.2"
paths:
/:
get:
description: |
Returns basic details about the server as well as your authentication status.
This is the only API request that does *not* require authentication.
responses:
"200":
content:
application/json:
schema:
properties:
authenticated:
description: "Is your current request authenticated?"
type: "boolean"
ok:
description: "'OK'"
type: "string"
service:
description: "'Obsidian Local REST API'"
type: "string"
versions:
properties:
obsidian:
description: "Obsidian plugin API version"
type: "string"
self:
description: "Plugin version."
type: "string"
type: "object"
type: "object"
description: "Success"
summary: |
Returns basic details about the server.
tags:
- "Status"
/active/:
delete:
parameters: []
responses:
"204":
description: "Success"
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "File does not exist."
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Deletes the currently-active file in Obsidian.
tags:
- "Active File"
get:
description: |
Returns the content of the currently active file in Obsidian.
If you specify the header `Accept: application/vnd.olrapi.note+json`, will return a JSON representation of your note including parsed tag and frontmatter data as well as filesystem metadata. See "responses" below for details.
parameters: []
responses:
"200":
content:
"application/vnd.olrapi.note+json":
schema:
"$ref": "#/components/schemas/NoteJson"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Success"
"404":
description: "File does not exist"
summary: |
Return the content of the active file open in Obsidian.
tags:
- "Active File"
patch:
description: |
Inserts content into the currently-open note relative to a heading, block refeerence, or frontmatter field within that document.
Allows you to modify the content relative to a heading, block reference, or frontmatter field in your document.
Note that this API was changed in Version 3.0 of this extension and the earlier PATCH API is now deprecated. Requests made using the previous version of this API will continue to work until Version 4.0 is released. See https://github.com/coddingtonbear/obsidian-local-rest-api/wiki/Changes-to-PATCH-requests-between-versions-2.0-and-3.0 for more details and migration instructions.
# Examples
All of the below examples assume you have a document that looks like
this:
```markdown
---
alpha: 1
beta: test
delta:
zeta: 1
yotta: 1
gamma:
- one
- two
---
# Heading 1
This is the content for heading one
Also references some [[#^484ef2]]
## Subheading 1:1
Content for Subheading 1:1
### Subsubheading 1:1:1
### Subsubheading 1:1:2
Testing how block references work for a table.[[#^2c7cfa]]
Some content for Subsubheading 1:1:2
More random text.
^2d9b4a
## Subheading 1:2
Content for Subheading 1:2.
some content with a block reference ^484ef2
## Subheading 1:3
| City | Population |
| ------------ | ---------- |
| Seattle, WA | 8 |
| Portland, OR | 4 |
^2c7cfa
```
## Append Content Below a Heading
If you wanted to append the content "Hello" below "Subheading 1:1:1" under "Heading 1",
you could send a request with the following headers:
- `Operation`: `append`
- `Target-Type`: `heading`
- `Target`: `Heading 1::Subheading 1:1:1`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Append Content to a Block Reference
If you wanted to append the content "Hello" below the block referenced by
"2d9b4a" above ("More random text."), you could send the following headers:
- `Operation`: `append`
- `Target-Type`: `block`
- `Target`: `2d9b4a`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Add a Row to a Table Referenced by a Block Reference
If you wanted to add a new city ("Chicago, IL") and population ("16") pair to the table above
referenced by the block reference `2c7cfa`, you could send the following
headers:
- `Operation`: `append`
- `TargetType`: `block`
- `Target`: `2c7cfa`
- `Content-Type`: `application/json`
- with the request body: `[["Chicago, IL", "16"]]`
The use of a `Content-Type` of `application/json` allows the API
to infer that member of your array represents rows and columns of your
to append to the referenced table. You can of course just use a
`Content-Type` of `text/markdown`, but in such a case you'll have to
format your table row manually instead of letting the library figure
it out for you.
You also have the option of using `prepend` (in which case, your new
row would be the first -- right below the table heading) or `replace` (in which
case all rows except the table heading would be replaced by the new row(s)
you supplied).
## Setting a Frontmatter Field
If you wanted to set the frontmatter field `alpha` to `2`, you could
send the following headers:
- `Operation`: `replace`
- `TargetType`: `frontmatter`
- `Target`: `beep`
- with the request body `2`
If you're setting a frontmatter field that might not already exist
you may want to use the `Create-Target-If-Missing` header so the
new frontmatter field is created and set to your specified value
if it doesn't already exist.
You may find using a `Content-Type` of `application/json` to be
particularly useful in the case of frontmatter since frontmatter
fields' values are JSON data, and the API can be smarter about
interpreting yoru `prepend` or `append` requests if you specify
your data as JSON (particularly when appending, for example,
list items).
parameters:
- description: "Patch operation to perform"
in: "header"
name: "Operation"
required: true
schema:
enum:
- "append"
- "prepend"
- "replace"
type: "string"
- description: "Type of target to patch"
in: "header"
name: "Target-Type"
required: true
schema:
enum:
- "heading"
- "block"
- "frontmatter"
type: "string"
- description: "Delimiter to use for nested targets (i.e. Headings)"
in: "header"
name: "Target-Delimiter"
required: false
schema:
default: "::"
type: "string"
- description: |
Target to patch; this value can be URL-Encoded and *must*
be URL-Encoded if it includes non-ASCII characters.
in: "header"
name: "Target"
required: true
schema:
type: "string"
- description: "Trim whitespace from Target before applying patch?"
in: "header"
name: "Trim-Target-Whitespace"
required: false
schema:
default: "false"
enum:
- "true"
- "false"
type: "string"
requestBody:
content:
application/json:
schema:
example: "['one', 'two']"
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to insert."
required: true
responses:
"200":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request; see response message for details."
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Does not exist"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Insert content into the currently open note in Obsidian relative to a heading, block reference, or frontmatter field within that document.
tags:
- "Active File"
post:
description: |
Appends content to the end of the currently-open note.
If you would like to insert text relative to a particular heading instead of appending to the end of the file, see 'patch'.
parameters: []
requestBody:
content:
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to append."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Append content to the active file open in Obsidian.
tags:
- "Active File"
put:
parameters: []
requestBody:
content:
"*/*":
schema:
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content of the file you would like to upload."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Incoming file could not be processed. Make sure you have specified a reasonable file name, and make sure you have set a reasonable 'Content-Type' header; if you are uploading a note, 'text/markdown' is likely the right choice.
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Update the content of the active file open in Obsidian.
tags:
- "Active File"
/commands/:
get:
responses:
"200":
content:
application/json:
example:
commands:
- id: "global-search:open"
name: "Search: Search in all files"
- id: "graph:open"
name: "Graph view: Open graph view"
schema:
properties:
commands:
items:
properties:
id:
type: "string"
name:
type: "string"
type: "object"
type: "array"
type: "object"
description: "A list of available commands."
summary: |
Get a list of available commands.
tags:
- "Commands"
"/commands/{commandId}/":
post:
parameters:
- description: "The id of the command to execute"
in: "path"
name: "commandId"
required: true
schema:
type: "string"
responses:
"204":
description: "Success"
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "The command you specified does not exist."
summary: |
Execute a command.
tags:
- "Commands"
"/open/{filename}":
post:
description: |
Opens the specified document in Obsidian.
Note: Obsidian will create a new document at the path you have
specified if such a document did not already exist.
parameters:
- description: |
Path to the file to return (relative to your vault root).
in: "path"
name: "filename"
required: true
schema:
format: "path"
type: "string"
- description: "Open this as a new leaf?"
in: "query"
name: "newLeaf"
required: false
schema:
type: "boolean"
responses:
"200":
description: "Success"
summary: |
Open the specified document in Obsidian
tags:
- "Open"
"/periodic/{period}/":
delete:
description: |
Deletes the periodic note for the specified period.
parameters:
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
responses:
"204":
description: "Success"
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "File does not exist."
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Delete a periodic note.
tags:
- "Periodic Notes"
get:
parameters:
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
responses:
"200":
content:
"application/vnd.olrapi.note+json":
schema:
"$ref": "#/components/schemas/NoteJson"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Success"
"404":
description: "File does not exist"
summary: |
Get current periodic note for the specified period.
tags:
- "Periodic Notes"
patch:
description: |
Inserts content into a periodic note relative to a heading, block refeerence, or frontmatter field within that document.
Allows you to modify the content relative to a heading, block reference, or frontmatter field in your document.
Note that this API was changed in Version 3.0 of this extension and the earlier PATCH API is now deprecated. Requests made using the previous version of this API will continue to work until Version 4.0 is released. See https://github.com/coddingtonbear/obsidian-local-rest-api/wiki/Changes-to-PATCH-requests-between-versions-2.0-and-3.0 for more details and migration instructions.
# Examples
All of the below examples assume you have a document that looks like
this:
```markdown
---
alpha: 1
beta: test
delta:
zeta: 1
yotta: 1
gamma:
- one
- two
---
# Heading 1
This is the content for heading one
Also references some [[#^484ef2]]
## Subheading 1:1
Content for Subheading 1:1
### Subsubheading 1:1:1
### Subsubheading 1:1:2
Testing how block references work for a table.[[#^2c7cfa]]
Some content for Subsubheading 1:1:2
More random text.
^2d9b4a
## Subheading 1:2
Content for Subheading 1:2.
some content with a block reference ^484ef2
## Subheading 1:3
| City | Population |
| ------------ | ---------- |
| Seattle, WA | 8 |
| Portland, OR | 4 |
^2c7cfa
```
## Append Content Below a Heading
If you wanted to append the content "Hello" below "Subheading 1:1:1" under "Heading 1",
you could send a request with the following headers:
- `Operation`: `append`
- `Target-Type`: `heading`
- `Target`: `Heading 1::Subheading 1:1:1`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Append Content to a Block Reference
If you wanted to append the content "Hello" below the block referenced by
"2d9b4a" above ("More random text."), you could send the following headers:
- `Operation`: `append`
- `Target-Type`: `block`
- `Target`: `2d9b4a`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Add a Row to a Table Referenced by a Block Reference
If you wanted to add a new city ("Chicago, IL") and population ("16") pair to the table above
referenced by the block reference `2c7cfa`, you could send the following
headers:
- `Operation`: `append`
- `TargetType`: `block`
- `Target`: `2c7cfa`
- `Content-Type`: `application/json`
- with the request body: `[["Chicago, IL", "16"]]`
The use of a `Content-Type` of `application/json` allows the API
to infer that member of your array represents rows and columns of your
to append to the referenced table. You can of course just use a
`Content-Type` of `text/markdown`, but in such a case you'll have to
format your table row manually instead of letting the library figure
it out for you.
You also have the option of using `prepend` (in which case, your new
row would be the first -- right below the table heading) or `replace` (in which
case all rows except the table heading would be replaced by the new row(s)
you supplied).
## Setting a Frontmatter Field
If you wanted to set the frontmatter field `alpha` to `2`, you could
send the following headers:
- `Operation`: `replace`
- `TargetType`: `frontmatter`
- `Target`: `beep`
- with the request body `2`
If you're setting a frontmatter field that might not already exist
you may want to use the `Create-Target-If-Missing` header so the
new frontmatter field is created and set to your specified value
if it doesn't already exist.
You may find using a `Content-Type` of `application/json` to be
particularly useful in the case of frontmatter since frontmatter
fields' values are JSON data, and the API can be smarter about
interpreting yoru `prepend` or `append` requests if you specify
your data as JSON (particularly when appending, for example,
list items).
parameters:
- description: "Patch operation to perform"
in: "header"
name: "Operation"
required: true
schema:
enum:
- "append"
- "prepend"
- "replace"
type: "string"
- description: "Type of target to patch"
in: "header"
name: "Target-Type"
required: true
schema:
enum:
- "heading"
- "block"
- "frontmatter"
type: "string"
- description: "Delimiter to use for nested targets (i.e. Headings)"
in: "header"
name: "Target-Delimiter"
required: false
schema:
default: "::"
type: "string"
- description: |
Target to patch; this value can be URL-Encoded and *must*
be URL-Encoded if it includes non-ASCII characters.
in: "header"
name: "Target"
required: true
schema:
type: "string"
- description: "Trim whitespace from Target before applying patch?"
in: "header"
name: "Trim-Target-Whitespace"
required: false
schema:
default: "false"
enum:
- "true"
- "false"
type: "string"
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
requestBody:
content:
application/json:
schema:
example: "['one', 'two']"
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to insert."
required: true
responses:
"200":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request; see response message for details."
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Does not exist"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Insert content into a periodic note in Obsidian relative to a heading, block reference, or frontmatter field within that document.
tags:
- "Periodic Notes"
post:
description: |
Appends content to the periodic note for the specified period. This will create the relevant periodic note if necessary.
parameters:
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
requestBody:
content:
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to append."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Append content to a periodic note.
tags:
- "Periodic Notes"
put:
parameters:
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
requestBody:
content:
"*/*":
schema:
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content of the file you would like to upload."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Incoming file could not be processed. Make sure you have specified a reasonable file name, and make sure you have set a reasonable 'Content-Type' header; if you are uploading a note, 'text/markdown' is likely the right choice.
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Update the content of a periodic note.
tags:
- "Periodic Notes"
"/periodic/{year}/{month}/{day}/{period}/":
delete:
description: |
Deletes the periodic note for the specified period.
parameters:
- description: "The year of the date for which you would like to grab a periodic note."
in: "path"
name: "year"
required: true
schema:
type: "number"
- description: "The month (1-12) of the date for which you would like to grab a periodic note."
in: "path"
name: "month"
required: true
schema:
type: "number"
- description: "The day (1-31) of the date for which you would like to grab a periodic note."
in: "path"
name: "day"
required: true
schema:
type: "number"
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
responses:
"204":
description: "Success"
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "File does not exist."
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Delete a periodic note.
tags:
- "Periodic Notes"
get:
parameters:
- description: "The year of the date for which you would like to grab a periodic note."
in: "path"
name: "year"
required: true
schema:
type: "number"
- description: "The month (1-12) of the date for which you would like to grab a periodic note."
in: "path"
name: "month"
required: true
schema:
type: "number"
- description: "The day (1-31) of the date for which you would like to grab a periodic note."
in: "path"
name: "day"
required: true
schema:
type: "number"
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
responses:
"200":
content:
"application/vnd.olrapi.note+json":
schema:
"$ref": "#/components/schemas/NoteJson"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Success"
"404":
description: "File does not exist"
summary: |
Get current periodic note for the specified period.
tags:
- "Periodic Notes"
patch:
description: |
Inserts content into a periodic note relative to a heading, block refeerence, or frontmatter field within that document.
Allows you to modify the content relative to a heading, block reference, or frontmatter field in your document.
Note that this API was changed in Version 3.0 of this extension and the earlier PATCH API is now deprecated. Requests made using the previous version of this API will continue to work until Version 4.0 is released. See https://github.com/coddingtonbear/obsidian-local-rest-api/wiki/Changes-to-PATCH-requests-between-versions-2.0-and-3.0 for more details and migration instructions.
# Examples
All of the below examples assume you have a document that looks like
this:
```markdown
---
alpha: 1
beta: test
delta:
zeta: 1
yotta: 1
gamma:
- one
- two
---
# Heading 1
This is the content for heading one
Also references some [[#^484ef2]]
## Subheading 1:1
Content for Subheading 1:1
### Subsubheading 1:1:1
### Subsubheading 1:1:2
Testing how block references work for a table.[[#^2c7cfa]]
Some content for Subsubheading 1:1:2
More random text.
^2d9b4a
## Subheading 1:2
Content for Subheading 1:2.
some content with a block reference ^484ef2
## Subheading 1:3
| City | Population |
| ------------ | ---------- |
| Seattle, WA | 8 |
| Portland, OR | 4 |
^2c7cfa
```
## Append Content Below a Heading
If you wanted to append the content "Hello" below "Subheading 1:1:1" under "Heading 1",
you could send a request with the following headers:
- `Operation`: `append`
- `Target-Type`: `heading`
- `Target`: `Heading 1::Subheading 1:1:1`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Append Content to a Block Reference
If you wanted to append the content "Hello" below the block referenced by
"2d9b4a" above ("More random text."), you could send the following headers:
- `Operation`: `append`
- `Target-Type`: `block`
- `Target`: `2d9b4a`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Add a Row to a Table Referenced by a Block Reference
If you wanted to add a new city ("Chicago, IL") and population ("16") pair to the table above
referenced by the block reference `2c7cfa`, you could send the following
headers:
- `Operation`: `append`
- `TargetType`: `block`
- `Target`: `2c7cfa`
- `Content-Type`: `application/json`
- with the request body: `[["Chicago, IL", "16"]]`
The use of a `Content-Type` of `application/json` allows the API
to infer that member of your array represents rows and columns of your
to append to the referenced table. You can of course just use a
`Content-Type` of `text/markdown`, but in such a case you'll have to
format your table row manually instead of letting the library figure
it out for you.
You also have the option of using `prepend` (in which case, your new
row would be the first -- right below the table heading) or `replace` (in which
case all rows except the table heading would be replaced by the new row(s)
you supplied).
## Setting a Frontmatter Field
If you wanted to set the frontmatter field `alpha` to `2`, you could
send the following headers:
- `Operation`: `replace`
- `TargetType`: `frontmatter`
- `Target`: `beep`
- with the request body `2`
If you're setting a frontmatter field that might not already exist
you may want to use the `Create-Target-If-Missing` header so the
new frontmatter field is created and set to your specified value
if it doesn't already exist.
You may find using a `Content-Type` of `application/json` to be
particularly useful in the case of frontmatter since frontmatter
fields' values are JSON data, and the API can be smarter about
interpreting yoru `prepend` or `append` requests if you specify
your data as JSON (particularly when appending, for example,
list items).
parameters:
- description: "Patch operation to perform"
in: "header"
name: "Operation"
required: true
schema:
enum:
- "append"
- "prepend"
- "replace"
type: "string"
- description: "Type of target to patch"
in: "header"
name: "Target-Type"
required: true
schema:
enum:
- "heading"
- "block"
- "frontmatter"
type: "string"
- description: "Delimiter to use for nested targets (i.e. Headings)"
in: "header"
name: "Target-Delimiter"
required: false
schema:
default: "::"
type: "string"
- description: |
Target to patch; this value can be URL-Encoded and *must*
be URL-Encoded if it includes non-ASCII characters.
in: "header"
name: "Target"
required: true
schema:
type: "string"
- description: "Trim whitespace from Target before applying patch?"
in: "header"
name: "Trim-Target-Whitespace"
required: false
schema:
default: "false"
enum:
- "true"
- "false"
type: "string"
- description: "The year of the date for which you would like to grab a periodic note."
in: "path"
name: "year"
required: true
schema:
type: "number"
- description: "The month (1-12) of the date for which you would like to grab a periodic note."
in: "path"
name: "month"
required: true
schema:
type: "number"
- description: "The day (1-31) of the date for which you would like to grab a periodic note."
in: "path"
name: "day"
required: true
schema:
type: "number"
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
requestBody:
content:
application/json:
schema:
example: "['one', 'two']"
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to insert."
required: true
responses:
"200":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request; see response message for details."
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Does not exist"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Insert content into a periodic note in Obsidian relative to a heading, block reference, or frontmatter field within that document.
tags:
- "Periodic Notes"
post:
description: |
Appends content to the periodic note for the specified period. This will create the relevant periodic note if necessary.
parameters:
- description: "The year of the date for which you would like to grab a periodic note."
in: "path"
name: "year"
required: true
schema:
type: "number"
- description: "The month (1-12) of the date for which you would like to grab a periodic note."
in: "path"
name: "month"
required: true
schema:
type: "number"
- description: "The day (1-31) of the date for which you would like to grab a periodic note."
in: "path"
name: "day"
required: true
schema:
type: "number"
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
requestBody:
content:
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to append."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Append content to a periodic note.
tags:
- "Periodic Notes"
put:
parameters:
- description: "The year of the date for which you would like to grab a periodic note."
in: "path"
name: "year"
required: true
schema:
type: "number"
- description: "The month (1-12) of the date for which you would like to grab a periodic note."
in: "path"
name: "month"
required: true
schema:
type: "number"
- description: "The day (1-31) of the date for which you would like to grab a periodic note."
in: "path"
name: "day"
required: true
schema:
type: "number"
- description: "The name of the period for which you would like to grab the current note."
in: "path"
name: "period"
required: true
schema:
default: "daily"
enum:
- "daily"
- "weekly"
- "monthly"
- "quarterly"
- "yearly"
type: "string"
requestBody:
content:
"*/*":
schema:
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content of the file you would like to upload."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Incoming file could not be processed. Make sure you have specified a reasonable file name, and make sure you have set a reasonable 'Content-Type' header; if you are uploading a note, 'text/markdown' is likely the right choice.
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Update the content of a periodic note.
tags:
- "Periodic Notes"
/search/:
post:
description: |
Evaluates a provided query against each file in your vault.
This endpoint supports multiple query formats. Your query should be specified in your request's body, and will be interpreted according to the `Content-type` header you specify from the below options.Additional query formats may be added in the future.
# Dataview DQL (`application/vnd.olrapi.dataview.dql+txt`)
Accepts a `TABLE`-type Dataview query as a text string. See [Dataview](https://blacksmithgu.github.io/obsidian-dataview/query/queries/)'s query documentation for information on how to construct a query.
# JsonLogic (`application/vnd.olrapi.jsonlogic+json`)
Accepts a JsonLogic query specified as JSON. See [JsonLogic](https://jsonlogic.com/operations.html)'s documentation for information about the base set of operators available, but in addition to those operators the following operators are available:
- `glob: [PATTERN, VALUE]`: Returns `true` if a string matches a glob pattern. E.g.: `{"glob": ["*.foo", "bar.foo"]}` is `true` and `{"glob": ["*.bar", "bar.foo"]}` is `false`.
- `regexp: [PATTERN, VALUE]`: Returns `true` if a string matches a regular expression. E.g.: `{"regexp": [".*\.foo", "bar.foo"]` is `true` and `{"regexp": [".*\.bar", "bar.foo"]}` is `false`.
Returns only non-falsy results. "Non-falsy" here treats the following values as "falsy":
- `false`
- `null` or `undefined`
- `0`
- `[]`
- `{}`
Files are represented as an object having the schema described
in the Schema named 'NoteJson' at the bottom of this page.
Understanding the shape of a JSON object from a schema can be
tricky; so you may find it helpful to examine the generated metadata
for individual files in your vault to understand exactly what values
are returned. To see that, access the `GET` `/vault/{filePath}`
route setting the header:
`Accept: application/vnd.olrapi.note+json`. See examples below
for working examples of queries performing common search operations.
requestBody:
content:
"application/vnd.olrapi.dataview.dql+txt":
examples:
find_fields_by_tag:
summary: "List data from files having the #game tag."
value: |
TABLE
time-played AS "Time Played",
length AS "Length",
rating AS "Rating"
FROM #game
SORT rating DESC
schema:
externalDocs:
url: "https://blacksmithgu.github.io/obsidian-dataview/query/queries/"
type: "object"
"application/vnd.olrapi.jsonlogic+json":
examples:
find_by_frontmatter_url_glob:
summary: "Find notes having URL or a matching URL glob frontmatter field."
value: |
{
"or": [
{"===": [{"var": "frontmatter.url"}, "https://myurl.com/some/path/"]},
{"glob": [{"var": "frontmatter.url-glob"}, "https://myurl.com/some/path/"]}
]
}
find_by_frontmatter_value:
summary: "Find notes having a certain frontmatter field value."
value: |
{
"==": [
{"var": "frontmatter.myField"},
"myValue"
]
}
find_by_tag:
summary: "Find notes having a certain tag"
value: |
{
"in": [
"myTag",
{"var": "tags"}
]
}
schema:
externalDocs:
url: "https://jsonlogic.com/operations.html"
type: "object"
required: true
responses:
"200":
content:
application/json:
schema:
items:
properties:
filename:
description: "Path to the matching file"
type: "string"
result:
oneOf:
- type: "string"
- type: "number"
- type: "array"
- type: "object"
- type: "boolean"
required:
- "filename"
- "result"
type: "object"
type: "array"
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Bad request. Make sure you have specified an acceptable
Content-Type for your search query.
summary: |
Search for documents matching a specified search query
tags:
- "Search"
/search/simple/:
post:
parameters:
- description: "Your search query"
in: "query"
name: "query"
required: true
schema:
type: "string"
- description: "How much context to return around the matching string"
in: "query"
name: "contextLength"
required: false
schema:
default: 100
type: "number"
responses:
"200":
content:
application/json:
schema:
items:
properties:
filename:
description: "Path to the matching file"
type: "string"
matches:
items:
properties:
context:
type: "string"
match:
properties:
end:
type: "number"
start:
type: "number"
required:
- "start"
- "end"
type: "object"
required:
- "match"
- "context"
type: "object"
type: "array"
score:
type: "number"
type: "object"
type: "array"
description: "Success"
summary: |
Search for documents matching a specified text query
tags:
- "Search"
/vault/:
get:
description: |
Lists files in the root directory of your vault.
Note: that this is exactly the same API endpoint as the below "List files that exist in the specified directory." and exists here only due to a quirk of this particular interactive tool.
responses:
"200":
content:
application/json:
example:
files:
- "mydocument.md"
- "somedirectory/"
schema:
properties:
files:
items:
type: "string"
type: "array"
type: "object"
description: "Success"
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Directory does not exist"
summary: |
List files that exist in the root of your vault.
tags:
- "Vault Directories"
"/vault/{filename}":
delete:
parameters:
- description: |
Path to the relevant file (relative to your vault root).
in: "path"
name: "filename"
required: true
schema:
format: "path"
type: "string"
responses:
"204":
description: "Success"
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "File does not exist."
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Delete a particular file in your vault.
tags:
- "Vault Files"
get:
description: |
Returns the content of the file at the specified path in your vault should the file exist.
If you specify the header `Accept: application/vnd.olrapi.note+json`, will return a JSON representation of your note including parsed tag and frontmatter data as well as filesystem metadata. See "responses" below for details.
parameters:
- description: |
Path to the relevant file (relative to your vault root).
in: "path"
name: "filename"
required: true
schema:
format: "path"
type: "string"
responses:
"200":
content:
"application/vnd.olrapi.note+json":
schema:
"$ref": "#/components/schemas/NoteJson"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Success"
"404":
description: "File does not exist"
summary: |
Return the content of a single file in your vault.
tags:
- "Vault Files"
patch:
description: |
Inserts content into an existing note relative to a heading, block refeerence, or frontmatter field within that document.
Allows you to modify the content relative to a heading, block reference, or frontmatter field in your document.
Note that this API was changed in Version 3.0 of this extension and the earlier PATCH API is now deprecated. Requests made using the previous version of this API will continue to work until Version 4.0 is released. See https://github.com/coddingtonbear/obsidian-local-rest-api/wiki/Changes-to-PATCH-requests-between-versions-2.0-and-3.0 for more details and migration instructions.
# Examples
All of the below examples assume you have a document that looks like
this:
```markdown
---
alpha: 1
beta: test
delta:
zeta: 1
yotta: 1
gamma:
- one
- two
---
# Heading 1
This is the content for heading one
Also references some [[#^484ef2]]
## Subheading 1:1
Content for Subheading 1:1
### Subsubheading 1:1:1
### Subsubheading 1:1:2
Testing how block references work for a table.[[#^2c7cfa]]
Some content for Subsubheading 1:1:2
More random text.
^2d9b4a
## Subheading 1:2
Content for Subheading 1:2.
some content with a block reference ^484ef2
## Subheading 1:3
| City | Population |
| ------------ | ---------- |
| Seattle, WA | 8 |
| Portland, OR | 4 |
^2c7cfa
```
## Append Content Below a Heading
If you wanted to append the content "Hello" below "Subheading 1:1:1" under "Heading 1",
you could send a request with the following headers:
- `Operation`: `append`
- `Target-Type`: `heading`
- `Target`: `Heading 1::Subheading 1:1:1`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Append Content to a Block Reference
If you wanted to append the content "Hello" below the block referenced by
"2d9b4a" above ("More random text."), you could send the following headers:
- `Operation`: `append`
- `Target-Type`: `block`
- `Target`: `2d9b4a`
- with the request body: `Hello`
The above would work just fine for `prepend` or `replace`, too, of course,
but with different results.
## Add a Row to a Table Referenced by a Block Reference
If you wanted to add a new city ("Chicago, IL") and population ("16") pair to the table above
referenced by the block reference `2c7cfa`, you could send the following
headers:
- `Operation`: `append`
- `TargetType`: `block`
- `Target`: `2c7cfa`
- `Content-Type`: `application/json`
- with the request body: `[["Chicago, IL", "16"]]`
The use of a `Content-Type` of `application/json` allows the API
to infer that member of your array represents rows and columns of your
to append to the referenced table. You can of course just use a
`Content-Type` of `text/markdown`, but in such a case you'll have to
format your table row manually instead of letting the library figure
it out for you.
You also have the option of using `prepend` (in which case, your new
row would be the first -- right below the table heading) or `replace` (in which
case all rows except the table heading would be replaced by the new row(s)
you supplied).
## Setting a Frontmatter Field
If you wanted to set the frontmatter field `alpha` to `2`, you could
send the following headers:
- `Operation`: `replace`
- `TargetType`: `frontmatter`
- `Target`: `beep`
- with the request body `2`
If you're setting a frontmatter field that might not already exist
you may want to use the `Create-Target-If-Missing` header so the
new frontmatter field is created and set to your specified value
if it doesn't already exist.
You may find using a `Content-Type` of `application/json` to be
particularly useful in the case of frontmatter since frontmatter
fields' values are JSON data, and the API can be smarter about
interpreting yoru `prepend` or `append` requests if you specify
your data as JSON (particularly when appending, for example,
list items).
parameters:
- description: "Patch operation to perform"
in: "header"
name: "Operation"
required: true
schema:
enum:
- "append"
- "prepend"
- "replace"
type: "string"
- description: "Type of target to patch"
in: "header"
name: "Target-Type"
required: true
schema:
enum:
- "heading"
- "block"
- "frontmatter"
type: "string"
- description: "Delimiter to use for nested targets (i.e. Headings)"
in: "header"
name: "Target-Delimiter"
required: false
schema:
default: "::"
type: "string"
- description: |
Target to patch; this value can be URL-Encoded and *must*
be URL-Encoded if it includes non-ASCII characters.
in: "header"
name: "Target"
required: true
schema:
type: "string"
- description: "Trim whitespace from Target before applying patch?"
in: "header"
name: "Trim-Target-Whitespace"
required: false
schema:
default: "false"
enum:
- "true"
- "false"
type: "string"
- description: |
Path to the relevant file (relative to your vault root).
in: "path"
name: "filename"
required: true
schema:
format: "path"
type: "string"
requestBody:
content:
application/json:
schema:
example: "['one', 'two']"
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to insert."
required: true
responses:
"200":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request; see response message for details."
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Does not exist"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Insert content into an existing note in Obsidian relative to a heading, block reference, or frontmatter field within that document.
tags:
- "Vault Files"
post:
description: |
Appends content to the end of an existing note. If the specified file does not yet exist, it will be created as an empty file.
If you would like to insert text relative to a particular heading, block reference, or frontmatter field instead of appending to the end of the file, see 'patch'.
parameters:
- description: |
Path to the relevant file (relative to your vault root).
in: "path"
name: "filename"
required: true
schema:
format: "path"
type: "string"
requestBody:
content:
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content you would like to append."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Bad Request"
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Append content to a new or existing file.
tags:
- "Vault Files"
put:
description: |
Creates a new file in your vault or updates the content of an existing one if the specified file already exists.
parameters:
- description: |
Path to the relevant file (relative to your vault root).
in: "path"
name: "filename"
required: true
schema:
format: "path"
type: "string"
requestBody:
content:
"*/*":
schema:
type: "string"
text/markdown:
schema:
example: |
# This is my document
something else here
type: "string"
description: "Content of the file you would like to upload."
required: true
responses:
"204":
description: "Success"
"400":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Incoming file could not be processed. Make sure you have specified a reasonable file name, and make sure you have set a reasonable 'Content-Type' header; if you are uploading a note, 'text/markdown' is likely the right choice.
"405":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: |
Your path references a directory instead of a file; this request method is valid only for updating files.
summary: |
Create a new file in your vault or update the content of an existing one.
tags:
- "Vault Files"
"/vault/{pathToDirectory}/":
get:
parameters:
- description: |
Path to list files from (relative to your vault root). Note that empty directories will not be returned.
Note: this particular interactive tool requires that you provide an argument for this field, but the API itself will allow you to list the root folder of your vault. If you would like to try listing content in the root of your vault using this interactive tool, use the above "List files that exist in the root of your vault" form above.
in: "path"
name: "pathToDirectory"
required: true
schema:
format: "path"
type: "string"
responses:
"200":
content:
application/json:
example:
files:
- "mydocument.md"
- "somedirectory/"
schema:
properties:
files:
items:
type: "string"
type: "array"
type: "object"
description: "Success"
"404":
content:
application/json:
schema:
"$ref": "#/components/schemas/Error"
description: "Directory does not exist"
summary: |
List files that exist in the specified directory.
tags:
- "Vault Directories"
security:
- apiKeyAuth: []
servers:
- description: "HTTPS (Secure Mode)"
url: "https://{host}:{port}"
variables:
host:
default: "127.0.0.1"
description: "Binding host"
port:
default: "27124"
description: "HTTPS port"
- description: "HTTP (Insecure Mode)"
url: "http://{host}:{port}"
variables:
host:
default: "127.0.0.1"
description: "Binding host"
port:
default: "27123"
description: "HTTP port"
```