首页
/ Outline API全栈开发指南:从基础交互到安全控制

Outline API全栈开发指南:从基础交互到安全控制

2026-03-12 03:32:27作者:仰钰奇

概述

Outline作为一款现代化的团队知识库平台,提供了功能完备的API接口体系,支持开发者构建自定义集成方案。本指南将API功能重新组织为基础交互层高级操作层安全控制层三个逻辑单元,帮助开发者系统性地掌握API的使用方法。

Outline平台logo

1. API基础架构

1.1 通信基础

所有API交互遵循RESTful设计原则,采用JSON格式进行数据交换。基础通信参数如下:

项目 说明
基础URL /api
认证方式 JWT(JSON Web Token)
请求方法 POST(统一使用POST进行操作)
数据格式 JSON
状态码 遵循HTTP标准状态码

通俗解释:JWT认证就像景区门票,初次登录后获取令牌,后续操作只需出示令牌即可,无需重复验证身份。

1.2 通用响应结构

API响应采用统一格式,包含数据、分页和权限信息:

{
  "data": [],
  "pagination": {
    "offset": 0,
    "limit": 20,
    "total": 100
  },
  "policies": {}
}
  • data:接口返回的核心数据
  • pagination:分页信息(仅列表接口返回)
  • policies:当前用户对资源的操作权限

2. 基础交互层

基础交互层提供文档管理的核心操作,包括文档的创建、查询、更新和删除等基础功能。

flowchart LR
    A[创建文档] --> B[获取文档]
    B --> C[更新文档]
    C --> D[删除文档]
    D --> E[恢复文档]

2.1 文档基础操作

2.1.1 创建新文档

创建新文档是最基础的API操作,支持设置标题、内容、所属集合等核心属性。

请求参数

参数名 类型 必需 使用场景
title string ⚠️ 所有新建文档场景
collectionId string ⚠️ 将文档归类到特定集合
text string 文档内容,ProseMirror JSON格式
parentDocumentId string 创建子文档时指定父文档
publish boolean 控制文档创建后是否立即发布
template boolean 标记文档是否为模板

适用场景:新建技术文档、会议记录、项目计划等各类内容。

注意事项

  • 标题长度建议控制在1-200字符
  • text字段需使用ProseMirror JSON格式,可通过编辑器获取
  • 未指定ID时系统会自动生成UUID

代码示例

JavaScript:

const createDocument = async (token) => {
  const response = await fetch('/api/documents.create', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      title: '2023年Q4产品规划',
      collectionId: 'coll_123456',
      text: JSON.stringify({ type: 'doc', content: [{ type: 'paragraph', content: [{ type: 'text', text: '季度目标概述' }] }] }),
      publish: true
    })
  });
  return response.json();
};

Python:

import requests
import json

def create_document(token):
    url = "/api/documents.create"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "title": "2023年Q4产品规划",
        "collectionId": "coll_123456",
        "text": json.dumps({
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "季度目标概述"}]}]
        }),
        "publish": True
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()

接口变更历史

  • 2024-03-15:新增template参数,支持创建模板文档
  • 2023-11-02:添加fullWidth参数,控制文档显示宽度
  • 2023-08-10:初始版本发布
响应示例
{
  "data": {
    "id": "doc_7890",
    "title": "2023年Q4产品规划",
    "text": "{\"type\":\"doc\",\"content\":[{\"type\":\"paragraph\",\"content\":[{\"type\":\"text\",\"text\":\"季度目标概述\"}]}]}",
    "createdAt": "2023-09-01T08:30:00Z",
    "updatedAt": "2023-09-01T08:30:00Z",
    "publishedAt": "2023-09-01T08:30:00Z",
    "collectionId": "coll_123456",
    "createdBy": {
      "id": "user_123",
      "name": "张三"
    },
    "icon": "file-text",
    "color": "#000000",
    "isTemplate": false,
    "isArchived": false,
    "isDeleted": false
  },
  "policies": {
    "canRead": true,
    "canUpdate": true,
    "canDelete": true
  }
}

2.1.2 获取文档列表

获取文档列表支持多条件筛选,满足不同场景下的文档检索需求。

请求参数

参数名 类型 必需 使用场景
collectionId string 获取特定集合下的文档
sort string 排序字段,默认"updatedAt"
direction string 排序方向,"ASC"或"DESC",默认"DESC"
statusFilter array 状态筛选:"published"、"draft"、"archived"
userId string 获取特定用户创建的文档
limit number 每页数量,默认20
offset number 分页偏移量,默认0

适用场景

  • 集合内文档浏览
  • 个人创建文档管理
  • 特定状态文档筛选

注意事项

  • 未指定collectionId时返回用户有权限访问的所有文档
  • 大量数据查询时建议使用分页参数控制返回数量

代码示例

JavaScript:

