Skip to content

API 文档指南

一句话总结:编写清晰、完整的 API 文档。

📍 本章定位

  • 服务方案:全部方案
  • 学习方式:📖 选学
  • 在流程中的作用:编写清晰、完整的 API 文档
  • 核心知识点:API 设计、文档规范、工具使用
  • 预计时长:按需查阅
  • 完成后能做什么:能够编写清晰、完整的 API 文档

一、API 文档总览

1.1 API 文档类型

1.2 API 文档要素

要素说明重要性
概述API 简介、使用场景
认证认证方式、Token 获取
端点URL、方法、参数
请求请求格式、Headers、Body
响应响应格式、状态码、错误码
示例请求示例、响应示例
SDK客户端库、使用方法

二、REST API 文档

2.1 OpenAPI/Swagger

问题:API 文档不规范,难以维护。

解决方案:使用 OpenAPI/Swagger 规范。

配置示例

yaml
# openapi.yaml
openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
  description: My API description

servers:
  - url: https://api.example.com/v1

paths:
  /users:
    get:
      summary: Get all users
      description: Get all users
      operationId: getUsers
      tags:
        - users
      responses:
        '200':
          description: Successful operation
          content:
            application/json:
              schema:
                type: array
                items:
                  $ref: '#/components/schemas/User'
        '500':
          description: Internal server error

    post:
      summary: Create a user
      description: Create a user
      operationId: createUser
      tags:
        - users
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: '#/components/schemas/UserInput'
      responses:
        '201':
          description: Successful operation
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/User'
        '400':
          description: Bad request
        '500':
          description: Internal server error

components:
  schemas:
    User:
      type: object
      properties:
        id:
          type: integer
          format: int64
        name:
          type: string
        email:
          type: string
          format: email
      required:
        - id
        - name
        - email

    UserInput:
      type: object
      properties:
        name:
          type: string
        email:
          type: string
          format: email
      required:
        - name
        - email

优点

  • 标准化规范
  • 自动生成文档
  • 支持代码生成

缺点

  • 学习曲线
  • 配置复杂

2.2 API Blueprint

问题:API 文档编写繁琐。

解决方案:使用 API Blueprint。

配置示例

markdown
# My API

## GET /users

Get all users

+ Response 200 (application/json)

    [
      {
        "id": 1,
        "name": "John",
        "email": "john@example.com"
      }
    ]

## POST /users

Create a user

+ Request (application/json)

    {
      "name": "John",
      "email": "john@example.com"
    }

+ Response 201 (application/json)

    {
      "id": 1,
      "name": "John",
      "email": "john@example.com"
    }

优点

  • 易于编写
  • 易于阅读
  • 支持代码生成

缺点

  • 功能有限
  • 社区较小

2.3 RAML

问题:API 文档不规范。

解决方案:使用 RAML。

配置示例

yaml
#%RAML 1.0
title: My API
version: v1
baseUri: https://api.example.com/{version}

/users:
  get:
    description: Get all users
    responses:
      200:
        body:
          application/json:
            type: array
            items:
              type: object
              properties:
                id:
                  type: integer
                name:
                  type: string
                email:
                  type: string
  post:
    description: Create a user
    body:
      application/json:
        type: object
        properties:
          name:
            type: string
          email:
            type: string
    responses:
      201:
        body:
          application/json:
            type: object
            properties:
              id:
                type: integer
              name:
                type: string
              email:
                type: string

优点

  • 标准化规范
  • 支持代码生成
  • 支持文档生成

缺点

  • 学习曲线
  • 配置复杂

三、GraphQL API 文档

3.1 GraphQL Schema

问题:GraphQL API 文档不清晰。

解决方案:使用 GraphQL Schema。

配置示例

graphql
# schema.graphql
type User {
  id: ID!
  name: String!
  email: String!
  posts: [Post!]!
}

type Post {
  id: ID!
  title: String!
  content: String!
  author: User!
}

type Query {
  users: [User!]!
  user(id: ID!): User
  posts: [Post!]!
  post(id: ID!): Post
}

type Mutation {
  createUser(name: String!, email: String!): User!
  createPost(title: String!, content: String!, authorId: ID!): Post!
}

优点

  • 类型安全
  • 自动文档
  • 灵活查询

缺点

  • 学习曲线
  • 性能优化

3.2 GraphQL Playground

问题:GraphQL API 测试困难。

解决方案:使用 GraphQL Playground。

配置示例

javascript
// server.js
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: true,
  introspection: true,
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

优点

  • 交互式测试
  • 自动文档
  • 查询历史

缺点

  • 仅限开发环境
  • 安全风险

四、WebSocket API 文档

4.1 WebSocket 协议

问题:WebSocket API 文档不清晰。

解决方案:使用 WebSocket 协议。

配置示例

javascript
// server.js
const WebSocket = require('ws');

const wss = new WebSocket.Server({ port: 8080 });

