首页
/ Outline API 完全指南:从入门到精通

Outline API 完全指南:从入门到精通

2026-03-12 04:01:58作者:余洋婵Anita

概述

Outline 是一个基于 React 和 Node.js 打造的快速、协作式团队知识库。它可以让团队方便地存储和管理知识信息。通过 Outline 提供的 RESTful API,开发者可以与系统深度集成,实现文档的创建、查询、更新和删除等操作。本文将从核心概念、操作指南、高级应用到问题解决,全面介绍 Outline API 的使用方法和最佳实践。

Outline 项目标志

一、核心概念

1.1 API 设计理念

Outline API 采用 RESTful 设计风格,遵循以下核心原则:

  • 资源导向:将文档、集合等抽象为资源,通过 URL 唯一标识
  • 统一接口:使用标准 HTTP 方法(POST)进行操作
  • 无状态:每个请求都包含所有必要信息,服务器不存储客户端状态
  • JSON 优先:所有请求和响应均使用 JSON 格式
  • 权限分离:通过 policies 字段明确资源访问权限

这种设计使得 API 具有良好的可读性、一致性和可扩展性,同时降低了学习成本。

1.2 基础架构

Outline API 的请求处理流程如下:

sequenceDiagram
    participant Client
    participant Auth Middleware
    participant API Controller
    participant Service Layer
    participant Database
    
    Client->>Auth Middleware: 请求 (带JWT令牌)
    Auth Middleware->>Auth Middleware: 验证令牌
    Auth Middleware->>API Controller: 转发请求
    API Controller->>Service Layer: 业务逻辑处理
    Service Layer->>Database: 数据操作
    Database-->>Service Layer: 返回数据
    Service Layer-->>API Controller: 处理结果
    API Controller-->>Client: 响应 (JSON格式)

1.3 核心数据模型

Outline API 围绕以下核心数据模型构建:

classDiagram
    class Document {
        +string id
        +string title
        +string text
        +string collectionId
        +string parentDocumentId
        +datetime createdAt
        +datetime updatedAt
        +datetime publishedAt
        +boolean isTemplate
        +string icon
        +string color
    }
    
    class Collection {
        +string id
        +string name
        +string description
        +string color
    }
    
    class User {
        +string id
        +string name
        +string email
    }
    
    Document "N" -- "1" Collection : belongs to
    Document "1" -- "N" Document : has children
    User "N" -- "N" Document : has permissions

1.4 认证机制

Outline API 使用 JWT(JSON Web Token)进行认证:

  1. 用户通过登录接口获取 JWT 令牌
  2. 后续请求在 HTTP 头部包含 Authorization: Bearer <token>
  3. 服务器验证令牌有效性和权限

二、操作指南

2.1 环境准备

在开始使用 Outline API 前,需要完成以下准备工作:

  1. 确保 Outline 服务已正确部署并运行
  2. 创建具有 API 访问权限的用户账户
  3. 获取 JWT 认证令牌

获取认证令牌的示例代码:

// 获取JWT令牌
async function getAuthToken(email, password) {
  const response = await fetch('/api/auth.login', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ email, password }),
  });
  
  const data = await response.json();
  return data.data.token; // 返回JWT令牌
}

2.2 文档管理基础操作

2.2.1 创建文档

创建新文档是最常用的操作之一,以下是完整示例:

