> ## 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 Gateway Blueprint

> Track API calls and gateway-level usage for billing. Perfect for API-as-a-service platforms with high-volume request tracking.

## Use Cases

Explore common scenarios supported by the API Gateway Blueprint:

<CardGroup cols={2}>
  <Card title="API-as-a-Service" icon="server">
    Track usage per customer for API platforms and charge based on number of calls.
  </Card>

  <Card title="Rate Limiting" icon="gauge">
    Monitor API usage patterns and implement usage-based rate limiting.
  </Card>

  <Card title="Performance Monitoring" icon="chart-line">
    Track response times and error rates alongside billing data.
  </Card>

  <Card title="Multi-Tenant SaaS" icon="users">
    Bill customers based on their API consumption across different endpoints.
  </Card>
</CardGroup>

<Info>
  Ideal for tracking API endpoint usage, rate limiting, and implementing usage-based API billing.
</Info>

## Quick Start

Track API calls at the gateway level with automatic batching for high-volume scenarios:

<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**: Get it from [Dodo Payments Dashboard](https://app.dodopayments.com/developer/api-keys)
  </Step>

  <Step title="Create a Meter">
    Create a meter in your [Dodo Payments Dashboard](https://app.dodopayments.com/):

    * **Event Name**: `api_call` (or your preferred name)
    * **Aggregation Type**: `count` for tracking number of calls
    * Configure additional properties if tracking metadata like response times, status codes, etc.
  </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>

## Configuration

### Ingestion Configuration

<ParamField path="apiKey" type="string" required>
  Your Dodo Payments API key from the dashboard.
</ParamField>

<ParamField path="environment" type="string" required>
  Environment mode: `test_mode` or `live_mode`.
</ParamField>

<ParamField path="eventName" type="string" required>
  Event name that matches your meter configuration.
</ParamField>

### Track API Call Options

<ParamField path="customerId" type="string" required>
  The customer ID for billing attribution.
</ParamField>

<ParamField path="metadata" type="object">
  Optional metadata about the API call like endpoint, method, status code, response time, etc.
</ParamField>

### Batch Configuration

<ParamField path="maxSize" type="number">
  Maximum number of events before auto-flush. Default: `100`.
</ParamField>

<ParamField path="flushInterval" type="number">
  Auto-flush interval in milliseconds. Default: `5000` (5 seconds).
</ParamField>

## Best Practices

<Tip>
  **Use Batching for High Volume**: For applications handling more than 10 requests per second, use `createBatch()` to reduce overhead and improve performance.
</Tip>

<Warning>
  **Always Clean Up Batches**: Call `batch.cleanup()` on application shutdown to flush pending events and prevent data loss.
</Warning>