const getDocuments = async (token, collectionId) => {
  const response = await fetch('/api/documents.list', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      collectionId,
      sort: 'publishedAt',
      direction: 'DESC',
      statusFilter: ['published'],
      limit: 10,
      offset: 0
    })
  });
  return response.json();
};

Python:

def get_documents(token, collection_id):
    url = "/api/documents.list"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "collectionId": collection_id,
        "sort": "publishedAt",
        "direction": "DESC",
        "statusFilter": ["published"],
        "limit": 10,
        "offset": 0
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()

接口变更历史

  • 2024-01-20:新增backlinkDocumentId参数,支持查询引用特定文档的文档
  • 2023-09-05:添加template参数,支持筛选模板文档
  • 2023-08-10:初始版本发布

2.2 文档状态管理

文档状态管理包括发布、归档、恢复等操作,控制文档的生命周期。

2.2.1 发布文档

将文档从草稿状态转换为已发布状态,使其对有权限的用户可见。

请求参数

参数名 类型 必需 使用场景
id string ⚠️ 要发布的文档ID
detach boolean 是否从集合中分离,默认false

适用场景

  • 完成文档编辑后公开发布
  • 将草稿状态文档正式上线

注意事项

  • 发布操作会设置publishedAt时间戳
  • 只有文档创建者或管理员可以执行发布操作

代码示例

JavaScript:

const publishDocument = async (token, documentId) => {
  const response = await fetch('/api/documents.publish', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      id: documentId,
      detach: false
    })
  });
  return response.json();
};

Python:

def publish_document(token, document_id):
    url = "/api/documents.publish"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "id": document_id,
        "detach": False
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()

3. 高级操作层

高级操作层提供批量处理、版本控制、导入导出等复杂功能,满足企业级应用需求。

flowchart LR
    A[批量操作] --> B[版本控制]
    B --> C[导入导出]
    C --> D[高级搜索]

3.1 批量文档操作

批量操作接口允许同时对多个文档执行相同操作,提高管理效率。

3.1.1 批量移动文档

将多个文档同时移动到指定集合或父文档下。

请求参数

参数名 类型 必需 使用场景
documentIds array ⚠️ 要移动的文档ID列表
collectionId string ⚠️ 目标集合ID
parentDocumentId string 目标父文档ID,无子文档时为null

适用场景

  • 项目重组时的文档迁移
  • 批量整理分散的文档到指定集合

注意事项

  • 单次批量操作建议不超过50个文档
  • 确保目标集合存在且用户有写入权限

代码示例

JavaScript:

const batchMoveDocuments = async (token, documentIds, collectionId) => {
  const response = await fetch('/api/documents.batchMove', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      documentIds,
      collectionId,
      parentDocumentId: null
    })
  });
  return response.json();
};

Python:

def batch_move_documents(token, document_ids, collection_id):
    url = "/api/documents.batchMove"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "documentIds": document_ids,
        "collectionId": collection_id,
        "parentDocumentId": None
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()

接口变更历史

  • 2024-02-10:支持同时指定parentDocumentId
  • 2023-10-15:初始版本发布

3.2 文档版本控制

版本控制功能允许追踪文档的修改历史,支持查看和恢复历史版本。

3.2.1 获取文档历史版本

获取文档的所有历史修订版本列表。

请求参数

参数名 类型 必需 使用场景
id string ⚠️ 文档ID
limit number 每页数量,默认20
offset number 分页偏移量,默认0

适用场景

  • 查看文档修改记录
  • 追踪内容变更历史
  • 准备恢复到之前版本

注意事项

  • 版本按更新时间倒序排列
  • 每次文档更新(包括微小修改)都会创建新版本

代码示例

JavaScript:

const getDocumentRevisions = async (token, documentId) => {
  const response = await fetch('/api/documents.revisions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      id: documentId,
      limit: 10,
      offset: 0
    })
  });
  return response.json();
};

Python:

def get_document_revisions(token, document_id):
    url = "/api/documents.revisions"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "id": document_id,
        "limit": 10,
        "offset": 0
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()

4. 安全控制层

安全控制层提供权限管理、访问控制等安全相关功能,确保文档数据的安全访问。

flowchart LR
    A[用户权限] --> B[组权限]
    B --> C[共享链接]
    C --> D[审计日志]

4.1 用户权限管理

用户权限管理允许为不同用户分配不同级别的文档访问权限。

4.1.1 添加用户权限

为指定用户授予对文档的访问权限。

请求参数

参数名 类型 必需 使用场景
id string ⚠️ 文档ID
userId string ⚠️ 用户ID
permission string ⚠️ 权限级别:"read"、"read_write"、"admin"

适用场景

  • 协作编辑时添加协作者
  • 项目交接时授予文档访问权
  • 按角色分配不同权限级别

注意事项

  • "admin"权限允许用户修改权限设置
  • 确保用户已加入当前团队
  • 权限变更会实时生效

代码示例

JavaScript:

