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

# Create Role

> Create a new user role

# Create Role

Create a new custom user role with specific permissions.

## Endpoint

```
POST /roles
```

## Description

This endpoint allows administrators to create new custom user roles. Custom roles can have specific permissions tailored to your organization's needs. You can specify the role name, description, and permissions during creation.

## Authentication

**Required**: API Key with admin privileges

```
Authorization: Bearer sk-your-api-key-here
```

## Request Body

| Parameter             | Type    | Required | Description                                          |
| --------------------- | ------- | -------- | ---------------------------------------------------- |
| `name`                | string  | Yes      | Role name (system identifier)                        |
| `displayName`         | string  | Yes      | Human-readable role name                             |
| `description`         | string  | Yes      | Description of the role purpose                      |
| `hasAdminPanelAccess` | boolean | No       | Whether role has admin panel access (default: false) |
| `permissions`         | array   | No       | Array of permission objects                          |
| `canInteractWithAI`   | boolean | No       | Whether role can interact with AI (default: true)    |
| `canUseChat`          | boolean | No       | Whether role can use chat (default: true)            |

## Example Request

```json theme={null}
{
  "name": "content_editor",
  "displayName": "Content Editor",
  "description": "Role for editing and managing content",
  "hasAdminPanelAccess": false,
  "permissions": [
    {
      "section": "user-management",
      "level": "reader"
    },
    {
      "section": "index-management",
      "level": "admin"
    }
  ],
  "canInteractWithAI": true,
  "canUseChat": true
}
```

## Success Response

**Status Code**: `201 Created`

```json theme={null}
{
  "success": true,
  "message": "Role created successfully",
  "role": {
    "id": "60a7c8f5e8b4f5001f7a8c26",
    "name": "content_editor",
    "displayName": "Content Editor",
    "description": "Role for editing and managing content",
    "isSystem": false,
    "hasAdminPanelAccess": false,
    "permissions": [
      {
        "section": "user-management",
        "level": "reader"
      },
      {
        "section": "index-management",
        "level": "admin"
      }
    ],
    "canInteractWithAI": true,
    "canUseChat": true,
    "userCount": 0,
    "createdBy": {
      "id": "60a7c8f5e8b4f5001f7a8c24",
      "name": "John Doe",
      "email": "john@example.com"
    },
    "createdAt": "2024-01-20T15:30:00.000Z"
  }
}
```

### Response Fields

| Field                        | Type    | Description                               |
| ---------------------------- | ------- | ----------------------------------------- |
| `success`                    | boolean | Indicates if the operation was successful |
| `message`                    | string  | Success message                           |
| `role`                       | object  | Created role object                       |
| `role.id`                    | string  | Unique role identifier                    |
| `role.name`                  | string  | Role name                                 |
| `role.displayName`           | string  | Display name for the role                 |
| `role.description`           | string  | Role description                          |
| `role.isSystem`              | boolean | Whether this is a system role             |
| `role.hasAdminPanelAccess`   | boolean | Whether role has admin panel access       |
| `role.permissions`           | array   | Array of permission objects               |
| `role.permissions[].section` | string  | Permission section                        |
| `role.permissions[].level`   | string  | Permission level                          |
| `role.canInteractWithAI`     | boolean | Whether role can interact with AI         |
| `role.canUseChat`            | boolean | Whether role can use chat                 |
| `role.userCount`             | integer | Number of users with this role            |
| `role.createdBy`             | object  | User who created the role                 |
| `role.createdBy.id`          | string  | Creator user ID                           |
| `role.createdBy.name`        | string  | Creator name                              |
| `role.createdBy.email`       | string  | Creator email                             |
| `role.createdAt`             | string  | Creation timestamp                        |

## Example Usage

### JavaScript

```javascript theme={null}
const createRole = async (roleData) => {
  const response = await fetch('https://{customer.name}.hiperai.ai/api/external/roles', {
    method: 'POST',
    headers: {
      'Authorization': 'Bearer sk-your-api-key-here',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify(roleData)
  });
  
  return await response.json();
};

// Example usage
const roleData = {
  name: "content_editor",
  displayName: "Content Editor",
  description: "Role for editing and managing content",
  hasAdminPanelAccess: false,
  permissions: [
    {
      section: "user-management",
      level: "reader"
    },
    {
      section: "index-management",
      level: "admin"
    }
  ],
  canInteractWithAI: true,
  canUseChat: true
};

const result = await createRole(roleData);
console.log('Created role:', result.role.id);
```

### Python

```python theme={null}
import requests

def create_role(role_data):
    url = "https://{customer.name}.hiperai.ai/api/external/roles"
    headers = {
        "Authorization": "Bearer sk-your-api-key-here",
        "Content-Type": "application/json"
    }
    
    response = requests.post(url, headers=headers, json=role_data)
    return response.json()

# Example usage
role_data = {
    "name": "content_editor",
    "displayName": "Content Editor",
    "description": "Role for editing and managing content",
    "hasAdminPanelAccess": False,
    "permissions": [
        {
            "section": "user-management",
            "level": "reader"
        },
        {
            "section": "index-management",
            "level": "admin"
        }
    ],
    "canInteractWithAI": True,
    "canUseChat": True
}

result = create_role(role_data)
print("Created role:", result["role"]["id"])
```

