api-documentation

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

API Documentation Skill

API文档技能

Auto-generate comprehensive API documentation with examples, schemas, and interactive tools.
自动生成包含示例、模式和交互式工具的全面API文档。

Instructions

使用说明

You are an API documentation expert. When invoked:
  1. Generate Documentation:
    • Create API reference documentation
    • Extract info from code comments
    • Generate from OpenAPI/Swagger specs
    • Include usage examples
    • Document authentication methods
  2. Interactive Documentation:
    • Set up Swagger UI
    • Configure Redoc
    • Create interactive playgrounds
    • Add try-it-out features
    • Include code samples
  3. Documentation Types:
    • API reference guides
    • Getting started tutorials
    • Authentication guides
    • Error handling documentation
    • Rate limiting policies
  4. Multi-Format Export:
    • HTML documentation
    • Markdown files
    • PDF exports
    • Postman collections
    • SDK generation
你是一位API文档专家。当被调用时:
  1. 生成文档:
    • 创建API参考文档
    • 从代码注释中提取信息
    • 根据OpenAPI/Swagger规范生成文档
    • 包含使用示例
    • 记录认证方法
  2. 交互式文档:
    • 搭建Swagger UI
    • 配置Redoc
    • 创建交互式演练场
    • 添加“立即尝试”功能
    • 包含代码示例
  3. 文档类型:
    • API参考指南
    • 快速入门教程
    • 认证指南
    • 错误处理文档
    • 速率限制策略
  4. 多格式导出:
    • HTML文档
    • Markdown文件
    • PDF导出
    • Postman集合
    • SDK生成

Usage Examples

使用示例

@api-documentation
@api-documentation --from-openapi
@api-documentation --interactive
@api-documentation --export-postman
@api-documentation --generate-sdk
@api-documentation
@api-documentation --from-openapi
@api-documentation --interactive
@api-documentation --export-postman
@api-documentation --generate-sdk

Documentation Tools

文档工具

Swagger UI

Swagger UI

Setup with Express

基于Express搭建

javascript
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

const app = express();

// Load OpenAPI spec
const swaggerDocument = YAML.load('./openapi.yaml');

// Serve Swagger UI
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: 'My API Documentation',
  customfavIcon: '/favicon.ico'
}));

// Serve OpenAPI spec as JSON
app.get('/openapi.json', (req, res) => {
  res.json(swaggerDocument);
});

app.listen(3000, () => {
  console.log('API docs available at http://localhost:3000/api-docs');
});
javascript
const express = require('express');
const swaggerUi = require('swagger-ui-express');
const YAML = require('yamljs');

const app = express();

// 加载OpenAPI规范
const swaggerDocument = YAML.load('./openapi.yaml');

// 提供Swagger UI服务
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, {
  customCss: '.swagger-ui .topbar { display: none }',
  customSiteTitle: 'My API Documentation',
  customfavIcon: '/favicon.ico'
}));

// 以JSON格式提供OpenAPI规范
app.get('/openapi.json', (req, res) => {
  res.json(swaggerDocument);
});

app.listen(3000, () => {
  console.log('API docs available at http://localhost:3000/api-docs');
});

Custom Swagger Options

自定义Swagger选项

javascript
const options = {
  explorer: true,
  swaggerOptions: {
    persistAuthorization: true,
    displayRequestDuration: true,
    filter: true,
    syntaxHighlight: {
      activate: true,
      theme: 'monokai'
    }
  },
  customCss: `
    .swagger-ui .topbar { background-color: #2c3e50; }
    .swagger-ui .info .title { color: #2c3e50; }
  `,
  customSiteTitle: 'My API - Documentation',
  customfavIcon: '/assets/favicon.ico'
};

app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument, options));
javascript
const options = {
  explorer: true,
  swaggerOptions: {
    persistAuthorization: true,
    displayRequestDuration: true,
    filter: true,
    syntaxHighlight: {
      activate: true,
      theme: 'monokai'
    }
  },
  customCss: `
    .swagger-ui .topbar { background-color: #2c3e50; }
    .swagger-ui .info .title { color: #2c3e50; }
  `,
  customSiteTitle: 'My API - Documentation',
  customfavIcon: '/assets/favicon.ico'
};

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

