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

# Obtener métricas de la organización (obsoleto)

> Get public metrics for one or more organizations

> [!WARNING]
>
> **Este endpoint está obsoleto.** Usa en su lugar el nuevo endpoint RESTful [GET /organization/metrics](https://chainpatrol.com/docs/es/external-api/organization-metrics-list.md). Este endpoint se eliminará en una versión futura.

## Inicio rápido

### Autenticación

Incluye tu clave de API en el encabezado `Authorization`:

```bash theme={null}
Authorization: Bearer your_api_key
```

### Solicitud de ejemplo

```bash theme={null}
curl -X POST 'https://app.chainpatrol.io/api/v2/public/getOrganizationMetrics' \
  -H 'Authorization: Bearer your_api_key' \
  -H 'Content-Type: application/json' \
  -d '{
    "organizationSlug": "your-org",
    "startDate": "2024-01-01T00:00:00Z",
    "endDate": "2024-03-01T00:00:00Z"
  }'
```

## Control de acceso

La API aplica un control de acceso estricto según el tipo de tu clave de API:

1. **Claves de API de organización**:

   * Solo pueden acceder a las métricas de su organización asociada
   * Deben coincidir exactamente con el `organizationSlug`
   * Ejemplo: una clave de API de "acme-org" solo puede consultar las métricas de "acme-org"

2. **Claves de API de usuario**:
   * Pueden acceder a las métricas de cualquier organización de la que el usuario sea miembro
   * Requieren que el usuario sea un miembro activo de la organización consultada
   * Ejemplo: un usuario que es miembro tanto de "acme-org" como de "beta-org" puede consultar las métricas de ambas organizaciones

Si intentas consultar una organización sin los permisos adecuados, recibirás un error 403 Forbidden con el mensaje: "You do not have permission to access metrics for this organization"

## Implementación de ejemplo

```javascript JavaScript theme={null}
async function fetchOrganizationMetrics(organizationSlug, startDate, endDate) {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/public/getOrganizationMetrics",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer YOUR_API_KEY_HERE",
      },
      body: JSON.stringify({
        organizationSlug,
        startDate,
        endDate,
      }),
    }
  );
  return response.json();
}

// Example usage
fetchOrganizationMetrics(
  "your-org",
  "2024-01-01T00:00:00Z",
  "2024-03-01T00:00:00Z"
)
  .then((data) => console.log("Metrics:", data))
  .catch((error) => console.error("Error fetching metrics:", error));
```

```typescript TypeScript theme={null}
interface OrganizationMetrics {
  metrics: {
    reportsCount: number;
    threatsBlockedCount: number;
    threatsBlockedByAssetType: Array<{
      assetType: string;
      count: number;
    }>;
    domainsBlockedCount: number;
    totalTakedownsFiledCount: number;
    totalTakedownsCompletedCount: number;
    totalDetections: number;
  };
}

async function fetchOrganizationMetrics(
  organizationSlug: string,
  startDate?: string,
  endDate?: string
): Promise<OrganizationMetrics> {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/public/getOrganizationMetrics",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: "Bearer YOUR_API_KEY_HERE",
      },
      body: JSON.stringify({
        organizationSlug,
        startDate,
        endDate,
      }),
    }
  );
  return response.json();
}

// Example usage
fetchOrganizationMetrics(
  "your-org",
  "2024-01-01T00:00:00Z",
  "2024-03-01T00:00:00Z"
)
  .then((data) => console.log("Metrics:", data))
  .catch((error) => console.error("Error fetching metrics:", error));
```

```python Python theme={null}
import requests
from typing import Dict, Optional
from datetime import datetime

def fetch_organization_metrics(
    organization_slug: str,
    start_date: Optional[str] = None,
    end_date: Optional[str] = None
) -> Dict:
    response = requests.post(
        "https://app.chainpatrol.io/api/v2/public/getOrganizationMetrics",
        headers={
            "Content-Type": "application/json",
            "Authorization": "Bearer YOUR_API_KEY_HERE",
        },
        json={
            "organizationSlug": organization_slug,
            "startDate": start_date,
            "endDate": end_date,
        },
    )
    return response.json()

# Example usage
try:
    metrics = fetch_organization_metrics(
        "your-org",
        "2024-01-01T00:00:00Z",
        "2024-03-01T00:00:00Z"
    )
    print("Metrics:", metrics)
except Exception as error:
    print("Error fetching metrics:", str(error))
```

## Detalles de la API

### Parámetros de la solicitud

| Parámetro | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| organizationSlug | string | Sí | Slug de la organización que se va a consultar |
| startDate | Date | No | Fecha de inicio de las métricas (por defecto: todo el historial) |
| endDate | Date | No | Fecha de fin de las métricas (por defecto: la fecha actual) |

### Formato de la respuesta

```typescript theme={null}
{
  metrics: {
    reportsCount: number; // Total number of reports
    threatsBlockedCount: number; // Total number of threats blocked
    threatsBlockedByAssetType: Array<{
      // Threats blocked grouped by asset type
      assetType: string;
      count: number;
    }>;
    domainsBlockedCount: number; // Number of domains blocked
    totalTakedownsFiledCount: number; // Total number of takedowns filed
    totalTakedownsCompletedCount: number; // Total number of completed takedowns
    totalDetections: number; // Total number of threat detections
  }
}
```

`totalDetections` cuenta las amenazas sospechosas: todos los resultados de detección dentro del rango de fechas
que no se hayan eliminado, sin importar si después se confirmaron o no. Las amenazas confirmadas
se cuentan en `threatsBlockedCount`.

## Manejo de errores

| Código de estado | Descripción |
| - | - |
| 401 Unauthorized | Clave de API no válida o faltante |
| 403 Forbidden | La clave de API no tiene permiso para consultar la organización solicitada |
| 500 Internal Server Error | Ocurrió un error del servidor al procesar la solicitud |

## Notas

* Si no se indica un rango de fechas, se devolverán las métricas de todo el historial
* La API solo devuelve las métricas de una única organización por solicitud
* Las claves de API de organización solo pueden acceder a las métricas de su organización asociada
* Las claves de API de usuario pueden acceder a las métricas de cualquier organización de la que el usuario sea miembro
* Para consultar varias organizaciones, debes usar una clave de API de usuario y asegurarte de que el usuario sea miembro de todas las organizaciones que quieras consultar


## OpenAPI

````yaml POST /public/getOrganizationMetrics
openapi: 3.0.3
info:
  title: ChainPatrol External API - OpenAPI 3.0
  description: ChainPatrol External API documentation
  version: 2.0.0
servers:
  - url: https://app.chainpatrol.io/api/v2
security: []
tags:
  - name: asset
  - name: report
  - name: dark-web
externalDocs:
  url: https://chainpatrol.com/docs
paths:
  /public/getOrganizationMetrics:
    post:
      tags:
        - public
      summary: Get public metrics for organizations
      description: Get public metrics for one or more organizations
      operationId: getPublicOrganizationMetrics
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                organizationSlug:
                  type: string
                brandSlug:
                  type: string
                startDate:
                  type: string
                  description: >-
                    Count from this date. A date-only value (YYYY-MM-DD) starts
                    at midnight UTC
                endDate:
                  type: string
                  description: >-
                    Count up to and including this date. A date-only value
                    (YYYY-MM-DD) covers the whole day in UTC; pass a full
                    timestamp for a precise cut-off
              required:
                - organizationSlug
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  metrics:
                    type: object
                    properties:
                      reports:
                        type: number
                      newThreats:
                        type: number
                      threatsWatchlisted:
                        type: number
                      takedownsFiled:
                        type: number
                      takedownsCompleted:
                        type: number
                      domainThreats:
                        type: number
                      twitterThreats:
                        type: number
                      telegramThreats:
                        type: number
                      otherThreats:
                        type: number
                    required:
                      - reports
                      - newThreats
                      - threatsWatchlisted
                      - takedownsFiled
                      - takedownsCompleted
                      - domainThreats
                      - twitterThreats
                      - telegramThreats
                      - otherThreats
                  blockedByType:
                    type: array
                    items:
                      type: object
                      properties:
                        type:
                          type: string
                        count:
                          type: number
                      required:
                        - type
                        - count
                  blockedByDay:
                    type: array
                    items:
                      type: object
                      properties:
                        date:
                          type: string
                        count:
                          type: number
                      required:
                        - date
                        - count
                required:
                  - metrics
                  - blockedByType
                  - blockedByDay
        '400':
          description: Invalid input data
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/error.BAD_REQUEST'
        '401':
          description: Authorization not provided
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/error.UNAUTHORIZED'
        '403':
          description: Insufficient access
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/error.FORBIDDEN'
        '500':
          description: Internal server error
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/error.INTERNAL_SERVER_ERROR'
      security:
        - ApiKey: []
components:
  schemas:
    error.BAD_REQUEST:
      type: object
      properties:
        message:
          type: string
          description: The error message
          example: Invalid input data
        code:
          type: string
          description: The error code
          example: BAD_REQUEST
        issues:
          type: array
          items:
            type: object
            properties:
              message:
                type: string
            required:
              - message
          description: An array of issues that were responsible for the error
          example: []
      required:
        - message
        - code
      title: Invalid input data error (400)
      description: The error information
      example:
        code: BAD_REQUEST
        message: Invalid input data
        issues: []
    error.UNAUTHORIZED:
      type: object
      properties:
        message:
          type: string
          description: The error message
          example: Authorization not provided
        code:
          type: string
          description: The error code
          example: UNAUTHORIZED
        issues:
          type: array
          items:
            type: object
            properties:
              message:
                type: string
            required:
              - message
          description: An array of issues that were responsible for the error
          example: []
      required:
        - message
        - code
      title: Authorization not provided error (401)
      description: The error information
      example:
        code: UNAUTHORIZED
        message: Authorization not provided
        issues: []
    error.FORBIDDEN:
      type: object
      properties:
        message:
          type: string
          description: The error message
          example: Insufficient access
        code:
          type: string
          description: The error code
          example: FORBIDDEN
        issues:
          type: array
          items:
            type: object
            properties:
              message:
                type: string
            required:
              - message
          description: An array of issues that were responsible for the error
          example: []
      required:
        - message
        - code
      title: Insufficient access error (403)
      description: The error information
      example:
        code: FORBIDDEN
        message: Insufficient access
        issues: []
    error.INTERNAL_SERVER_ERROR:
      type: object
      properties:
        message:
          type: string
          description: The error message
          example: Internal server error
        code:
          type: string
          description: The error code
          example: INTERNAL_SERVER_ERROR
        issues:
          type: array
          items:
            type: object
            properties:
              message:
                type: string
            required:
              - message
          description: An array of issues that were responsible for the error
          example: []
      required:
        - message
        - code
      title: Internal server error error (500)
      description: The error information
      example:
        code: INTERNAL_SERVER_ERROR
        message: Internal server error
        issues: []
  securitySchemes:
    ApiKey:
      type: apiKey
      in: header
      name: X-API-KEY
      description: >-
        Your API key. This is required by most endpoints to access our API
        programatically. Reach out to us at
        [support@chainpatrol.io](mailto:support@chainpatrol.io?subject=Re:%20API%20Key%20for%20SDK&body=Company:%20%0AName:%20%0APurpose:%20)
        to get an API key for your use.

````

This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.