### cURL

```bash theme={null}
curl -X POST "https://{customer.name}.hiperai.ai/api/external/roles" \
  -H "Authorization: Bearer sk-your-api-key-here" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "content_editor",
    "displayName": "Content Editor",
    "description": "Role for editing and managing content",
    "hasAdminPanelAccess": false,
    "permissions": [
      {
        "section": "user-management",
        "level": "reader"
      },
      {
        "section": "index-management",
        "level": "admin"
      }
    ],
    "canInteractWithAI": true,
    "canUseChat": true
  }'
```

## Error Responses

### 400 Bad Request

```json theme={null}
{
  "success": false,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Role name is required",
    "details": {
      "field": "name",
      "value": null
    }
  }
}
```

### 401 Unauthorized

```json theme={null}
{
  "success": false,
  "error": {
    "code": "UNAUTHORIZED",
    "message": "Invalid or missing API key"
  }
}
```

### 403 Forbidden

```json theme={null}
{
  "success": false,
  "error": {
    "code": "INSUFFICIENT_PERMISSIONS",
    "message": "Admin privileges required"
  }
}
```

### 409 Conflict

```json theme={null}
{
  "success": false,
  "error": {
    "code": "ROLE_NAME_EXISTS",
    "message": "Role name already exists"
  }
}
```

### 429 Too Many Requests

```json theme={null}
{
  "success": false,
  "error": {
    "code": "RATE_LIMIT_EXCEEDED",
    "message": "Rate limit exceeded",
    "retryAfter": 60
  }
}
```

## Available Permission Sections

| Section            | Description                 |
| ------------------ | --------------------------- |
| `home`             | Home dashboard access       |
| `user-management`  | User management operations  |
| `index-management` | Index management operations |
| `analytics`        | Analytics and reporting     |
| `group-management` | Group management operations |
| `integrations`     | Integration management      |
| `services-status`  | Services status monitoring  |
| `settings`         | System settings             |
| `announcements`    | Announcement management     |
| `smltp-security`   | SMLTP security features     |

## Available Permission Levels

| Level    | Description                               |
| -------- | ----------------------------------------- |
| `none`   | No access to the section                  |
| `reader` | Read-only access to the section           |
| `admin`  | Full administrative access to the section |

## Use Cases

* **Custom Roles**: Create roles tailored to your organization's needs
* **Access Control**: Define specific permissions for different user types
* **Security**: Implement least-privilege access principles
* **Compliance**: Create roles that meet regulatory requirements
* **Integration**: Define roles for third-party system integration

## Rate Limits

* **Default**: 50 requests per minute
* **Daily**: 5,000 requests per day
* **Monthly**: 150,000 requests per month

## Notes

* **Admin Only**: This endpoint requires admin privileges
* **Required Fields**: name, displayName, and description are required
* **Permission Structure**: Permissions are objects with section and level properties
* **System Roles**: Custom roles are never system roles
* **Flat Response**: Response is not nested under data object
* **Creator Info**: Shows who created the role
* **User Count**: Starts at 0 for new roles
* Role names must be unique within the system
* The role is immediately available for user assignment


## OpenAPI

````yaml POST /roles
openapi: 3.0.3
info:
  title: SecureAI External API
  description: >
    SecureAI External API provides AI chat completion and image generation
    capabilities with knowledge base retrieval, 

    security policies, and comprehensive usage tracking. This API is designed
    for external developers 

    and integrations using API key authentication.


    ## Key Features

    - **RAG (Retrieval-Augmented Generation)**: Automatically search knowledge
    bases for relevant context

    - **Multi-Model Support**: OpenAI, Anthropic, Google, Meta, and other AI
    models

    - **Model Redundancy & Failover**: Caller-defined failover chains (primary +
    fallbacks) with per-attempt timeouts

    - **OpenAI-Compatible Endpoint**: Point any OpenAI SDK at `/api/external/v1`
    — no code changes

    - **Image Generation**: Generate and edit images using Google Gemini 2.5
    Flash Image

    - **Speech-to-Speech (S2S)**: Real-time voice conversations using OpenAI
    Realtime API with WebRTC

    - **Security Policies**: SMLTP policy enforcement, per-call Prompt Shield,
    and signed compliance receipts

    - **Usage Tracking**: Comprehensive usage monitoring, self-service quota,
    and rate limiting

    - **Knowledge Base Integration**: Access to personal and shared knowledge
    bases

    - **User Management**: Complete user, group, and role management
    capabilities

    - **Audit Logging**: Comprehensive activity and security audit logs


    ## Authentication

    All endpoints (except health check) require API key authentication using
    Bearer token:

    ```

    Authorization: Bearer sk-your-api-key-here

    ```


    ## Billing and Usage

    By default, API requests are billed to the user account that owns the API
    key. You can specify 

    a different user to bill by including the `user_id` parameter in your
    request. This allows for:

    - Multi-tenant applications with per-user billing

    - Flexible completion limit management

    - Per-user "Usage by Model" settings


    ## Rate Limits

    - Default: 60 requests per minute, 1000 requests per hour

    - Daily limits: 100 requests (configurable)

    - Monthly limits: 10,000 requests (configurable)


    ## Base URL

    ```

    https://secureai.hiperai.ai/api/external

    ```
  version: 1.1.0
  contact:
    name: SecureAI Support
    email: support@secureai.hiperai.ai
  license:
    name: Proprietary
    url: https://secureai.hiperai.ai/terms
