首页
/ Outline API集成开发指南:从基础到高级应用

Outline API集成开发指南:从基础到高级应用

2026-03-12 03:05:36作者:伍希望

核心概念:API集成基础

API架构概述

Outline提供的RESTful API是连接第三方系统与团队知识库的桥梁,基于JWT认证机制,采用JSON格式进行数据交换。通过这些接口,开发者可以实现对文档的全生命周期管理,构建自定义工作流或集成到现有系统中。

Outline API架构示意图

图1:Outline项目标志,象征知识管理与文档协作的核心功能

基础交互模型

所有API交互遵循统一的请求-响应模式:

  • 基础URL/api
  • 认证方式:JWT令牌(在请求头中使用Authorization: Bearer <token>格式)
  • 数据格式:请求与响应均为JSON
  • 标准响应结构
    {
      "pagination": { "offset": 0, "limit": 20, "total": 100 },
      "data": [],
      "policies": {}
    }
    

[!TIP] API版本控制通过请求参数apiVersion实现,目前支持版本1和2,建议使用最新版本以获得完整功能支持。

操作指南:API核心功能实现

文档基础操作API集成

创建文档

接口信息POST /api/documents.create

请求参数

参数名 类型 必需 描述
title string 文档标题,长度限制1-255字符
text string 文档内容,ProseMirror JSON格式
collectionId string 所属集合ID
publish boolean 是否发布,默认false
parentDocumentId string 父文档ID,用于创建子文档

请求示例(JavaScript)

fetch('/api/documents.create', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'
  },
  body: JSON.stringify({
    title: "API集成指南",
    text: JSON.stringify({ type: "doc", content: [{ type: "paragraph", content: [{ type: "text", text: "Outline API使用指南" }]}]}),
    collectionId: "col_123456",
    publish: true
  })
})
.then(response => response.json())
.then(data => console.log("创建结果:", data));

请求示例(Python)

import requests
import json

url = "/api/documents.create"
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
}
data = {
    "title": "API集成指南",
    "text": json.dumps({ 
        "type": "doc", 
        "content": [{ 
            "type": "paragraph", 
            "content": [{ "type": "text", "text": "Outline API使用指南" }]
        }]
    }),
    "collectionId": "col_123456",
    "publish": True
}

response = requests.post(url, headers=headers, json=data)
print("创建结果:", response.json())

流程图

sequenceDiagram
    participant Client
    participant Server
    Client->>Server: 发送创建文档请求(POST /api/documents.create)
    Server->>Server: 验证JWT令牌
    Server->>Server: 验证请求参数
    Server->>Server: 创建文档记录
    Server->>Server: 生成文档ID
    Server-->>Client: 返回文档信息(200 OK)

获取文档详情

接口信息POST /api/documents.info

请求参数

  • id: 文档ID(必需)
  • shareId: 共享链接ID(可选,用于访问共享文档)

响应示例

{
  "data": {
    "document": {
      "id": "doc_789",
      "title": "API集成指南",
      "text": "{\"type\":\"doc\",\"content\":[...]} ",
      "createdAt": "2025-01-15T10:30:00Z",
      "updatedAt": "2025-01-15T10:30:00Z",
      "collectionId": "col_123456",
      "createdBy": {
        "id": "user_123",
        "name": "开发者"
      }
    }
  },
  "policies": {
    "canRead": true,
    "canUpdate": true,
    "canDelete": true
  }
}

文档批量处理API集成

批量获取文档列表

接口信息POST /api/documents.list

请求参数

参数名 类型 描述
sort string 排序字段:createdAt/updatedAt/publishedAt
direction string 排序方向:ASC/DESC
collectionId string 按集合筛选
statusFilter array 状态筛选:published/draft/archived
offset number 分页偏移量,默认0
limit number 每页数量,默认20

请求示例(Java)

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.HashMap;
import java.util.Map;
import com.google.gson.Gson;

