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

# Quitar asset de la organización

> Remove an asset from your organization's allowlist. This performs a soft delete.

## Descripción general

Quita un **Asset** (activo digital: URL, dirección, perfil, app, etc.) de la **Allowlist** (lista de permitidos) de tu organización. Esta operación elimina la asociación entre el asset y tu organización: el asset en sí permanece en el sistema de ChainPatrol, pero ya no está vinculado a tu organización. El asset debe pertenecer a tu organización para poder quitarlo.

## 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/assets/12345",
  {
    method: "DELETE",
    headers: {
      "Content-Type": "application/json",
      "X-API-KEY": "YOUR_API_KEY_HERE",
    },
    body: JSON.stringify({
      assetId: 12345,
    }),
  }
);

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

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

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

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

response = requests.delete(
    "https://app.chainpatrol.io/api/v2/organization/assets/12345",
    headers={
        "Content-Type": "application/json",
        "X-API-KEY": "YOUR_API_KEY_HERE",
    },
    json={
        "assetId": 12345,
    },
)

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

```bash cURL theme={null}
curl -X DELETE 'https://app.chainpatrol.io/api/v2/organization/assets/12345' \
  -H 'X-API-KEY: YOUR_API_KEY_HERE' \
  -H 'Content-Type: application/json' \
  -d '{
    "assetId": 12345
  }'
```

## Parámetros de ruta

| Parámetro | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| assetId | number | Sí | ID del asset que se va a quitar |

## Cuerpo de la solicitud

| Campo | Tipo | Obligatorio | Descripción |
| - | - | - | - |
| assetId | number | Sí | ID del asset que se va a quitar (debe coincidir con el parámetro de ruta) |

## Respuesta

### Respuesta exitosa

```json theme={null}
{
  "success": true,
  "id": 12345
}
```

### Campos de la respuesta

| Campo | Tipo | Descripción |
| - | - | - |
| success | boolean | Siempre `true` cuando el asset se quita correctamente |
| id | number | ID del asset que se quitó de la organización |

## Respuestas de error

### 400 Bad Request

Se devuelve cuando la solicitud está mal formada:

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

### 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"
  }
}
```

### 403 Forbidden

Se devuelve cuando el asset no pertenece a tu organización:

```json theme={null}
{
  "error": {
    "code": "FORBIDDEN",
    "message": "Asset does not belong to your organization"
  }
}
```

### 404 Not Found

Se devuelve cuando el asset no existe o ya se había quitado de tu organización:

```json theme={null}
{
  "error": {
    "code": "NOT_FOUND",
    "message": "Asset with ID 12345 not found"
  }
}
```

## Buenas prácticas

### Verificación antes de quitar

Verifica siempre el asset antes de quitarlo para evitar operaciones accidentales:

```typescript theme={null}
async function safeRemoveAsset(assetId: number) {
  // First, fetch the asset to verify it exists and belongs to your org
  const getResponse = await fetch(
    `https://app.chainpatrol.io/api/v2/organization/assets?query=${assetId}`,
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

  const { assets } = await getResponse.json();
  const asset = assets.find((a) => a.id === assetId);

  if (!asset) {
    console.error("Asset not found or doesn't belong to organization");
    return;
  }

  // Show confirmation
  console.log(`About to remove from organization: ${asset.content} (${asset.name})`);
  
  // Proceed with removal
  const deleteResponse = await fetch(
    `https://app.chainpatrol.io/api/v2/organization/assets/${assetId}`,
    {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "YOUR_API_KEY_HERE",
      },
      body: JSON.stringify({ assetId }),
    }
  );

  const result = await deleteResponse.json();
  console.log("Asset removed from organization:", result);
}
```

### Eliminación masiva

Cuando quites varios assets de tu organización, procésalos de forma secuencial y con manejo de errores:

```typescript theme={null}
async function bulkRemoveAssets(assetIds: number[]) {
  const results = [];

  for (const assetId of assetIds) {
    try {
      const response = await fetch(
        `https://app.chainpatrol.io/api/v2/organization/assets/${assetId}`,
        {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "YOUR_API_KEY_HERE",
          },
          body: JSON.stringify({ assetId }),
        }
      );

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

  return results;
}

// Usage
const assetIds = [12345, 12346, 12347];
bulkRemoveAssets(assetIds).then((results) => {
  const successful = results.filter((r) => r.success).length;
  const failed = results.filter((r) => !r.success).length;
  console.log(`Removed ${successful} assets from organization, ${failed} failed`);
  
  // Log failures
  results
    .filter((r) => !r.success)
    .forEach((r) => console.error(`Failed to remove ${r.id}: ${r.error}`));
});
```

### Registro de auditoría

Implementa un registro de las operaciones de eliminación con fines de cumplimiento y depuración:

```typescript theme={null}
async function removeAssetWithAudit(
  assetId: number,
  reason: string,
  removedBy: string
) {
  // Fetch asset details for audit log
  const getResponse = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/assets",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );
  const { assets } = await getResponse.json();
  const asset = assets.find((a) => a.id === assetId);

  if (!asset) {
    throw new Error("Asset not found");
  }

  // Perform removal
  const deleteResponse = await fetch(
    `https://app.chainpatrol.io/api/v2/organization/assets/${assetId}`,
    {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        "X-API-KEY": "YOUR_API_KEY_HERE",
      },
      body: JSON.stringify({ assetId }),
    }
  );

  const result = await deleteResponse.json();

  // Log to your audit system
  const auditLog = {
    timestamp: new Date().toISOString(),
    action: "ASSET_REMOVED_FROM_ORGANIZATION",
    assetId: asset.id,
    assetContent: asset.content,
    assetName: asset.name,
    assetType: asset.type,
    removedBy,
    reason,
    success: result.success,
  };

  console.log("Audit log:", JSON.stringify(auditLog));
  // await sendToAuditSystem(auditLog);

  return result;
}

