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

# Listar grupos de assets de la organización

> List all asset groups belonging to your organization with asset counts.

## Descripción general

Lista todos los grupos de assets (**Asset**: activo digital, como una URL, dirección, perfil, app, etc.) que pertenecen a tu organización. Los grupos de assets te ayudan a organizar tus assets por categoría, proyecto o propósito. Cada grupo incluye un conteo de los assets asignados para facilitar la gestión del inventario.

## Inicio rápido

### Autenticación

Incluye tu clave de API en el encabezado `X-API-KEY`:

```bash theme={null}
X-API-KEY: your_api_key_here
```

### Solicitud de ejemplo

```typescript TypeScript theme={null}
const response = await fetch(
  "https://app.chainpatrol.io/api/v2/organization/asset-groups",
  {
    method: "GET",
    headers: {
      "X-API-KEY": "YOUR_API_KEY_HERE",
    },
  }
);

const data = await response.json();
console.log(data.groups);
```

```javascript JavaScript theme={null}
const response = await fetch(
  "https://app.chainpatrol.io/api/v2/organization/asset-groups",
  {
    method: "GET",
    headers: {
      "X-API-KEY": "YOUR_API_KEY_HERE",
    },
  }
);

const data = await response.json();
console.log(data.groups);
```

```python Python theme={null}
import requests

response = requests.get(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    headers={
        "X-API-KEY": "YOUR_API_KEY_HERE",
    },
)

data = response.json()
print(data["groups"])
```

```bash cURL theme={null}
curl -X GET 'https://app.chainpatrol.io/api/v2/organization/asset-groups' \
  -H 'X-API-KEY: YOUR_API_KEY_HERE'
```

## Respuesta

### Respuesta exitosa

```json theme={null}
{
  "groups": [
    {
      "id": 1,
      "name": "URLs",
      "assetCount": 25
    },
    {
      "id": 2,
      "name": "Wallets",
      "assetCount": 10
    },
    {
      "id": 3,
      "name": "Socials",
      "assetCount": 15
    },
    {
      "id": 4,
      "name": "Empty Group",
      "assetCount": 0
    }
  ]
}
```

### Campos de la respuesta

| Campo | Tipo | Descripción |
| - | - | - |
| groups | array | Arreglo de objetos de grupo que pertenecen a tu organización |
| groups\[].id | number | Identificador único del grupo |
| groups\[].name | string | Nombre visible del grupo |
| groups\[].assetCount | number | Cantidad de assets asignados actualmente a este grupo |

## Respuestas de error

### 401 Unauthorized

Se devuelve cuando falta la clave de API, no es válida o no tiene acceso a la organización:

```json theme={null}
{
  "error": {
    "code": "UNAUTHORIZED",
    "message": "API key with organization access required"
  }
}
```

## Casos de uso

### Mostrar estadísticas de los grupos

```typescript theme={null}
async function displayGroupStats() {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { groups } = await response.json();

  console.log("Asset Group Statistics:");
  console.log("========================");

  groups.forEach((group) => {
    console.log(`${group.name}: ${group.assetCount} assets`);
  });

  const totalAssets = groups.reduce((sum, g) => sum + g.assetCount, 0);
  console.log(`\nTotal: ${totalAssets} assets across ${groups.length} groups`);
}
```

### Buscar un grupo por nombre

```typescript theme={null}
async function findGroupByName(groupName: string) {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { groups } = await response.json();
  const group = groups.find((g) => g.name.toLowerCase() === groupName.toLowerCase());

  if (group) {
    console.log(`Found group "${group.name}" (ID: ${group.id}) with ${group.assetCount} assets`);
    return group;
  } else {
    console.log(`Group "${groupName}" not found`);
    return null;
  }
}

// Usage
findGroupByName("Wallets");
```

### Identificar grupos vacíos

```typescript theme={null}
async function findEmptyGroups() {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { groups } = await response.json();
  const emptyGroups = groups.filter((g) => g.assetCount === 0);

  if (emptyGroups.length > 0) {
    console.log(`Found ${emptyGroups.length} empty groups:`);
    emptyGroups.forEach((g) => console.log(`  - ${g.name} (ID: ${g.id})`));
  } else {
    console.log("No empty groups found");
  }

  return emptyGroups;
}
```

### Crear un selector de grupos para la interfaz

```typescript theme={null}
interface GroupOption {
  value: number;
  label: string;
  count: number;
}

async function getGroupOptions(): Promise<GroupOption[]> {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { groups } = await response.json();

  return groups.map((group) => ({
    value: group.id,
    label: `${group.name} (${group.assetCount})`,
    count: group.assetCount,
  }));
}

// Usage in a UI framework
async function renderGroupSelector() {
  const options = await getGroupOptions();
  
  // Example for React/similar framework
  // return (
  //   <select>
  //     {options.map(opt => (
  //       <option key={opt.value} value={opt.value}>
  //         {opt.label}
  //       </option>
  //     ))}
  //   </select>
  // );
}
```

