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

> Monitora le chiamate API e l'utilizzo a livello di gateway per la fatturazione. Perfetto per piattaforme API-as-a-service con tracciamento di richieste ad alto volume.

## Casi d'uso

Esplora scenari comuni supportati dall'API Gateway Blueprint:

<CardGroup cols={2}>
  <Card title="API-as-a-Service" icon="server">
    Monitora l’utilizzo per cliente sulle piattaforme API e addebita in base al numero di chiamate.
  </Card>

  <Card title="Rate Limiting" icon="gauge">
    Monitora i modelli di utilizzo delle API e implementa limitazioni di velocità basate sull’uso.
  </Card>

  <Card title="Performance Monitoring" icon="chart-line">
    Monitora tempi di risposta e tassi di errore insieme ai dati di fatturazione.
  </Card>

  <Card title="Multi-Tenant SaaS" icon="users">
    Fattura i clienti in base al loro consumo di API attraverso diversi endpoint.
  </Card>
</CardGroup>

<Info>
  Ideale per monitorare l’utilizzo degli endpoint API, il rate limiting e implementare la fatturazione delle API basata sull’utilizzo.
</Info>

## Avvio Veloce

Monitora le chiamate API a livello di gateway con batching automatico per scenari ad alto volume:

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

  <Step title="Get Your API Keys">
    * **Chiave API Dodo Payments**: ottienila da [Dodo Payments Dashboard](https://app.dodopayments.com/developer/api-keys)
  </Step>

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

    * **Nome evento**: `api_call` (o il nome che preferisci)
    * **Tipo di aggregazione**: `count` per monitorare il numero di chiamate
    * Configura proprietà aggiuntive se monitori metadati come tempi di risposta, codici di stato, ecc.
  </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>

## Configurazione

### Configurazione dell'Ingestione

<ParamField path="apiKey" type="string" required>
  La tua chiave API Dodo Payments dal dashboard.
</ParamField>

<ParamField path="environment" type="string" required>
  Modalità ambiente: `test_mode` o `live_mode`.
</ParamField>

<ParamField path="eventName" type="string" required>
  Nome dell’evento che corrisponde alla configurazione del tuo meter.
</ParamField>

### Opzioni di Monitoraggio delle Chiamate API

<ParamField path="customerId" type="string" required>
  L’ID cliente per l’attribuzione della fatturazione.
</ParamField>

<ParamField path="metadata" type="object">
  Metadati opzionali sulla chiamata API come endpoint, metodo, codice di stato, tempo di risposta, ecc.
</ParamField>

### Configurazione del Batch

<ParamField path="maxSize" type="number">
  Numero massimo di eventi prima dell’auto-flush. Valore predefinito: `100`.
</ParamField>

<ParamField path="flushInterval" type="number">
  Intervallo di auto-flush in millisecondi. Valore predefinito: `5000` (5 secondi).
</ParamField>

## Migliori Pratiche

<Tip>
  **Usa il batch per volumi elevati**: per applicazioni che gestiscono più di 10 richieste al secondo, usa `createBatch()` per ridurre il sovraccarico e migliorare le prestazioni.
</Tip>

<Warning>
  **Pulisci sempre i batch**: chiama `batch.cleanup()` alla chiusura dell’applicazione per svuotare gli eventi in sospeso ed evitare la perdita di dati.
</Warning>
