> ## Documentation Index
> Fetch the complete documentation index at: https://docs.dodopayments.com/llms.txt
> Use this file to discover all available pages before exploring further.

# API 网关蓝图

> 跟踪 API 调用和网关级使用情况以进行计费。非常适合高流量请求跟踪的 API 即服务平台。

## 用例

探索 API 网关蓝图支持的常见场景：

<CardGroup cols={2}>
  <Card title="API-as-a-Service" icon="server">
    跟踪每位客户在 API 平台上的使用情况，并根据调用次数收费。
  </Card>

  <Card title="Rate Limiting" icon="gauge">
    监控 API 使用模式并实施基于使用的速率限制。
  </Card>

  <Card title="Performance Monitoring" icon="chart-line">
    与计费数据一起跟踪响应时间和错误率。
  </Card>

  <Card title="Multi-Tenant SaaS" icon="users">
    根据客户在不同端点上的 API 消费向其计费。
  </Card>
</CardGroup>

<Info>
  非常适合跟踪 API 端点使用情况、速率限制以及实现基于使用的 API 计费。
</Info>

## 快速开始

在网关级别跟踪 API 调用，适用于高流量场景的自动批处理：

<Steps>
  <Step title="Install the SDK">
    ```bash theme={null}
    npm install @dodopayments/ingestion-blueprints
    ```
  </Step>

  <Step title="Get Your API Keys">
    * **Dodo Payments API Key**：从 [Dodo Payments Dashboard](https://app.dodopayments.com/developer/api-keys) 获取
  </Step>

  <Step title="Create a Meter">
    在 [Dodo Payments Dashboard](https://app.dodopayments.com/) 中创建一个计量器：

    * **Event Name**：`api_call`（或您喜欢的名称）
    * **Aggregation Type**：`count`（用于跟踪调用次数）
    * 如果要跟踪响应时间、状态码等元数据，请配置额外属性。
  </Step>

  <Step title="Track API Calls">
    <CodeGroup>
      ```javascript Single API Call theme={null}
      import { Ingestion, trackAPICall } from '@dodopayments/ingestion-blueprints';

      const ingestion = new Ingestion({
        apiKey: process.env.DODO_PAYMENTS_API_KEY,
        environment: 'test_mode',
        eventName: 'api_call'
      });

      // Track a single API call
      await trackAPICall(ingestion, {
        customerId: 'customer_123',
        metadata: {
          endpoint: '/api/v1/users',
          method: 'GET',
          status_code: 200,
          response_time_ms: 45
        }
      });
      ```

      ```javascript High-Volume with Batching theme={null}
      import { Ingestion, createBatch } from '@dodopayments/ingestion-blueprints';

      const ingestion = new Ingestion({
        apiKey: process.env.DODO_PAYMENTS_API_KEY,
        environment: 'live_mode',
        eventName: 'api_call'
      });

      // Create batch for high-volume tracking
      const batch = createBatch(ingestion, {
        maxSize: 100,      // Flush after 100 events
        flushInterval: 5000 // Or flush every 5 seconds
      });

      // Add API calls to batch
      batch.add({
        customerId: 'customer_123',
        metadata: {
          endpoint: '/api/v1/products',
          method: 'GET',
          status_code: 200
        }
      });

      // Clean up when done
      await batch.cleanup();
      ```

      ```javascript Express.js Middleware theme={null}
      import express from 'express';
      import { Ingestion, createBatch } from '@dodopayments/ingestion-blueprints';

      const app = express();

      const ingestion = new Ingestion({
        apiKey: process.env.DODO_PAYMENTS_API_KEY,
        environment: 'live_mode',
        eventName: 'api_call'
      });

      const batch = createBatch(ingestion, {
        maxSize: 50,
        flushInterval: 10000
      });

      // Middleware to track all API calls
      app.use((req, res, next) => {
        const startTime = Date.now();
        
        res.on('finish', () => {
          const responseTime = Date.now() - startTime;
          
          batch.add({
            customerId: req.user?.id || 'anonymous',
            metadata: {
              endpoint: req.path,
              method: req.method,
              status_code: res.statusCode,
              response_time_ms: responseTime
            }
          });
        });
        
        next();
      });

      // Cleanup on shutdown
      process.on('SIGTERM', async () => {
        await batch.cleanup();
        process.exit(0);
      });
      ```
    </CodeGroup>
  </Step>
</Steps>

## 配置

### 数据摄取配置

<ParamField path="apiKey" type="string" required>
  来自仪表板的 Dodo Payments API 密钥。
</ParamField>

<ParamField path="environment" type="string" required>
  环境模式：`test_mode` 或 `live_mode`。
</ParamField>

<ParamField path="eventName" type="string" required>
  与您的计量器配置匹配的事件名称。
</ParamField>

### 跟踪 API 调用选项

<ParamField path="customerId" type="string" required>
  用于计费归因的客户 ID。
</ParamField>

<ParamField path="metadata" type="object">
  有关 API 调用的可选元数据，如端点、方法、状态码、响应时间等。
</ParamField>

### 批处理配置

<ParamField path="maxSize" type="number">
  自动刷新前的最大事件数。默认值：`100`。
</ParamField>

<ParamField path="flushInterval" type="number">
  自动刷新间隔（毫秒）。默认值：`5000`（5 秒）。
</ParamField>

## 最佳实践

<Tip>
  **高流量时使用批处理**：对于每秒处理超过 10 个请求的应用，请使用 `createBatch()` 以减少开销并提升性能。
</Tip>

<Warning>
  **始终清理批处理**：在应用关闭时调用 `batch.cleanup()` 以刷新挂起事件并防止数据丢失。
</Warning>