### Exportar un resumen de los grupos

```typescript theme={null}
async function exportGroupSummary() {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { groups } = await response.json();

  // Create CSV content
  const csvHeader = "Group ID,Group Name,Asset Count\n";
  const csvRows = groups
    .map((g) => `${g.id},"${g.name}",${g.assetCount}`)
    .join("\n");
  const csvContent = csvHeader + csvRows;

  // Save to file (Node.js)
  const fs = require("fs");
  fs.writeFileSync("group-summary.csv", csvContent);
  console.log("Group summary exported to group-summary.csv");
}
```

### Monitorear el crecimiento de los grupos

```typescript theme={null}
async function monitorGroupGrowth() {
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { groups } = await response.json();

  // Sort by asset count
  const sortedGroups = [...groups].sort((a, b) => b.assetCount - a.assetCount);

  console.log("Groups by size (largest first):");
  sortedGroups.forEach((group, index) => {
    const percentage = groups.reduce((sum, g) => sum + g.assetCount, 0);
    const groupPercentage = ((group.assetCount / percentage) * 100).toFixed(1);
    console.log(
      `${index + 1}. ${group.name}: ${group.assetCount} assets (${groupPercentage}%)`
    );
  });
}
```

## Buenas prácticas

### Caché

* Guarda en caché las listas de grupos cuando construyas menús desplegables en la interfaz para reducir las llamadas a la API
* Invalida la caché cuando se creen, actualicen o eliminen grupos
* Considera un TTL de caché de 5 a 10 minutos para los casos de uso típicos

### Rendimiento

* Este endpoint devuelve todos los grupos en una sola solicitud (no se necesita paginación)
* Los grupos suelen ser pocos (\< 100 en la mayoría de las organizaciones)
* Usa este endpoint para construir tablas de búsqueda que relacionen el ID de cada grupo con su nombre

### Integración

```typescript theme={null}
// Create a helper class for group management
class GroupManager {
  private apiKey: string;
  private cache: Map<number, { name: string; assetCount: number }> = new Map();
  private cacheTime: number = 0;
  private cacheTTL: number = 5 * 60 * 1000; // 5 minutes

  constructor(apiKey: string) {
    this.apiKey = apiKey;
  }

  async getGroups(forceRefresh: boolean = false) {
    if (!forceRefresh && Date.now() - this.cacheTime < this.cacheTTL) {
      return Array.from(this.cache.values());
    }

    const response = await fetch(
      "https://app.chainpatrol.io/api/v2/organization/asset-groups",
      {
        headers: { "X-API-KEY": this.apiKey },
      }
    );

    const { groups } = await response.json();
    
    this.cache.clear();
    groups.forEach((g) => {
      this.cache.set(g.id, { name: g.name, assetCount: g.assetCount });
    });
    this.cacheTime = Date.now();

    return groups;
  }

  async getGroupName(groupId: number): Promise<string | null> {
    if (this.cache.has(groupId)) {
      return this.cache.get(groupId)!.name;
    }

    await this.getGroups();
    return this.cache.get(groupId)?.name || null;
  }

  invalidateCache() {
    this.cache.clear();
    this.cacheTime = 0;
  }
}

// Usage
const manager = new GroupManager("YOUR_API_KEY_HERE");
const groups = await manager.getGroups();
const groupName = await manager.getGroupName(1);
```

## Notas

* La organización se determina automáticamente a partir de tu clave de API
* Todos los grupos que pertenecen a tu organización se devuelven en una sola respuesta
* `assetCount` refleja la cantidad actual de assets asignados a cada grupo
* Los grupos con cero assets igualmente se incluyen en la respuesta
* Los ID de grupo son únicos dentro de tu organización
* Este endpoint no admite paginación porque la cantidad de grupos suele ser pequeña


## OpenAPI

````yaml GET /organization/asset-groups
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:
  /organization/asset-groups:
    get:
      tags:
        - organization
      summary: List organization asset groups
      description: List all asset groups belonging to your organization with asset counts.
      operationId: organizationAssetGroupsList
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  groups:
                    type: array
                    items:
                      type: object
                      properties:
                        id:
                          type: number
                          description: Group ID
                        name:
                          type: string
                          description: Group name
                        assetCount:
                          type: number
                          description: Number of assets in this group
                      required:
                        - id
                        - name
                        - assetCount
                    description: List of asset groups
                required:
                  - groups
                description: Successful operation
        '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'
        '404':
          description: Not found
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/error.NOT_FOUND'
        '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.NOT_FOUND:
      type: object
      properties:
        message:
          type: string
          description: The error message
          example: Not found
        code:
          type: string
          description: The error code
          example: NOT_FOUND
        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: Not found error (404)
      description: The error information
      example:
        code: NOT_FOUND
        message: Not found
        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.