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

# Create Organization Asset Group

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

## Overview

Create a new asset group for organizing your organization's assets. Groups help you categorize assets by type, project, purpose, or any other criteria that makes sense for your use case.

## Quick Start

### Authentication

Include your API key in the `X-API-KEY` header:

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

### Example Request

<CodeGroup>
  ```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"
    }'
  ```
</CodeGroup>

## Request Body

| Field | Type   | Required | Description                               |
| ----- | ------ | -------- | ----------------------------------------- |
| name  | string | Yes      | Name for the new group (1-255 characters) |

## Response

### Success Response

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

### Response Fields

| Field | Type   | Description                     |
| ----- | ------ | ------------------------------- |
| id    | number | Unique identifier for the group |
| name  | string | Name of the created group       |

## Error Responses

### 400 Bad Request

Returned when the request is malformed or validation fails:

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

Returned when the API key is missing, invalid, or doesn't have organization access:

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

### 409 Conflict

Returned when a group with the same name already exists:

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

## Best Practices

### Naming Conventions

Use clear, descriptive names that reflect the group's purpose:

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

### Check for Existing Groups

Before creating a group, check if one with the same name already exists:

```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;
}
```

### Batch Group Creation

Create multiple groups in sequence:

```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}`);
    }
  });
});
```

## Use Cases

### Initialize Group Structure

Set up a standard group structure for a new organization:

```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");
}
```

### Project-Based Groups

Create groups for different projects:

```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`);
});
```

### Environment-Based Groups

Organize by environment (production, staging, development):

```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}`);
    }
  }
}
```

### Dynamic Group Creation

Create groups dynamically based on asset type:

```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");
```

## Common Error Messages

| Error Message                                   | Cause                           | Resolution                                 |
| ----------------------------------------------- | ------------------------------- | ------------------------------------------ |
| Group name is required                          | Missing `name` field in request | Provide a `name` field                     |
| Group name must be between 1 and 255 characters | Name is too short or too long   | Use a name with 1-255 characters           |
| A group with this name already exists           | Duplicate group name            | Use a different name or use existing group |

## Notes

* Group names must be unique within your organization
* Names are case-sensitive for uniqueness checks
* Group names have a maximum length of 255 characters
* Organization is automatically determined from your API key
* Newly created groups start with zero assets
* Groups can be renamed later using the update endpoint
* There is no hard limit on the number of groups per organization


## 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
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
              required:
                - name
      responses:
        '200':
          description: Successful response
          content:
            application/json:
              schema:
                type: object
                properties:
                  id:
                    type: number
                  name:
                    type: string
                required:
                  - id
                  - name
        '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.

````