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

# Crear grupo de assets de la organización

> Create a new asset group for organizing your organization's assets.

## Descripción general

Crea un nuevo grupo de **Assets** (activos digitales: URL, direcciones, perfiles, apps, etc.) para ordenar los assets de tu organización. Los grupos te ayudan a clasificar los assets por tipo, proyecto, propósito o cualquier otro criterio que tenga sentido para tu caso de uso.

## 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: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-KEY": "YOUR_API_KEY_HERE",
    },
    body: JSON.stringify({
      name: "New Group",
    }),
  }
);

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

```javascript JavaScript theme={null}
const response = await fetch(
  "https://app.chainpatrol.io/api/v2/organization/asset-groups",
  {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      "X-API-KEY": "YOUR_API_KEY_HERE",
    },
    body: JSON.stringify({
      name: "New Group",
    }),
  }
);

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

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

response = requests.post(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    headers={
        "Content-Type": "application/json",
        "X-API-KEY": "YOUR_API_KEY_HERE",
    },
    json={
        "name": "New Group",
    },
)

data = response.json()
print(data)
```

```bash cURL theme={null}
curl -X POST 'https://app.chainpatrol.io/api/v2/organization/asset-groups' \
  -H 'X-API-KEY: YOUR_API_KEY_HERE' \
  -H 'Content-Type: application/json' \
  -d '{
    "name": "New Group"
  }'
```

## Cuerpo de la solicitud

| Campo | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| name | string | Sí | Nombre del nuevo grupo (de 1 a 255 caracteres) |

## Respuesta

### Respuesta exitosa

```json theme={null}
{
  "id": 4,
  "name": "New Group"
}
```

### Campos de la respuesta

| Campo | Tipo | Descripción |
| - | - | - |
| id | number | Identificador único del grupo |
| name | string | Nombre del grupo creado |

## Respuestas de error

### 400 Bad Request

Se devuelve cuando la solicitud tiene un formato incorrecto o falla la validación:

```json theme={null}
{
  "error": {
    "code": "BAD_REQUEST",
    "message": "Group name is required"
  }
}
```

```json theme={null}
{
  "error": {
    "code": "BAD_REQUEST",
    "message": "Group name must be between 1 and 255 characters"
  }
}
```

### 401 Unauthorized

Se devuelve cuando la clave de API falta, 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"
  }
}
```

### 409 Conflict

Se devuelve cuando ya existe un grupo con el mismo nombre:

```json theme={null}
{
  "error": {
    "code": "CONFLICT",
    "message": "A group with this name already exists"
  }
}
```

## Buenas prácticas

### Convenciones de nombres

Usa nombres claros y descriptivos que reflejen el propósito del grupo:

```typescript theme={null}
// Good examples
await createGroup("Official Websites");
await createGroup("Treasury Wallets");
await createGroup("Social Media Accounts");
await createGroup("Smart Contracts - Production");
await createGroup("Smart Contracts - Testnet");

// Avoid
await createGroup("Group1"); // Not descriptive
await createGroup("Misc"); // Too vague
await createGroup("test"); // Not professional
```

### Verifica si ya existe el grupo

Antes de crear un grupo, verifica si ya existe uno con el mismo nombre:

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

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

  if (existingGroup) {
    console.log(`Group "${groupName}" already exists with ID ${existingGroup.id}`);
    return existingGroup;
  }

  // Create new group
  const createResponse = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "YOUR_API_KEY_HERE",
      },
      body: JSON.stringify({ name: groupName }),
    }
  );

  const newGroup = await createResponse.json();
  console.log(`Created new group "${groupName}" with ID ${newGroup.id}`);
  return newGroup;
}
```

### Creación de grupos por lotes

Crea varios grupos en secuencia:

```typescript theme={null}
async function createMultipleGroups(groupNames: string[]) {
  const results = [];

  for (const name of groupNames) {
    try {
      const response = await fetch(
        "https://app.chainpatrol.io/api/v2/organization/asset-groups",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "YOUR_API_KEY_HERE",
          },
          body: JSON.stringify({ name }),
        }
      );

      if (response.ok) {
        const group = await response.json();
        results.push({ name, success: true, id: group.id });
      } else {
        const error = await response.json();
        results.push({ name, success: false, error: error.error.message });
      }
    } catch (error) {
      results.push({ name, success: false, error: String(error) });
    }
  }

  return results;
}

// Usage
const groupNames = ["Websites", "Wallets", "Social Media", "Contracts"];
createMultipleGroups(groupNames).then((results) => {
  const successful = results.filter((r) => r.success).length;
  console.log(`Created ${successful} of ${results.length} groups`);
  
  results.forEach((r) => {
    if (r.success) {
      console.log(`✓ ${r.name} (ID: ${r.id})`);
    } else {
      console.log(`✗ ${r.name}: ${r.error}`);
    }
  });
});
```

## Casos de uso