const addDocumentPermission = async (token, documentId, userId, permission) => {
  const response = await fetch('/api/documents.addUser', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      id: documentId,
      userId,
      permission
    })
  });
  return response.json();
};

Python:

def add_document_permission(token, document_id, user_id, permission):
    url = "/api/documents.addUser"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {token}"
    }
    data = {
        "id": document_id,
        "userId": user_id,
        "permission": permission
    }
    response = requests.post(url, headers=headers, json=data)
    return response.json()

接口变更历史

  • 2024-01-25:权限级别从"edit"重命名为"read_write"
  • 2023-09-30:初始版本发布

5. 接口组合示例

5.1 项目文档管理流程

以下示例展示了一个完整的项目文档管理流程,包括创建集合、添加文档、设置权限和导出备份。

// 1. 创建项目集合
const createProjectCollection = async (token, projectName) => {
  const response = await fetch('/api/collections.create', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      name: projectName,
      description: '项目文档集合',
      color: '#4CAF50'
    })
  });
  return response.json();
};

// 2. 创建项目文档
const createProjectDocuments = async (token, collectionId, documents) => {
  const results = [];
  for (const doc of documents) {
    const response = await fetch('/api/documents.create', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      },
      body: JSON.stringify({
        title: doc.title,
        text: doc.content,
        collectionId,
        publish: true
      })
    });
    results.push(await response.json());
  }
  return results;
};

// 3. 添加团队成员权限
const addTeamPermissions = async (token, documentIds, teamMembers) => {
  const results = [];
  for (const docId of documentIds) {
    for (const member of teamMembers) {
      const response = await fetch('/api/documents.addUser', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
          id: docId,
          userId: member.id,
          permission: member.permission
        })
      });
      results.push(await response.json());
    }
  }
  return results;
};

// 4. 导出项目文档备份
const exportProjectDocuments = async (token, collectionId) => {
  const response = await fetch('/api/collections.export', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${token}`
    },
    body: JSON.stringify({
      id: collectionId,
      format: 'markdown'
    })
  });
  
  // 处理文件下载
  const blob = await response.blob();
  const url = URL.createObjectURL(blob);
  const a = document.createElement('a');
  a.href = url;
  a.download = 'project-backup.zip';
  a.click();
  URL.revokeObjectURL(url);
};

// 执行完整流程
const setupProjectDocumentation = async (token, projectName, documents, teamMembers) => {
  try {
    // 创建集合
    const { data: collection } = await createProjectCollection(token, projectName);
    
    // 创建文档
    const documentResults = await createProjectDocuments(token, collection.id, documents);
    const documentIds = documentResults.map(res => res.data.id);
    
    // 设置权限
    await addTeamPermissions(token, documentIds, teamMembers);
    
    // 导出备份
    await exportProjectDocuments(token, collection.id);
    
    return { success: true, collectionId: collection.id, documentIds };
  } catch (error) {
    console.error('项目文档设置失败:', error);
    return { success: false, error: error.message };
  }
};

6. 常见问题诊断

6.1 API调用故障排查

flowchart TD
    A[API调用失败] --> B{状态码是什么?}
    B -->|401| C[检查JWT令牌]
    B -->|403| D[验证权限设置]
    B -->|404| E[确认资源ID是否正确]
    B -->|422| F[检查请求参数格式]
    B -->|500| G[查看服务器日志]
    
    C --> H[令牌是否过期?]
    H -->|是| I[重新获取令牌]
    H -->|否| J[检查令牌格式]
    
    D --> K[用户是否有操作权限?]
    K -->|否| L[申请更高权限]
    
    F --> M[使用API验证工具检查参数]

6.2 常见错误及解决方法

错误类型 可能原因 解决方案
401 Unauthorized 令牌过期或无效 重新登录获取新令牌
403 Forbidden 权限不足 联系文档管理员提升权限
422 Validation Error 请求参数格式错误 检查参数类型和必填项
429 Too Many Requests 超过API调用频率限制 实现请求限流或等待冷却
500 Server Error 服务器内部错误 检查系统状态或联系技术支持

7. 接口调用频率限制

为保障系统稳定性,API实施以下调用频率限制:

  • 普通接口:每分钟25次请求
  • 搜索接口:每分钟100次请求
  • 批量操作接口:每分钟5次请求

建议在实现时添加请求限流机制,当收到429状态码时,可使用指数退避策略重试。

8. 总结

本指南以分层架构重新组织了Outline API,从基础交互到高级操作再到安全控制,全面覆盖了API的核心功能。通过提供详细的参数说明、代码示例和使用场景,帮助开发者快速掌握API的使用方法。

建议开发者在实际应用中:

  • 优先使用批量接口减少请求次数
  • 实施适当的错误处理和重试机制
  • 定期备份重要数据
  • 遵循最小权限原则管理文档访问权限

通过合理利用Outline API,可以构建强大的自定义集成方案,满足团队协作和知识管理的多样化需求。

登录后查看全文
热门项目推荐
相关项目推荐