wss.on('connection', (ws) => {
  console.log('Client connected');
  
  ws.on('message', (message) => {
    console.log(`Received: ${message}`);
    ws.send(`Echo: ${message}`);
  });
  
  ws.on('close', () => {
    console.log('Client disconnected');
  });
});

优点

  • 实时通信
  • 低延迟
  • 双向通信

缺点

  • 连接管理
  • 错误处理

4.2 Socket.IO

问题:WebSocket API 使用困难。

解决方案:使用 Socket.IO。

配置示例

javascript
// server.js
const io = require('socket.io')(3000);

io.on('connection', (socket) => {
  console.log('Client connected');
  
  socket.on('message', (message) => {
    console.log(`Received: ${message}`);
    socket.emit('message', `Echo: ${message}`);
  });
  
  socket.on('disconnect', () => {
    console.log('Client disconnected');
  });
});

优点

  • 易于使用
  • 自动重连
  • 支持多种传输

缺点

  • 依赖库
  • 性能开销

五、gRPC API 文档

5.1 Protocol Buffers

问题:gRPC API 文档不清晰。

解决方案:使用 Protocol Buffers。

配置示例

protobuf
// user.proto
syntax = "proto3";

package user;

service UserService {
  rpc GetUsers (GetUsersRequest) returns (GetUsersResponse);
  rpc GetUser (GetUserRequest) returns (User);
  rpc CreateUser (CreateUserRequest) returns (User);
}

message GetUsersRequest {}

message GetUsersResponse {
  repeated User users = 1;
}

message GetUserRequest {
  int64 id = 1;
}

message CreateUserRequest {
  string name = 1;
  string email = 2;
}

message User {
  int64 id = 1;
  string name = 2;
  string email = 3;
}

优点

  • 高性能
  • 类型安全
  • 跨语言支持

缺点

  • 学习曲线
  • 调试困难

5.2 gRPC 服务定义

问题:gRPC 服务定义不清晰。

解决方案:使用 gRPC 服务定义。

配置示例

protobuf
// service.proto
syntax = "proto3";

package service;

service MyService {
  rpc MyMethod (MyRequest) returns (MyResponse);
}

message MyRequest {
  string input = 1;
}

message MyResponse {
  string output = 1;
}

优点

  • 标准化规范
  • 支持多种语言
  • 高性能

缺点

  • 学习曲线
  • 调试困难

六、文档工具

6.1 Swagger UI

问题:API 文档不直观。

解决方案:使用 Swagger UI。

配置示例

javascript
// server.js
const swaggerUi = require('swagger-ui-express');
const swaggerDocument = require('./openapi.json');

app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));

优点

  • 交互式文档
  • 自动更新
  • 易于使用

缺点

  • 仅限 REST API
  • 配置复杂

6.2 GraphQL Playground

问题:GraphQL API 测试困难。

解决方案:使用 GraphQL Playground。

配置示例

javascript
// server.js
const { ApolloServer } = require('apollo-server');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const server = new ApolloServer({
  typeDefs,
  resolvers,
  playground: true,
  introspection: true,
});

server.listen().then(({ url }) => {
  console.log(`🚀 Server ready at ${url}`);
});

优点

  • 交互式测试
  • 自动文档
  • 查询历史

缺点

  • 仅限开发环境
  • 安全风险

6.3 Postman

问题:API 测试困难。

解决方案:使用 Postman。

使用方法

  1. 创建集合

    • 创建新的集合
    • 添加请求
  2. 配置请求

    • 设置 URL
    • 设置方法
    • 设置 Headers
    • 设置 Body
  3. 发送请求

    • 发送请求
    • 查看响应
    • 保存结果

优点

  • 易于使用
  • 支持多种协议
  • 支持自动化测试

缺点

  • 需要安装
  • 需要注册

七、最佳实践

7.1 文档规范

问题:API 文档不规范。

解决方案:制定文档规范。

规范清单

规范说明重要性
命名规范使用一致的命名
格式规范使用一致的格式
示例规范提供清晰的示例
版本规范使用版本控制

7.2 文档维护

问题:API 文档过时。

解决方案:建立文档维护机制。

维护流程

7.3 文档测试

问题:API 文档不准确。

解决方案:进行文档测试。

测试方法

方法说明工具
手动测试手动验证文档Postman
自动测试自动验证文档CI/CD
用户测试用户验证文档反馈

八、核心洞察

核心洞察

API 文档是开发效率的保障

  • REST API:OpenAPI/Swagger、API Blueprint、RAML
  • GraphQL API:GraphQL Schema、GraphQL Playground
  • WebSocket API:WebSocket 协议、Socket.IO
  • gRPC API:Protocol Buffers、gRPC 服务定义

记住:好的 API 文档可以减少沟通成本,提高开发效率。


九、参考与延伸

[1] OpenAPI 规范(2026)— REST API 规范

[2] GraphQL 规范(2026)— GraphQL API 规范

[3] gRPC 文档(2026)— gRPC API 文档


十、下一步

完成本章后,进入:

OPC 超级个体实战指南