public class DocumentListExample {
    public static void main(String[] args) throws Exception {
        HttpClient client = HttpClient.newHttpClient();
        Gson gson = new Gson();
        
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("collectionId", "col_123456");
        requestBody.put("sort", "updatedAt");
        requestBody.put("direction", "DESC");
        requestBody.put("limit", 10);
        
        HttpRequest request = HttpRequest.newBuilder()
            .uri(URI.create("/api/documents.list"))
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
            .POST(HttpRequest.BodyPublishers.ofString(gson.toJson(requestBody)))
            .build();
            
        client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(HttpResponse::body)
            .thenAccept(System.out::println)
            .join();
    }
}

流程图

sequenceDiagram
    participant Client
    participant Server
    Client->>Server: 请求文档列表(POST /api/documents.list)
    Server->>Server: 验证权限
    Server->>Server: 执行数据库查询
    Server->>Server: 应用筛选条件和排序
    Server->>Server: 生成分页信息
    Server-->>Client: 返回文档列表和分页数据

批量移动文档

接口信息POST /api/documents.move

请求参数

  • id: 文档ID(必需)
  • collectionId: 目标集合ID(必需)
  • parentDocumentId: 目标父文档ID(可选)
  • index: 在父文档中的位置索引(可选)

[!TIP] 批量操作建议使用事务处理,确保操作的原子性。如遇网络中断,可通过查询文档状态确认操作结果。

进阶应用:API集成最佳实践

接口调用频率控制

Outline API实施调用频率限制,确保系统稳定性:

  • 普通接口:每分钟25次请求
  • 搜索接口:每分钟100次请求

当超出限制时,API将返回429状态码,建议实现指数退避重试机制:

async function apiRequestWithRetry(url, options, retries = 3, delay = 1000) {
  try {
    const response = await fetch(url, options);
    if (response.status === 429 && retries > 0) {
      await new Promise(resolve => setTimeout(resolve, delay));
      return apiRequestWithRetry(url, options, retries - 1, delay * 2);
    }
    return response;
  } catch (error) {
    if (retries > 0) {
      await new Promise(resolve => setTimeout(resolve, delay));
      return apiRequestWithRetry(url, options, retries - 1, delay * 2);
    }
    throw error;
  }
}

错误处理与调试

常见错误码说明
状态码 错误类型 处理建议
400 请求参数错误 检查请求体格式和参数值
401 未授权 重新获取JWT令牌
403 权限不足 检查用户对资源的访问权限
404 资源不存在 验证文档ID或集合ID是否正确
422 验证错误 根据返回的details字段修正输入
429 请求频率超限 实现请求限流或重试机制
500 服务器错误 记录错误详情并联系支持团队

错误响应格式示例:

{
  "error": {
    "name": "ValidationError",
    "message": "无效的输入数据",
    "status": 422,
    "details": [
      {
        "path": ["title"],
        "message": "文档标题不能为空"
      }
    ]
  }
}

接口调试工具推荐

  1. Postman:可视化API测试工具,支持请求历史记录和环境变量管理
  2. curl:命令行工具,适合自动化测试和CI/CD集成
    curl -X POST /api/documents.info \
      -H "Content-Type: application/json" \
      -H "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..." \
      -d '{"id": "doc_789"}'
    
  3. Insomnia:开源API客户端,支持GraphQL和REST,提供美观的界面和协作功能

API版本兼容性说明

API版本 主要变化 兼容性说明
v1 初始版本 基础文档操作功能
v2 新增字段和筛选选项 向下兼容v1,新增backlinkDocumentId等参数

建议在请求中明确指定API版本:

{
  "id": "doc_789",
  "apiVersion": 2
}

总结

本文详细介绍了Outline API的集成方法,从基础概念到高级应用,涵盖了文档的创建、查询、批量处理等核心功能。通过遵循最佳实践和错误处理机制,开发者可以构建稳定可靠的集成方案。无论是构建自定义前端界面、实现自动化工作流,还是与其他系统集成,Outline API都提供了灵活而强大的接口支持。

完整的API文档可参考项目源代码中的路由定义文件,更多高级功能和接口细节请查阅官方开发文档。

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