dnd5-scripts/obsidian_rest_api.md

258 lines
8.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## Locar REST API with MCP
Here is the transcribed text from the provided images, with the values updated to your specified configuration.
### Local REST API with MCP
#### How to access via REST
You can access the Obsidian local REST API & MCP server via the following URL:
* **Encrypted (HTTPS) API URL:** `[https://127.0.0.1:27124/](https://127.0.0.1:27124/)`
*Requires that this certificate be configured as a trusted certificate authority for your browser.*
**Authorization:**
Your API key should be passed as a bearer token via the `Authorization` header:
`Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e`
---
#### How to access via MCP
You can connect to the MCP server via the following endpoint:
* **Encrypted (HTTPS) MCP Endpoint:** `[https://127.0.0.1:27124/mcp/](https://127.0.0.1:27124/mcp/)`
*Requires that this certificate be configured as a trusted certificate authority.*
**Authorization:**
Your API key should be passed as a bearer token via the `Authorization` header:
`Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e`
---
### Example Claude Configuration
Example Claude code MCP configuration (for `.Claude/settings.json`):
```json
{
"mcpServers": {
"obsidian": {
"type": "http",
"url": "https://127.0.0.1:27124/mcp/",
"headers": {
"Authorization": "Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e"
}
}
}
}
```
---
### Settings Overview
* **Enable non-encrypted (HTTP) server:** Enables a non-encrypted (HTTP) server on the port designated. By default, this plugin requires a secure HTTPS connection.
* **Reset all cryptography:** Pressing this button will cause your certificate, private key, public key, and API key to be regenerated.
* **Re-generate certificates:** Pressing this button will cause your certificate, private key, and public key to be re-generated, but your API key will remain unchanged.
* **Restore default settings:** Pressing this button will reset this plugin's settings to defaults.
* **Show advanced settings:** Advanced settings are dangerous and may make your configuration unstable.
---
### Примеры запросов
1) Вывести список файлов в папке:
```
curl -k "https://127.0.0.1:27124/vault/Фракции" ^
-H "Authorization: Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e" ^
--insecure
```
```
{
"files": [
"Tests/",
"Арфисты/",
"Башня Колдовства Лускана.md",
"Гильдии воров.md",
"Гоблины, отряды.md",
"Жентарим/",
"ИП/",
"Корабль Курта.md",
"Краснометки/",
"Магические ордена.md",
"Орден Перчатки/",
"Орки, отряды.md",
"Племя Каменной Пасти.md",
"Торговые дома/",
"Фракции.md",
"Церкви/"
]
}
```
2) Поиск файла по имени `Test_Faction_B`:
```
curl --request POST --url "https://127.0.0.1:27124/search/simple/?query=Test_Faction_B" --header "Accept: application/json" --header "Authorization: Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e" --header "Content-Type: application/json" --insecure
[
{
"filename": "Фракции/Tests/Test_Faction_B.md",
"score": -0.0638,
"matches": [
{
"match": {
"start": 0,
"end": 14,
"source": "filename"
},
"context": "Test_Faction_B"
}
]
}
]
```
3) Пример запроса на получение содержимого файла `Фракции/Tests/Test_Faction_B.md`:
```
curl --request GET --url https://127.0.0.1:27124/vault/Фракции/Tests/Test_Faction_B.md --header "Accept: application/json, application/vnd.olrapi.document-map+json, application/vnd.olrapi.note+json, text/html, text/markdown" --header "Authorization: Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e" --header "Markdown-Patch-Version: " --header "Target-Scope: " --insecure
---
force: 2
wealth: 4
cunning: 2
magic: None
hp: 10
hp_max: 10
treasure: 15
state: active
locations:
- "[[Test Location]]"
faction_tags: []
assets:
- name: "Base of Influence — Test Location"
is_base_of_influence: true
hp: 10
hp_max: 10
location: "[[Test Location]]"
cost: 10
- name: Armed Guards
is_base_of_influence: false
hp: 3
hp_max: 3
location: "[[Test Location]]"
attribute: Wealth
tier_required: 1
cost: 1
---
# Test Faction B
Файл для автоматических тестов.
```
4) Перезапись frontmatter, не трогая текст:
```
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$uri = "https://127.0.0.1:27124/vault/Фракции/Tests/Test_Faction_B.md"
$headers = @{
"Authorization" = "Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e"
"Content-Type" = "text/markdown; charset=utf-8"
}
# 1. Получаем текущий контент
$fullContent = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
# 2. Отделяем тело файла от фронтматтера
if ($fullContent -match '(?s)^---\r?\n(.*?)\r?\n---\r?\n(.*)') {
$existingBody = $matches[2]
} else {
$existingBody = $fullContent
}
# 3. Ваш НОВЫЙ фронтматтер
$newFrontmatter = @"
---
force: 10
wealth: 20
new_field: true
---
"@
# 4. Соединяем новый фронтматтер и старое тело
$finalContent = $newFrontmatter + "`n" + $existingBody
# 5. Записываем файл обратно
Invoke-RestMethod -Method Put -Uri $uri -Headers $headers -Body ([System.Text.Encoding]::UTF8.GetBytes($finalContent))
```
5) Изменение / добавление во frontmatter поля apple == 3:
```
curl -X PATCH "https://127.0.0.1:27124/vault/Фракции/Tests/Test_Faction_B.md" ^
-H "Authorization: Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e" ^
-H "Operation: replace" ^
-H "Target-Type: frontmatter" ^
-H "Target: apple" ^
-H "Create-Target-If-Missing: true" ^
-H "Content-Type: application/json" ^
-d "3" ^
--insecure
```
6) Удаление поля:
```
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$uri = "https://127.0.0.1:27124/vault/Фракции/Tests/Test_Faction_B.md"
$headers = @{ "Authorization" = "Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e" }
# 1. Получение текущего контента
$response = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
$currentContent = $response
# 2. Удаление строки с полем apple (регулярное выражение удаляет всю строку с ключом)
$newContent = $currentContent -replace '(?m)^force:.*(\r?\n)?', ''
# 3. Полная перезапись через PUT
$headersPUT = @{
"Authorization" = "Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e"
"Content-Type" = "text/markdown"
}
Invoke-RestMethod -Method Put -Uri $uri -Headers $headersPUT -Body $newContent
```
7) `create_file` (PUT для создания файла)
В `vault_utils.py` метод `create_file` использует `PUT`. У вас есть пример с `PUT` в пункте 4, но он используется как "костыль" для удаления поля.
**Что добавить:** Одиночный пример создания нового файла (или перезаписи) без предварительного чтения. Это стандартная задача "Создать заметку", которой не хватает в списке примеров.
```yaml
curl -X PUT "https://127.0.0.1:27124/vault/Фракции/Tests/New_Faction.md" ^
-H "Authorization: Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e" ^
-H "Content-Type: text/markdown" ^
-d "# New Faction2" ^
--insecure
```
или многострочный текст через Powershell:
```
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$uri = "https://127.0.0.1:27124/vault/Фракции/Tests/New_Faction.md"
$headers = @{
"Authorization" = "Bearer 31c4ee60e78cea8503d0ac076298a0da6f5cbc3992f4e4cdc97d84fcbf27248e"
"Content-Type" = "text/markdown; charset=utf-8"
}
$body = [System.Text.Encoding]::UTF8.GetBytes("# New Faction`r`nКонтент заметки")
Invoke-RestMethod -Method Put -Uri $uri -Headers $headers -Body $body
```