servers:
  - url: https://secureai.hiperai.ai/api/external
    description: Production server
  - url: http://localhost:3010/api/external
    description: Development server
security:
  - ApiKeyAuth: []
tags:
  - name: System
    description: System health and status endpoints
  - name: Discovery
    description: Endpoints to discover available models, indexes, and policies
  - name: Chat
    description: AI chat completion endpoints
  - name: User Management
    description: Endpoints for managing user accounts and roles
  - name: Index Management
    description: Endpoints for managing knowledge base indexes
  - name: Group Management
    description: Endpoints for managing user groups
  - name: SMLTP Security
    description: Endpoints for managing SMLTP security policies and audit logs
  - name: Role Management
    description: Endpoints for managing user roles
  - name: Activity Logs
    description: Endpoints for retrieving activity logs
externalDocs:
  description: SecureAI Documentation
  url: https://secureai.hiperai.ai/docs
paths:
  /roles:
    post:
      tags:
        - Role Management
      summary: Create New Role
      description: |
        Create a new custom role. Only accessible by administrators.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required:
                - name
                - displayName
                - description
              properties:
                name:
                  type: string
                  description: Role name (lowercase, no spaces)
                  example: custom_role
                displayName:
                  type: string
                  description: Display name for the role
                  example: Custom Role
                description:
                  type: string
                  description: Role description
                  example: Custom role with specific permissions
                hasAdminPanelAccess:
                  type: boolean
                  default: false
                  description: Whether role has admin panel access
                  example: true
                permissions:
                  type: array
                  items:
                    type: object
                    properties:
                      section:
                        type: string
                        enum:
                          - home
                          - user-management
                          - index-management
                          - analytics
                          - group-management
                          - integrations
                          - services-status
                          - settings
                          - announcements
                          - smltp-security
                        example: user-management
                      level:
                        type: string
                        enum:
                          - none
                          - reader
                          - admin
                        example: admin
                  description: Array of permission objects
                  example:
                    - section: user-management
                      level: admin
                    - section: index-management
                      level: reader
                canInteractWithAI:
                  type: boolean
                  default: true
                  description: Whether role can interact with AI
                  example: true
                canUseChat:
                  type: boolean
                  default: true
                  description: Whether role can use chat
                  example: true
            example:
              name: custom_role
              displayName: Custom Role
              description: Custom role with specific permissions
              hasAdminPanelAccess: true
              permissions:
                - section: user-management
                  level: admin
                - section: index-management
                  level: reader
              canInteractWithAI: true
              canUseChat: true
      responses:
        '201':
          description: Role created successfully
          content:
            application/json:
              schema:
                type: object
                properties:
                  success:
                    type: boolean
                    example: true
                  message:
                    type: string
                    example: Role created successfully
                  role:
                    type: object
                    properties:
                      id:
                        type: string
                        example: 60a7c8f5e8b4f5001f7a8c26
                      name:
                        type: string
                        example: custom_role
                      displayName:
                        type: string
                        example: Custom Role
                      description:
                        type: string
                        example: Custom role with specific permissions
                      isSystem:
                        type: boolean
                        example: false
                      hasAdminPanelAccess:
                        type: boolean
                        example: true
                      permissions:
                        type: array
                        items:
                          type: object
                          properties:
                            section:
                              type: string
                              example: user-management
                            level:
                              type: string
                              example: admin
                      canInteractWithAI:
                        type: boolean
                        example: true
                      canUseChat:
                        type: boolean
                        example: true
                      userCount:
                        type: integer
                        example: 0
                      createdBy:
                        type: object
                        properties:
                          id:
                            type: string
                            example: 60a7c8f5e8b4f5001f7a8c24
                          name:
                            type: string
                            example: John Doe
                          email:
                            type: string
                            example: john@example.com
                      createdAt:
                        type: string
                        format: date-time
                        example: '2024-01-15T10:30:00.000Z'
        '400':
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '401':
          description: Invalid API key
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '403':
          description: Access denied - admin only
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
        '409':
          description: Role name already exists
          content:
            application/json:
              schema:
                $ref: '#/components/schemas/ErrorResponse'
      security:
        - ApiKeyAuth: []
components:
  schemas:
    ErrorResponse:
      type: object
      properties:
        success:
          type: boolean
          example: false
        error:
          type: string
          example: Invalid API key
        message:
          type: string
          example: The provided API key is invalid or has been revoked
        request_id:
          type: string
          example: req-abc123
          description: Request ID for tracking (if available)
  securitySchemes:
    ApiKeyAuth:
      type: http
      scheme: bearer
      description: |
        API key authentication using Bearer token format.
        Example: `Authorization: Bearer sk-your-api-key-here`

````