// Usage
await removeAssetWithAudit(
  12345,
  "Asset no longer in use",
  "admin@example.com"
);
```

## Casos de uso

### Quitar assets desactualizados

```typescript theme={null}
// Remove assets that haven't been updated in over a year
async function removeStaleAssets() {
  const oneYearAgo = new Date();
  oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);

  // Fetch all assets
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/assets",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

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

  // Filter for stale assets
  const staleAssets = assets.filter((asset) => {
    const updatedAt = new Date(asset.updatedAt);
    return updatedAt < oneYearAgo;
  });

  console.log(`Found ${staleAssets.length} stale assets`);

  // Delete each stale asset
  for (const asset of staleAssets) {
    await fetch(
      `https://app.chainpatrol.io/api/v2/organization/assets/${asset.id}`,
      {
        method: "DELETE",
        headers: {
          "Content-Type": "application/json",
          "X-API-KEY": "YOUR_API_KEY_HERE",
        },
        body: JSON.stringify({ assetId: asset.id }),
      }
    );
    console.log(`Removed stale asset: ${asset.content}`);
  }
}
```

### Quitar assets por grupo

```typescript theme={null}
// Remove all assets in a specific group
async function removeAssetsByGroup(groupId: number) {
  // Fetch all assets in the group
  const response = await fetch(
    `https://app.chainpatrol.io/api/v2/organization/assets?groupId=${groupId}`,
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );

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

  console.log(`Removing ${assets.length} assets from group ${groupId}`);

  // Delete each asset
  const results = await Promise.all(
    assets.map(async (asset) => {
      const deleteResponse = await fetch(
        `https://app.chainpatrol.io/api/v2/organization/assets/${asset.id}`,
        {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "YOUR_API_KEY_HERE",
          },
          body: JSON.stringify({ assetId: asset.id }),
        }
      );
      return deleteResponse.json();
    })
  );

  const successCount = results.filter((r) => r.success).length;
  console.log(`Successfully removed ${successCount} assets`);
}
```

### Eliminación interactiva con confirmación

```typescript theme={null}
import * as readline from "readline";

async function removeAssetInteractive(assetId: number) {
  // Fetch asset details
  const response = await fetch(
    "https://app.chainpatrol.io/api/v2/organization/assets",
    {
      headers: { "X-API-KEY": "YOUR_API_KEY_HERE" },
    }
  );
  const { assets } = await response.json();
  const asset = assets.find((a) => a.id === assetId);

  if (!asset) {
    console.error("Asset not found");
    return;
  }

  // Display asset details
  console.log("\nAsset to be removed from organization:");
  console.log(`  ID: ${asset.id}`);
  console.log(`  Content: ${asset.content}`);
  console.log(`  Name: ${asset.name}`);
  console.log(`  Type: ${asset.type}`);
  console.log(`  Group: ${asset.group?.name || "None"}\n`);

  // Ask for confirmation
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });

  rl.question("Are you sure you want to remove this asset from your organization? (yes/no): ", async (answer) => {
    if (answer.toLowerCase() === "yes") {
      const deleteResponse = await fetch(
        `https://app.chainpatrol.io/api/v2/organization/assets/${assetId}`,
        {
          method: "DELETE",
          headers: {
            "Content-Type": "application/json",
            "X-API-KEY": "YOUR_API_KEY_HERE",
          },
          body: JSON.stringify({ assetId }),
        }
      );

      const result = await deleteResponse.json();
      if (result.success) {
        console.log("Asset successfully removed from organization");
      } else {
        console.error("Failed to remove asset");
      }
    } else {
      console.log("Removal cancelled");
    }
    rl.close();
  });
}
```

## Notas

* Esta operación elimina la asociación entre el asset y tu organización: el asset en sí permanece en el sistema de ChainPatrol
* Después de quitarlo, el asset ya no aparecerá en las listas de assets de tu organización
* Solo se pueden quitar los assets que pertenecen a tu organización
* La organización se determina automáticamente a partir de tu clave de API
* El ID del asset debe coincidir tanto en la ruta de la URL como en el cuerpo de la solicitud
* Si lo necesitas, más adelante puedes volver a agregar el mismo asset a tu organización con el endpoint Agregar assets a la organización
* Quitar un asset no afecta su existencia en la base de datos de ChainPatrol ni su estado para otras organizaciones


## OpenAPI

````yaml DELETE /organization/assets/{assetId}
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/assets/{assetId}:
    delete:
      tags:
        - organization
      summary: Remove asset from organization
      description: >-
        Remove an asset from your organization's allowlist. This performs a soft
        delete.
      operationId: organizationAssetsDelete
      parameters:
        - in: path
          name: assetId
          description: ID of the asset to remove
          schema:
            type: integer
            minimum: 0
            exclusiveMinimum: true
            description: ID of the asset to remove
          required: true
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    description: Whether the asset was removed successfully
                  id:
                    type: number
                    description: Asset ID that was removed
                required:
                  - success
                  - id
                description: Delete operation result
        '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.