Redoc

Redoc

Setup

搭建

javascript
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// Serve OpenAPI spec
app.get('/openapi.yaml', (req, res) => {
  res.sendFile(__dirname + '/openapi.yaml');
});

// Serve Redoc
app.get('/docs', (req, res) => {
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>API Documentation</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
        <style>
          body { margin: 0; padding: 0; }
        </style>
      </head>
      <body>
        <redoc spec-url='/openapi.yaml'></redoc>
        <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
      </body>
    </html>
  `);
});

app.listen(3000);
javascript
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');

const app = express();

// 提供OpenAPI规范
app.get('/openapi.yaml', (req, res) => {
  res.sendFile(__dirname + '/openapi.yaml');
});

// 提供Redoc服务
app.get('/docs', (req, res) => {
  res.send(`
    <!DOCTYPE html>
    <html>
      <head>
        <title>API Documentation</title>
        <meta charset="utf-8"/>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link href="https://fonts.googleapis.com/css?family=Montserrat:300,400,700|Roboto:300,400,700" rel="stylesheet">
        <style>
          body { margin: 0; padding: 0; }
        </style>
      </head>
      <body>
        <redoc spec-url='/openapi.yaml'></redoc>
        <script src="https://cdn.redoc.ly/redoc/latest/bundles/redoc.standalone.js"></script>
      </body>
    </html>
  `);
});

app.listen(3000);

Redoc CLI

Redoc CLI

bash
undefined
bash
undefined

Install

安装

npm install -g redoc-cli
npm install -g redoc-cli

Generate static HTML

生成静态HTML

redoc-cli bundle openapi.yaml -o docs/index.html
redoc-cli bundle openapi.yaml -o docs/index.html

Serve with live reload

带热重载启动服务

redoc-cli serve openapi.yaml --watch
redoc-cli serve openapi.yaml --watch

Custom options

自定义选项

redoc-cli bundle openapi.yaml
--output docs/index.html
--title "My API Documentation"
--options.theme.colors.primary.main="#2c3e50"
undefined
redoc-cli bundle openapi.yaml
--output docs/index.html
--title "My API Documentation"
--options.theme.colors.primary.main="#2c3e50"
undefined

Stoplight Elements

Stoplight Elements

html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>API Documentation</title>
    <script src="https://unpkg.com/@stoplight/elements/web-components.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/@stoplight/elements/styles.min.css" />
  </head>
  <body>
    <elements-api
      apiDescriptionUrl="/openapi.yaml"
      router="hash"
      layout="sidebar"
    />
  </body>
</html>
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
    <title>API Documentation</title>
    <script src="https://unpkg.com/@stoplight/elements/web-components.min.js"></script>
    <link rel="stylesheet" href="https://unpkg.com/@stoplight/elements/styles.min.css" />
  </head>
  <body>
    <elements-api
      apiDescriptionUrl="/openapi.yaml"
      router="hash"
      layout="sidebar"
    />
  </body>
</html>

Documentation from Code

从代码生成文档

JSDoc to OpenAPI

JSDoc转OpenAPI

javascript
/**
 * @openapi
 * /api/users:
 *   get:
 *     summary: Get all users
 *     description: Retrieve a paginated list of all users
 *     tags:
 *       - Users
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           minimum: 1
 *           default: 1
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           minimum: 1
 *           maximum: 100
 *           default: 10
 *         description: Number of items per page
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 data:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/User'
 *                 meta:
 *                   $ref: '#/components/schemas/PaginationMeta'
 *       401:
 *         $ref: '#/components/responses/UnauthorizedError'
 *     security:
 *       - bearerAuth: []
 */
router.get('/users', async (req, res) => {
  // Implementation
});

/**
 * @openapi
 * components:
 *   schemas:
 *     User:
 *       type: object
 *       required:
 *         - id
 *         - name
 *         - email
 *       properties:
 *         id:
 *           type: string
 *           description: User ID
 *           example: "123"
 *         name:
 *           type: string
 *           description: User's full name
 *           example: "John Doe"
 *         email:
 *           type: string
 *           format: email
 *           description: User's email address
 *           example: "john@example.com"
 */
javascript
/**
 * @openapi
 * /api/users:
 *   get:
 *     summary: Get all users
 *     description: Retrieve a paginated list of all users
 *     tags:
 *       - Users
 *     parameters:
 *       - in: query
 *         name: page
 *         schema:
 *           type: integer
 *           minimum: 1
 *           default: 1
 *         description: Page number
 *       - in: query
 *         name: limit
 *         schema:
 *           type: integer
 *           minimum: 1
 *           maximum: 100
 *           default: 10
 *         description: Number of items per page
 *     responses:
 *       200:
 *         description: Successful response
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 data:
 *                   type: array
 *                   items:
 *                     $ref: '#/components/schemas/User'
 *                 meta:
 *                   $ref: '#/components/schemas/PaginationMeta'
 *       401:
 *         $ref: '#/components/responses/UnauthorizedError'
 *     security:
 *       - bearerAuth: []
 */
router.get('/users', async (req, res) => {
  // 实现代码
});

/**
 * @openapi
 * components:
 *   schemas:
 *     User:
 *       type: object
 *       required:
 *         - id
 *         - name
 *         - email
 *       properties:
 *         id:
 *           type: string
 *           description: User ID
 *           example: "123"
 *         name:
 *           type: string
 *           description: User's full name
 *           example: "John Doe"
 *         email:
 *           type: string
 *           format: email
 *           description: User's email address
 *           example: "john@example.com"
 */

TypeDoc (TypeScript)

TypeDoc(TypeScript)

typescript
/**
 * User management API
 * @module UserAPI
 */

/**
 * Represents a user in the system
 * @interface User
 */
interface User {
  /** Unique user identifier */
  id: string;
  /** User's full name */
  name: string;
  /** User's email address */
  email: string;
  /** User role */
  role: 'user' | 'admin';
}

/**
 * Get all users
 * @route GET /api/users
 * @param {number} page - Page number (default: 1)
 * @param {number} limit - Items per page (default: 10)
 * @returns {Promise<User[]>} List of users
 * @throws {UnauthorizedError} If not authenticated
 */
export async function getUsers(
  page: number = 1,
  limit: number = 10
): Promise<User[]> {
  // Implementation
}

/**
 * Create a new user
 * @route POST /api/users
 * @param {CreateUserRequest} data - User data
 * @returns {Promise<User>} Created user
 * @throws {ValidationError} If data is invalid
 * @throws {ConflictError} If email already exists
 */
export async function createUser(data: CreateUserRequest): Promise<User> {
  // Implementation
}
typescript
/**
 * User management API
 * @module UserAPI
 */

/**
 * Represents a user in the system
 * @interface User
 */
interface User {
  /** Unique user identifier */
  id: string;
  /** User's full name */
  name: string;
  /** User's email address */
  email: string;
  /** User role */
  role: 'user' | 'admin';
}

/**
 * Get all users
 * @route GET /api/users
 * @param {number} page - Page number (default: 1)
 * @param {number} limit - Items per page (default: 10)
 * @returns {Promise<User[]>} List of users
 * @throws {UnauthorizedError} If not authenticated
 */
export async function getUsers(
  page: number = 1,
  limit: number = 10
): Promise<User[]> {
  // 实现代码
}

/**
 * Create a new user
 * @route POST /api/users
 * @param {CreateUserRequest} data - User data
 * @returns {Promise<User>} Created user
 * @throws {ValidationError} If data is invalid
 * @throws {ConflictError} If email already exists
 */
export async function createUser(data: CreateUserRequest): Promise<User> {
  // 实现代码
}

Python Docstrings (FastAPI)

Python文档字符串(FastAPI)

python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional

app = FastAPI(
    title="User Management API",
    description="API for managing users and authentication",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

class User(BaseModel):
    """
    User model representing a user account.

    Attributes:
        id: Unique user identifier
        name: User's full name
        email: User's email address
        role: User role (user or admin)
    """
    id: str
    name: str
    email: str
    role: str = "user"

@app.get("/api/users", response_model=List[User], tags=["Users"])
async def get_users(
    page: int = 1,
    limit: int = 10
) -> List[User]:
    """
    Get all users with pagination.

    Args:
        page: Page number (default: 1)
        limit: Number of items per page (default: 10)

    Returns:
        List of users

    Raises:
        HTTPException: If unauthorized (401)
    """
    # Implementation
    return []

@app.post("/api/users", response_model=User, status_code=201, tags=["Users"])
async def create_user(user: User) -> User:
    """
    Create a new user account.

    Args:
        user: User data including name, email, and optional role

    Returns:
        Created user object

    Raises:
        HTTPException: If validation fails (400)
        HTTPException: If email already exists (409)
    """
    # Implementation
    return user
python
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional

app = FastAPI(
    title="User Management API",
    description="API for managing users and authentication",
    version="1.0.0",
    docs_url="/docs",
    redoc_url="/redoc"
)

class User(BaseModel):
    """
    User model representing a user account.

    Attributes:
        id: Unique user identifier
        name: User's full name
        email: User's email address
        role: User role (user or admin)
    """
    id: str
    name: str
    email: str
    role: str = "user"

@app.get("/api/users", response_model=List[User], tags=["Users"])
async def get_users(
    page: int = 1,
    limit: int = 10
) -> List[User]:
    """
    Get all users with pagination.

    Args:
        page: Page number (default: 1)
        limit: Number of items per page (default: 10)

    Returns:
        List of users

    Raises:
        HTTPException: If unauthorized (401)
    """
    # 实现代码
    return []

@app.post("/api/users", response_model=User, status_code=201, tags=["Users"])
async def create_user(user: User) -> User:
    """
    Create a new user account.

    Args:
        user: User data including name, email, and optional role

    Returns:
        Created user object

    Raises:
        HTTPException: If validation fails (400)
        HTTPException: If email already exists (409)
    """
    # 实现代码
    return user

Documentation Templates

文档模板

Markdown API Reference

Markdown API参考

markdown
undefined
markdown
undefined

API Reference

API参考

Base URL:
https://api.example.com/v1
基础URL:
https://api.example.com/v1

Authentication

认证

All API requests require authentication using a Bearer token:
bash
Authorization: Bearer YOUR_ACCESS_TOKEN
Get your access token by calling the
/auth/login
endpoint.
所有API请求都需要使用Bearer令牌进行认证:
bash
Authorization: Bearer YOUR_ACCESS_TOKEN
调用
/auth/login
端点获取访问令牌。

Endpoints

端点

Users

用户

Get All Users

获取所有用户

http
GET /api/users
Retrieve a paginated list of users.
Parameters
NameTypeInRequiredDescription
pageintegerqueryNoPage number (default: 1)
limitintegerqueryNoItems per page (max: 100)
Response
json
{
  "data": [
    {
      "id": "123",
      "name": "John Doe",
      "email": "john@example.com",
      "role": "user"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 42,
    "totalPages": 5
  }
}
Status Codes
  • 200 OK
    - Success
  • 401 Unauthorized
    - Missing or invalid authentication
  • 500 Internal Server Error
    - Server error
Example Request
bash
curl -X GET "https://api.example.com/v1/api/users?page=1&limit=10" \
  -H "Authorization: Bearer YOUR_TOKEN"
javascript
const response = await fetch('https://api.example.com/v1/api/users?page=1&limit=10', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});
const data = await response.json();
python
import requests

response = requests.get(
    'https://api.example.com/v1/api/users',
    headers={'Authorization': 'Bearer YOUR_TOKEN'},
    params={'page': 1, 'limit': 10}
)
data = response.json()
http
GET /api/users
获取分页的用户列表。
参数
名称类型位置是否必填描述
pageintegerquery页码(默认值:1)
limitintegerquery每页条目数(最大值:100)
响应
json
{
  "data": [
    {
      "id": "123",
      "name": "John Doe",
      "email": "john@example.com",
      "role": "user"
    }
  ],
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 42,
    "totalPages": 5
  }
}
状态码
  • 200 OK
    - 请求成功
  • 401 Unauthorized
    - 认证信息缺失或无效
  • 500 Internal Server Error
    - 服务器错误
请求示例
bash
curl -X GET "https://api.example.com/v1/api/users?page=1&limit=10" \
  -H "Authorization: Bearer YOUR_TOKEN"
javascript
const response = await fetch('https://api.example.com/v1/api/users?page=1&limit=10', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});
const data = await response.json();
python
import requests

response = requests.get(
    'https://api.example.com/v1/api/users',
    headers={'Authorization': 'Bearer YOUR_TOKEN'},
    params={'page': 1, 'limit': 10}
)
data = response.json()

Create User

创建用户

http
POST /api/users
Create a new user account.
Request Body
json
{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePass123!",
  "role": "user"
}
Response
json
{
  "id": "123",
  "name": "John Doe",
  "email": "john@example.com",
  "role": "user",
  "createdAt": "2024-01-15T10:30:00Z"
}
Status Codes
  • 201 Created
    - User created successfully
  • 400 Bad Request
    - Invalid request data
  • 409 Conflict
    - Email already exists
  • 401 Unauthorized
    - Authentication required
http
POST /api/users
创建新用户账户。
请求体
json
{
  "name": "John Doe",
  "email": "john@example.com",
  "password": "SecurePass123!",
  "role": "user"
}
响应
json
{
  "id": "123",
  "name": "John Doe",
  "email": "john@example.com",
  "role": "user",
  "createdAt": "2024-01-15T10:30:00Z"
}
状态码
  • 201 Created
    - 用户创建成功
  • 400 Bad Request
    - 请求数据无效
  • 409 Conflict
    - 邮箱已存在
  • 401 Unauthorized
    - 需要认证

Error Handling

错误处理

All errors follow a consistent format:
json
{
  "code": "ERROR_CODE",
  "message": "Human-readable error message",
  "details": {
    "field": "Additional error details"
  }
}
所有错误遵循统一格式:
json
{
  "code": "ERROR_CODE",
  "message": "易读的错误信息",
  "details": {
    "field": "额外错误详情"
  }
}

Common Error Codes

常见错误码

CodeHTTP StatusDescription
UNAUTHORIZED401Authentication required
FORBIDDEN403Insufficient permissions
NOT_FOUND404Resource not found
VALIDATION_ERROR400Invalid input data
RATE_LIMIT_EXCEEDED429Too many requests
代码HTTP状态码描述
UNAUTHORIZED401需要认证
FORBIDDEN403权限不足
NOT_FOUND404资源不存在
VALIDATION_ERROR400输入数据无效
RATE_LIMIT_EXCEEDED429请求次数过多

Rate Limiting

速率限制

API requests are limited to:
  • 100 requests per minute for authenticated users
  • 20 requests per minute for unauthenticated requests
Rate limit headers are included in all responses:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1610000000
API请求限制:
  • 已认证用户:每分钟100次请求
  • 未认证用户:每分钟20次请求
所有响应均包含速率限制头:
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1610000000

Pagination

分页

All list endpoints support pagination with these parameters:
  • page
    - Page number (default: 1)
  • limit
    - Items per page (default: 10, max: 100)
Responses include pagination metadata:
json
{
  "data": [...],
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 100,
    "totalPages": 10
  }
}
所有列表端点支持以下分页参数:
  • page
    - 页码(默认值:1)
  • limit
    - 每页条目数(默认值:10,最大值:100)
响应包含分页元数据:
json
{
  "data": [...],
  "meta": {
    "page": 1,
    "limit": 10,
    "total": 100,
    "totalPages": 10
  }
}

Versioning

版本控制

The API uses URL versioning:
  • Current version:
    v1
  • Base URL:
    https://api.example.com/v1
Breaking changes will be introduced in new versions (v2, v3, etc.)
undefined
API使用URL版本控制:
  • 当前版本:
    v1
  • 基础URL:
    https://api.example.com/v1
重大变更将在新版本(v2、v3等)中引入
undefined

Getting Started Guide

快速入门指南

markdown
undefined
markdown
undefined

Getting Started

快速入门

This guide will help you make your first API request.
本指南将帮助你发出第一个API请求。

1. Get Your API Key

1. 获取API密钥

Sign up at https://example.com/signup to get your API key.
访问https://example.com/signup注册以获取API密钥。

2. Make Your First Request

2. 发出第一个请求

Using curl

使用curl

bash
curl -X GET https://api.example.com/v1/api/users \
  -H "Authorization: Bearer YOUR_API_KEY"
bash
curl -X GET https://api.example.com/v1/api/users \
  -H "Authorization: Bearer YOUR_API_KEY"

Using JavaScript

使用JavaScript

javascript
const response = await fetch('https://api.example.com/v1/api/users', {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY'
  }
});

const users = await response.json();
console.log(users);
javascript
const response = await fetch('https://api.example.com/v1/api/users', {
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY'
  }
});

const users = await response.json();
console.log(users);

Using Python

使用Python

python
import requests

response = requests.get(
    'https://api.example.com/v1/api/users',
    headers={'Authorization': 'Bearer YOUR_API_KEY'}
)

users = response.json()
print(users)
python
import requests

response = requests.get(
    'https://api.example.com/v1/api/users',
    headers={'Authorization': 'Bearer YOUR_API_KEY'}
)

users = response.json()
print(users)

3. Create a Resource

3. 创建资源

bash
curl -X POST https://api.example.com/v1/api/users \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com"
  }'
bash
curl -X POST https://api.example.com/v1/api/users \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "John Doe",
    "email": "john@example.com"
  }'

4. Handle Errors

4. 处理错误

Always check the response status:
javascript
try {
  const response = await fetch('https://api.example.com/v1/api/users', {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  if (!response.ok) {
    const error = await response.json();
    console.error('Error:', error.message);
    return;
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error('Network error:', error);
}
始终检查响应状态:
javascript
try {
  const response = await fetch('https://api.example.com/v1/api/users', {
    headers: { 'Authorization': 'Bearer YOUR_API_KEY' }
  });

  if (!response.ok) {
    const error = await response.json();
    console.error('Error:', error.message);
    return;
  }

  const data = await response.json();
  console.log(data);
} catch (error) {
  console.error('Network error:', error);
}

Next Steps

下一步

undefined
undefined

Documentation Generation Tools

文档生成工具

Docusaurus (Facebook)

Docusaurus(Facebook)

bash
undefined
bash
undefined

Create new site

创建新站点

npx create-docusaurus@latest my-docs classic
npx create-docusaurus@latest my-docs classic

Install OpenAPI plugin

安装OpenAPI插件

npm install docusaurus-plugin-openapi-docs
npm install docusaurus-plugin-openapi-docs

Configure

配置

docusaurus.config.js

docusaurus.config.js

module.exports = { plugins: [ [ 'docusaurus-plugin-openapi-docs', { id: 'api', docsPluginId: 'classic', config: { api: { specPath: 'openapi.yaml', outputDir: 'docs/api', sidebarOptions: { groupPathsBy: 'tag' } } } } ] ] };
module.exports = { plugins: [ [ 'docusaurus-plugin-openapi-docs', { id: 'api', docsPluginId: 'classic', config: { api: { specPath: 'openapi.yaml', outputDir: 'docs/api', sidebarOptions: { groupPathsBy: 'tag' } } } } ] ] };

Generate docs

生成文档

npm run docusaurus gen-api-docs all
npm run docusaurus gen-api-docs all

Serve

启动服务

npm run start
undefined
npm run start
undefined

Slate (Beautiful API Docs)

Slate(美观的API文档)

bash
undefined
bash
undefined

Clone template

克隆模板

git clone https://github.com/slatedocs/slate.git my-api-docs cd my-api-docs
git clone https://github.com/slatedocs/slate.git my-api-docs cd my-api-docs

Install dependencies

安装依赖

bundle install
bundle install

Edit source/index.html.md

编辑source/index.html.md

Run server

启动服务器

bundle exec middleman server
bundle exec middleman server

Build static site

构建静态站点

bundle exec middleman build
undefined
bundle exec middleman build
undefined

ReadMe.io

ReadMe.io

bash
undefined
bash
undefined

Install CLI

安装CLI

npm install -g rdme
npm install -g rdme

Upload OpenAPI spec

上传OpenAPI规范

rdme openapi openapi.yaml --key YOUR_README_API_KEY
rdme openapi openapi.yaml --key YOUR_README_API_KEY

Sync with GitHub

与GitHub同步

rdme openapi openapi.yaml --github --key YOUR_README_API_KEY
undefined
rdme openapi openapi.yaml --github --key YOUR_README_API_KEY
undefined

MkDocs (Python)

MkDocs(Python)

bash
undefined
bash
undefined

Install

安装

pip install mkdocs mkdocs-material
pip install mkdocs mkdocs-material

Create new project

创建新项目

mkdocs new my-api-docs cd my-api-docs
mkdocs new my-api-docs cd my-api-docs

Configure mkdocs.yml

配置mkdocs.yml

site_name: My API Documentation theme: name: material features: - navigation.tabs - navigation.sections - toc.integrate
nav:
  • Home: index.md
  • Getting Started: getting-started.md
  • API Reference: api-reference.md
  • Examples: examples.md
site_name: My API Documentation theme: name: material features: - navigation.tabs - navigation.sections - toc.integrate
nav:
  • Home: index.md
  • Getting Started: getting-started.md
  • API Reference: api-reference.md
  • Examples: examples.md

Serve locally

本地启动服务

mkdocs serve
mkdocs serve

Build

构建站点

mkdocs build
undefined
mkdocs build
undefined

Code Examples Generator

代码示例生成器

Automatic Code Generation

自动代码生成

javascript
// From OpenAPI spec
const CodeGen = require('openapi-client-axios-typegen');

async function generateSDK() {
  const api = await CodeGen.generateClient('openapi.yaml');

  // Generated TypeScript client
  const users = await api.getUsers({ page: 1, limit: 10 });
  const newUser = await api.createUser({
    name: 'John Doe',
    email: 'john@example.com'
  });
}
javascript
// 从OpenAPI规范生成
const CodeGen = require('openapi-client-axios-typegen');

async function generateSDK() {
  const api = await CodeGen.generateClient('openapi.yaml');

  // 生成的TypeScript客户端
  const users = await api.getUsers({ page: 1, limit: 10 });
  const newUser = await api.createUser({
    name: 'John Doe',
    email: 'john@example.com'
  });
}

Multi-Language Examples

多语言示例

javascript
// examples-generator.js
const examples = {
  getUsersCurl: `curl -X GET "https://api.example.com/v1/api/users?page=1&limit=10" \\
  -H "Authorization: Bearer YOUR_TOKEN"`,

  getUsersJavaScript: `const response = await fetch('https://api.example.com/v1/api/users?page=1&limit=10', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});
const data = await response.json();`,

  getUsersPython: `import requests

response = requests.get(
    'https://api.example.com/v1/api/users',
    headers={'Authorization': 'Bearer YOUR_TOKEN'},
    params={'page': 1, 'limit': 10}
)
data = response.json()`,

  getUsersGo: `client := &http.Client{}
req, _ := http.NewRequest("GET", "https://api.example.com/v1/api/users?page=1&limit=10", nil)
req.Header.Add("Authorization", "Bearer YOUR_TOKEN")
resp, _ := client.Do(req)`,

  getUsersRuby: `require 'net/http'

uri = URI('https://api.example.com/v1/api/users?page=1&limit=10')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer YOUR_TOKEN'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }`
};
javascript
// examples-generator.js
const examples = {
  getUsersCurl: `curl -X GET "https://api.example.com/v1/api/users?page=1&limit=10" \\
  -H "Authorization: Bearer YOUR_TOKEN"`,

  getUsersJavaScript: `const response = await fetch('https://api.example.com/v1/api/users?page=1&limit=10', {
  headers: {
    'Authorization': 'Bearer YOUR_TOKEN'
  }
});
const data = await response.json();`,

  getUsersPython: `import requests

response = requests.get(
    'https://api.example.com/v1/api/users',
    headers={'Authorization': 'Bearer YOUR_TOKEN'},
    params={'page': 1, 'limit': 10}
)
data = response.json()`,

  getUsersGo: `client := &http.Client{}
req, _ := http.NewRequest("GET", "https://api.example.com/v1/api/users?page=1&limit=10", nil)
req.Header.Add("Authorization", "Bearer YOUR_TOKEN")
resp, _ := client.Do(req)`,

  getUsersRuby: `require 'net/http'

uri = URI('https://api.example.com/v1/api/users?page=1&limit=10')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer YOUR_TOKEN'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }`
};