async function createDocument(token, documentData) {
  // 发送POST请求到文档创建接口
  const response = await fetch('/api/documents.create', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}` // 包含JWT令牌
    },
    body: JSON.stringify(documentData),
  });
  
  const result = await response.json();
  
  // 处理响应结果
  if (result.error) {
    console.error('创建文档失败:', result.error.message);
    return null;
  }
  
  return result.data; // 返回新创建的文档信息
}

// 使用示例
const newDoc = await createDocument(token, {
  title: "API使用指南",
  text: "这是通过API创建的文档内容",
  collectionId: "your-collection-id",
  publish: true,
  icon: "file-text",
  color: "#3498db"
});

创建文档的主要参数说明:

参数名 类型 描述 必要性
title string 文档标题 必需
text string 文档内容(ProseMirror JSON格式) 必需
collectionId string 所属集合ID 必需
publish boolean 是否立即发布 可选,默认false
parentDocumentId string 父文档ID,用于创建子文档 可选
icon string 文档图标 可选
color string 图标颜色(十六进制) 可选
template boolean 是否作为模板文档 可选,默认false

2.2.2 获取文档列表

获取文档列表可以根据多种条件进行筛选:

async function getDocuments(token, filters = {}) {
  const response = await fetch('/api/documents.list', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      sort: 'updatedAt',    // 排序字段
      direction: 'DESC',    // 排序方向
      limit: 20,            // 每页数量
      ...filters            // 应用筛选条件
    }),
  });
  
  const result = await response.json();
  return result;
}

// 获取特定集合的文档
const collectionDocs = await getDocuments(token, {
  collectionId: "target-collection-id",
  statusFilter: ["published"]  // 只获取已发布文档
});

2.2.3 更新文档

更新文档可以修改标题、内容、状态等属性:

async function updateDocument(token, documentId, updates) {
  const response = await fetch('/api/documents.update', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      id: documentId,  // 要更新的文档ID
      ...updates       // 更新内容
    }),
  });
  
  const result = await response.json();
  return result.data;
}

// 更新文档标题和内容
const updatedDoc = await updateDocument(token, "document-id", {
  title: "更新后的标题",
  text: "更新后的内容",
  publish: true
});

2.2.4 删除文档

删除文档操作默认会将文档移至回收站:

async function deleteDocument(token, documentId, permanent = false) {
  const response = await fetch('/api/documents.delete', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      id: documentId,
      permanent: permanent  // 是否永久删除
    }),
  });
  
  const result = await response.json();
  return result.data;
}

// 将文档移至回收站
await deleteDocument(token, "document-id");

// 永久删除文档(谨慎使用)
// await deleteDocument(token, "document-id", true);

2.3 文档状态管理

文档在其生命周期中有多种状态,通过 API 可以灵活管理:

2.3.1 文档状态流转

stateDiagram
    [*] --> Draft
    Draft --> Published: 发布(publish)
    Published --> Draft: 取消发布(unpublish)
    Published --> Archived: 归档(archive)
    Archived --> Published: 恢复(restore)
    Draft --> Deleted: 删除(delete)
    Published --> Deleted: 删除(delete)
    Archived --> Deleted: 删除(delete)
    Deleted --> [*]: 永久删除(permanent)
    Deleted --> Published: 恢复(restore)

2.3.2 常用状态操作

// 归档文档
async function archiveDocument(token, documentId) {
  const response = await fetch('/api/documents.archive', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({ id: documentId }),
  });
  return await response.json();
}

// 恢复文档
async function restoreDocument(token, documentId, collectionId) {
  const response = await fetch('/api/documents.restore', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({ id: documentId, collectionId }),
  });
  return await response.json();
}

// 取消发布
async function unpublishDocument(token, documentId) {
  const response = await fetch('/api/documents.unpublish', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({ id: documentId }),
  });
  return await response.json();
}

三、高级应用

3.1 文档搜索功能

Outline API 提供了强大的搜索能力,可以搜索文档标题或内容:

async function searchDocuments(token, query, options = {}) {
  // 搜索文档内容
  const response = await fetch('/api/documents.search', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      query: query,           // 搜索关键词
      collectionId: options.collectionId,  // 可选:限定集合
      statusFilter: options.statusFilter || ["published"],  // 文档状态
      snippetMinWords: 10,    // 摘要最小单词数
      snippetMaxWords: 30     // 摘要最大单词数
    }),
  });
  
  const result = await response.json();
  return result;
}

// 搜索包含"API"关键词的文档
const searchResults = await searchDocuments(token, "API", {
  collectionId: "target-collection-id"
});

3.2 权限管理

Outline 支持细粒度的权限控制,可以为用户或组设置不同级别的文档访问权限:

// 添加用户权限
async function addDocumentPermission(token, documentId, userId, permission) {
  const response = await fetch('/api/documents.add_user', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      id: documentId,
      userId: userId,
      permission: permission  // 权限级别:read, read_write, admin
    }),
  });
  return await response.json();
}

// 为用户添加读写权限
await addDocumentPermission(token, "document-id", "user-id", "read_write");

权限级别说明:

权限级别 描述
read 只读权限,只能查看文档
read_write 读写权限,可以查看和编辑文档
admin 管理员权限,可以管理文档权限和删除文档

3.3 批量操作

对于需要处理多个文档的场景,可以实现批量操作功能:

// 批量移动文档到指定集合
async function batchMoveDocuments(token, documentIds, collectionId) {
  // 并发执行移动操作
  const promises = documentIds.map(id => 
    fetch('/api/documents.move', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        id: id,
        collectionId: collectionId
      }),
    }).then(res => res.json())
  );
  
  // 等待所有操作完成
  const results = await Promise.all(promises);
  return results;
}

// 批量移动多个文档
await batchMoveDocuments(token, ["doc1-id", "doc2-id"], "target-collection-id");

四、问题解决

4.1 常见错误处理

Outline API 使用标准 HTTP 状态码表示请求结果,常见错误及处理方法:

状态码 错误类型 可能原因 解决方案
400 错误请求 请求参数格式错误 检查请求参数是否符合API要求
401 未授权 令牌无效或已过期 重新获取JWT令牌
403 权限不足 用户没有操作权限 检查用户权限设置
404 资源不存在 请求的文档或集合不存在 验证资源ID是否正确
422 验证错误 请求参数验证失败 检查并修正参数值
429 请求频率超限 API调用过于频繁 实现请求限流机制
500 服务器错误 服务器内部问题 检查服务器日志,联系管理员

错误响应处理示例:

async function safeApiCall(fetchFn) {
  try {
    const response = await fetchFn();
    
    // 检查HTTP状态码
    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(`${errorData.error.name}: ${errorData.error.message}`);
    }
    
    return await response.json();
  } catch (error) {
    console.error('API调用失败:', error.message);
    
    // 根据错误类型进行特定处理
    if (error.message.includes('Unauthorized')) {
      console.log('令牌已过期,需要重新登录');
      // 触发重新登录逻辑
    }
    
    throw error; // 重新抛出错误供上层处理
  }
}

// 使用安全调用包装器
const result = await safeApiCall(() => 
  fetch('/api/documents.info', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({ id: documentId }),
  })
);

4.2 性能优化

为提高 API 调用效率,建议采取以下优化措施:

  1. 批量操作:尽量使用批量操作减少 API 调用次数
  2. 字段筛选:只请求需要的字段,减少数据传输量
  3. 分页处理:对大量数据使用分页,避免一次性加载过多数据
  4. 缓存策略:缓存不常变化的数据,减少重复请求
  5. 并发控制:合理控制并发请求数量,避免触发限流

4.3 调试技巧

API 开发调试建议:

  1. 使用 Postman 或 Insomnia 等 API 测试工具进行手动测试
  2. 开启详细日志记录,包括请求和响应数据
  3. 使用 API 版本控制,确保兼容性
  4. 实现请求重试机制,处理临时网络问题
  5. 使用浏览器开发者工具监控网络请求

五、最佳实践

5.1 API 调用规范

为确保 API 调用的稳定性和可维护性,建议遵循以下规范:

  1. 错误处理:始终处理可能的错误情况,包括网络错误和业务错误
  2. 认证管理:实现令牌自动刷新机制,处理令牌过期
  3. 请求验证:在发送请求前验证参数,减少无效请求
  4. 响应处理:统一的响应处理逻辑,便于错误跟踪和调试
  5. 资源释放:确保及时取消不再需要的请求,避免资源浪费

5.2 安全最佳实践

  1. 令牌安全:JWT 令牌应妥善保管,避免在客户端存储中明文保存
  2. 权限最小化:遵循最小权限原则,只授予必要的权限
  3. 输入验证:严格验证所有输入数据,防止注入攻击
  4. HTTPS:始终使用 HTTPS 协议进行 API 通信
  5. 请求签名:对于敏感操作,考虑实现请求签名机制

5.3 常见场景案例

案例一:文档自动化生成

自动从其他系统导入内容并创建 Outline 文档:

// 从外部系统获取数据并创建文档
async function importFromExternalSystem(token, externalData) {
  // 转换外部数据为Outline文档格式
  const documentData = {
    title: externalData.title,
    text: convertToProseMirrorJSON(externalData.content),
    collectionId: "import-target-collection",
    publish: true,
    icon: "file-text",
    color: "#2ecc71"
  };
  
  // 创建文档
  return createDocument(token, documentData);
}

案例二:文档版本管理

实现简单的文档版本控制:

// 创建文档快照(版本)
async function createDocumentSnapshot(token, documentId, snapshotName) {
  // 1. 获取当前文档内容
  const docInfo = await getDocumentInfo(token, documentId);
  
  // 2. 创建新文档作为快照
  return createDocument(token, {
    title: `[快照] ${snapshotName} - ${docInfo.data.document.title}`,
    text: docInfo.data.document.text,
    collectionId: "snapshots-collection-id",
    publish: false,
    icon: "clock",
    color: "#95a5a6"
  });
}

六、附录

6.1 API 测试工具推荐

Postman

功能全面的 API 测试工具,支持请求创建、集合管理、环境配置等功能。

使用方法:

  1. 创建新的请求集合
  2. 配置环境变量存储基础 URL 和令牌
  3. 创建请求并保存到集合
  4. 使用集合 runner 进行批量测试

curl

命令行工具,适合自动化脚本和快速测试:

# 获取文档列表示例
curl -X POST https://your-outline-instance.com/api/documents.list \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -d '{"collectionId": "your-collection-id", "limit": 10}'

6.2 接口参考速查表

常用 API 端点概览:

功能 接口地址 请求方法 主要参数
获取文档列表 /api/documents.list POST collectionId, sort, limit
创建文档 /api/documents.create POST title, text, collectionId
获取文档详情 /api/documents.info POST id
更新文档 /api/documents.update POST id, title, text
删除文档 /api/documents.delete POST id, permanent
搜索文档 /api/documents.search POST query, collectionId
添加用户权限 /api/documents.add_user POST id, userId, permission
移动文档 /api/documents.move POST id, collectionId, parentDocumentId
复制文档 /api/documents.duplicate POST id, title, collectionId

6.3 状态码速查表

类别 状态码 含义
成功 200 请求成功
客户端错误 400 请求参数错误
客户端错误 401 未授权
客户端错误 403 权限不足
客户端错误 404 资源不存在
客户端错误 422 验证错误
客户端错误 429 请求频率超限
服务器错误 500 服务器内部错误
登录后查看全文
热门项目推荐
相关项目推荐