### Inicializar la estructura de grupos

Configura una estructura de grupos estándar para una organización nueva:

```typescript theme={null}
async function initializeGroupStructure() {
  const standardGroups = [
    "Official Websites",
    "Documentation Sites",
    "Blockchain Addresses",
    "Smart Contracts",
    "Twitter Accounts",
    "Discord Servers",
    "Telegram Channels",
    "GitHub Repositories",
    "Email Addresses",
    "Other Assets",
  ];

  console.log("Initializing group structure...");

  for (const groupName of standardGroups) {
    const response = await fetch(
      "https://app.chainpatrol.io/api/v2/organization/asset-groups",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-API-KEY": "YOUR_API_KEY_HERE",
        },
        body: JSON.stringify({ name: groupName }),
      }
    );

    if (response.ok) {
      const group = await response.json();
      console.log(`✓ Created "${groupName}" (ID: ${group.id})`);
    } else {
      console.log(`✗ Failed to create "${groupName}"`);
    }
  }

  console.log("Group structure initialization complete");
}
```

### Grupos por proyecto

Crea grupos para distintos proyectos:

```typescript theme={null}
async function createProjectGroups(projectName: string) {
  const groupTypes = ["URLs", "Wallets", "Contracts", "Socials"];

  const groups = [];

  for (const type of groupTypes) {
    const groupName = `${projectName} - ${type}`;
    
    const response = await fetch(
      "https://app.chainpatrol.io/api/v2/organization/asset-groups",
      {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          "X-API-KEY": "YOUR_API_KEY_HERE",
        },
        body: JSON.stringify({ name: groupName }),
      }
    );

    if (response.ok) {
      const group = await response.json();
      groups.push(group);
      console.log(`Created group: ${groupName}`);
    }
  }

  return groups;
}

// Usage
createProjectGroups("DeFi Protocol").then((groups) => {
  console.log(`Created ${groups.length} groups for project`);
});
```

### Grupos por entorno

Organiza por entorno (producción, staging, desarrollo):

```typescript theme={null}
async function createEnvironmentGroups() {
  const environments = ["Production", "Staging", "Development"];
  const categories = ["URLs", "APIs", "Contracts"];

  for (const env of environments) {
    for (const category of categories) {
      const groupName = `${env} - ${category}`;
      
      await fetch(
        "https://app.chainpatrol.io/api/v2/organization/asset-groups",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "YOUR_API_KEY_HERE",
          },
          body: JSON.stringify({ name: groupName }),
        }
      );

      console.log(`Created: ${groupName}`);
    }
  }
}
```

### Creación dinámica de grupos

Crea grupos de forma dinámica según el tipo de asset:

```typescript theme={null}
async function ensureGroupForAssetType(assetType: string) {
  const groupName = `${assetType} Assets`;

  // Check if group exists
  const listResponse = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { groups } = await listResponse.json();
  const existingGroup = groups.find((g) => g.name === groupName);

  if (existingGroup) {
    return existingGroup.id;
  }

  // Create new group
  const createResponse = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/asset-groups",
    {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "YOUR_API_KEY_HERE",
      },
      body: JSON.stringify({ name: groupName }),
    }
  );

  const newGroup = await createResponse.json();
  return newGroup.id;
}

// Usage: Automatically create groups as needed
const urlGroupId = await ensureGroupForAssetType("URL");
const addressGroupId = await ensureGroupForAssetType("ADDRESS");
```

## Mensajes de error comunes

| Mensaje de error | Causa | Solución |
| - | - | - |
| Group name is required | Falta el campo `name` en la solicitud | Incluye un campo `name` |
| Group name must be between 1 and 255 characters | El nombre es demasiado corto o demasiado largo | Usa un nombre de 1 a 255 caracteres |
| A group with this name already exists | Nombre de grupo duplicado | Usa un nombre distinto o usa el grupo existente |

## Notas

* Los nombres de los grupos deben ser únicos dentro de tu organización
* Los nombres distinguen entre mayúsculas y minúsculas al verificar que sean únicos
* Los nombres de los grupos tienen una longitud máxima de 255 caracteres
* La organización se determina automáticamente a partir de tu clave de API
* Los grupos recién creados empiezan con cero assets
* Los grupos se pueden renombrar más adelante con el endpoint de actualización
* No hay un límite fijo para la cantidad de grupos por organización


## OpenAPI

````yaml POST /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:
    post:
      tags:
        - organization
      summary: Create asset group
      description: Create a new asset group for organizing your organization's assets.
      operationId: organizationAssetGroupsCreate
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                name:
                  type: string
                  minLength: 1
                  maxLength: 255
                  description: Name for the new group
              required:
                - name
              description: >-
                Create a new asset group


                Creates a new asset group for organizing your organization's
                assets.
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: number
                    description: Created group ID
                  name:
                    type: string
                    description: Group name
                required:
                  - id
                  - name
                description: Created group
        '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.