Best Practices

最佳实践

Documentation Content

文档内容

  • Write clear, concise descriptions
  • Include code examples in multiple languages
  • Provide real-world use cases
  • Document all error codes
  • Include rate limits and quotas
  • Show authentication examples
  • Explain pagination
  • Document versioning strategy
  • 编写清晰、简洁的描述
  • 包含多种语言的代码示例
  • 提供真实场景用例
  • 记录所有错误码
  • 包含速率限制和配额说明
  • 展示认证示例
  • 解释分页机制
  • 记录版本控制策略

Interactive Features

交互式功能

  • Add "Try it out" functionality
  • Include request/response examples
  • Show syntax highlighting
  • Provide copy-to-clipboard buttons
  • Add search functionality
  • Include navigation menu
  • 添加“立即尝试”功能
  • 包含请求/响应示例
  • 显示语法高亮
  • 提供一键复制按钮
  • 添加搜索功能
  • 包含导航菜单

Maintenance

维护

  • Keep docs synchronized with code
  • Automate documentation generation
  • Version documentation with API
  • Review and update regularly
  • Test all code examples
  • Collect user feedback
  • 保持文档与代码同步
  • 自动化文档生成
  • 文档与API版本同步
  • 定期审阅和更新
  • 测试所有代码示例
  • 收集用户反馈

SEO and Discovery

SEO与可发现性

  • Use descriptive titles
  • Add meta descriptions
  • Create sitemap
  • Use proper heading structure
  • Include keywords
  • Make docs publicly accessible
  • 使用描述性标题
  • 添加元描述
  • 创建站点地图
  • 使用合理的标题层级
  • 包含关键词
  • 确保文档可公开访问

Notes

注意事项

  • Auto-generate docs from OpenAPI specs when possible
  • Include interactive API explorers
  • Provide examples in multiple programming languages
  • Keep documentation up-to-date with code changes
  • Use version control for documentation
  • Make documentation searchable
  • Include getting started guides
  • Document authentication thoroughly
  • Show error handling examples
  • Test all code examples before publishing
  • Collect and incorporate user feedback
  • Use consistent formatting and style
  • 尽可能从OpenAPI规范自动生成文档
  • 包含交互式API浏览器
  • 提供多种编程语言的示例
  • 保持文档与代码变更同步
  • 使用版本控制管理文档
  • 让文档支持搜索
  • 包含快速入门指南
  • 详细记录认证流程
  • 展示错误处理示例
  • 发布前测试所有代码示例
  • 收集并整合用户反馈
  • 使用一致的格式和风格