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

# List Rules

> Query and filter rules with pagination — in the gu1 rules engine for compliance and risk detection, with examples for list use cases.

## Overview

Retrieves a paginated list of rules with support for filtering by status, category, entity type, tags, and search. Useful for displaying rule libraries, dashboards, and management interfaces.

## Endpoint

```
GET http://api.gu1.ai/rules
```

## Authentication

Requires a valid API key in the Authorization header:

```bash theme={null}
Authorization: Bearer YOUR_API_KEY
```

## Query Parameters

<ParamField query="page" type="number" default="1">
  Page number for pagination
</ParamField>

<ParamField query="pageSize" type="number" default="20">
  Number of rules per page (max: 100)
</ParamField>

<ParamField query="status" type="string">
  Filter by status: `draft`, `active`, `shadow`, `archived`, `inactive`
</ParamField>

<ParamField query="category" type="string">
  Filter by category: `kyc`, `kyb`, `aml`, `fraud`, `compliance`, `custom`
</ParamField>

<ParamField query="enabled" type="boolean">
  Filter by enabled status: `true` or `false`
</ParamField>

<ParamField query="targetEntityType" type="string">
  Filter by entity type: `person`, `company`, `transaction`
</ParamField>

<ParamField query="riskMatrixId" type="string">
  Filter by risk matrix UUID
</ParamField>

<ParamField query="tags" type="string">
  Filter by tags (comma-separated): `high-risk,pep,sanctions`
</ParamField>

<ParamField query="search" type="string">
  Search in rule name and description
</ParamField>

<ParamField query="sortBy" type="string" default="updatedAt">
  Sort field: `name`, `priority`, `createdAt`, `updatedAt`, `score`
</ParamField>

<ParamField query="sortOrder" type="string" default="desc">
  Sort order: `asc` or `desc`
</ParamField>

## Response

<ResponseField name="rules" type="array">
  Array of rule objects
</ResponseField>

<ResponseField name="total" type="string">
  Total number of rules matching filters
</ResponseField>

<ResponseField name="page" type="number">
  Current page number
</ResponseField>

<ResponseField name="pageSize" type="number">
  Number of items per page
</ResponseField>

<ResponseField name="totalPages" type="number">
  Total number of pages
</ResponseField>

## Example Requests

### List All Active Rules

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/rules?status=active&enabled=true" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules?status=active&enabled=true',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(`Found ${data.total} active rules`);
  console.log('Rules:', data.rules.map(r => r.name));
  ```

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

  response = requests.get(
      'http://api.gu1.ai/rules',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY'
      },
      params={
          'status': 'active',
          'enabled': True
      }
  )

  data = response.json()
  print(f"Found {data['total']} active rules")
  for rule in data['rules']:
      print(f"  - {rule['name']}")
  ```
</CodeGroup>

### Search Rules

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/rules?search=sanctions&category=aml" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules?search=sanctions&category=aml',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(`Found ${data.total} rules matching "sanctions"`);
  ```

  ```python Python theme={null}
  response = requests.get(
      'http://api.gu1.ai/rules',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY'
      },
      params={
          'search': 'sanctions',
          'category': 'aml'
      }
  )

  data = response.json()
  print(f"Found {data['total']} rules matching 'sanctions'")
  ```
</CodeGroup>

### Filter by Entity Type and Risk Matrix

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/rules?targetEntityType=company&riskMatrixId=d257247b-af7b-402a-ad8f-eac209e2990e&pageSize=50" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules?' + new URLSearchParams({
      targetEntityType: 'company',
      riskMatrixId: 'd257247b-af7b-402a-ad8f-eac209e2990e',
      pageSize: 50
    }),
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(`Found ${data.total} company rules in this matrix`);
  ```

  ```python Python theme={null}
  response = requests.get(
      'http://api.gu1.ai/rules',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY'
      },
      params={
          'targetEntityType': 'company',
          'riskMatrixId': 'd257247b-af7b-402a-ad8f-eac209e2990e',
          'pageSize': 50
      }
  )

  data = response.json()
  print(f"Found {data['total']} company rules in this matrix")
  ```
</CodeGroup>

### Sort by Priority

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/rules?sortBy=priority&sortOrder=desc&status=active" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules?sortBy=priority&sortOrder=desc&status=active',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log('Rules sorted by priority:');
  data.rules.forEach(rule => {
    console.log(`  [${rule.priority}] ${rule.name}`);
  });
  ```

  ```python Python theme={null}
  response = requests.get(
      'http://api.gu1.ai/rules',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY'
      },
      params={
          'sortBy': 'priority',
          'sortOrder': 'desc',
          'status': 'active'
      }
  )

  data = response.json()
  print('Rules sorted by priority:')
  for rule in data['rules']:
      print(f"  [{rule['priority']}] {rule['name']}")
  ```
</CodeGroup>

### Filter by Tags

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "http://api.gu1.ai/rules?tags=high-risk,pep" \
    -H "Authorization: Bearer YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/rules?tags=high-risk,pep',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();
  console.log(`Found ${data.total} rules tagged with high-risk OR pep`);
  ```

  ```python Python theme={null}
  response = requests.get(
      'http://api.gu1.ai/rules',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY'
      },
      params={
          'tags': 'high-risk,pep'
      }
  )

  data = response.json()
  print(f"Found {data['total']} rules tagged with high-risk OR pep")
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
  "rules": [
    {
      "id": "e2cdd639-52cc-4749-9b16-927bfa5dfaea",
      "organizationId": "71e8f908-e032-4fcb-b0ce-ad0cd0ffb236",
      "name": "CNPJ Blocklist Check",
      "description": "Block companies with specific CNPJ",
      "category": "kyb",
      "status": "active",
      "enabled": true,
      "priority": 100,
      "score": 85,
      "targetEntityTypes": ["company"],
      "evaluationMode": "sync",
      "riskMatrixId": "d257247b-af7b-402a-ad8f-eac209e2990e",
      "version": 1,
      "tags": [],
      "createdBy": "f35c10cb-9b67-4cda-9aea-f36567375dba",
      "createdAt": "2024-12-22T14:10:28.131Z",
      "updatedAt": "2024-12-22T14:44:29.627Z",
      "stats": {
        "failures": 0,
        "successes": 7,
        "executions": 7
      }
    },
    {
      "id": "a5a29ed9-1e98-4a57-8e89-3aa819d5da0a",
      "organizationId": "71e8f908-e032-4fcb-b0ce-ad0cd0ffb236",
      "name": "Terrorism Sanctions Check",
      "description": "Detect entities with terrorism-related sanctions",
      "category": "aml",
      "status": "active",
      "enabled": true,
      "priority": 100,
      "score": 95,
      "targetEntityTypes": ["person", "company"],
      "evaluationMode": "sync",
      "riskMatrixId": "b6d543cb-1006-4bbb-8777-c43859d51c8a",
      "version": 1,
      "tags": ["sanctions", "terrorism", "critical"],
      "createdBy": "f35c10cb-9b67-4cda-9aea-f36567375dba",
      "createdAt": "2024-12-21T17:09:00.746Z",
      "updatedAt": "2024-12-22T14:41:32.821Z",
      "stats": {
        "failures": 12,
        "successes": 7,
        "executions": 19
      }
    }
  ],
  "total": "2",
  "page": 1,
  "pageSize": 20,
  "totalPages": 1
}
```

## Pagination Example

```javascript theme={null}
async function getAllRules() {
  const allRules = [];
  let page = 1;
  const pageSize = 100;
  let hasMore = true;

  while (hasMore) {
    const response = await fetch(
      `http://api.gu1.ai/rules?page=${page}&pageSize=${pageSize}`,
      {
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY'
        }
      }
    );

    const data = await response.json();
    allRules.push(...data.rules);

    hasMore = page < data.totalPages;
    page++;
  }

  return allRules;
}

// Usage
const rules = await getAllRules();
console.log(`Fetched ${rules.length} total rules`);
```

## Use Cases

### Build Rule Dashboard

```javascript theme={null}
async function buildRuleDashboard() {
  // Get active rules grouped by category
  const categories = ['kyc', 'kyb', 'aml', 'fraud', 'compliance'];
  const dashboard = {};

  for (const category of categories) {
    const response = await fetch(
      `http://api.gu1.ai/rules?category=${category}&status=active`,
      {
        headers: {
          'Authorization': 'Bearer YOUR_API_KEY'
        }
      }
    );

    const data = await response.json();
    dashboard[category] = {
      total: parseInt(data.total),
      rules: data.rules.map(r => ({
        id: r.id,
        name: r.name,
        enabled: r.enabled,
        priority: r.priority,
        score: r.score,
        executions: r.stats.executions,
        successRate: (r.stats.successes / r.stats.executions * 100).toFixed(1) + '%'
      }))
    };
  }

  return dashboard;
}
```

### Monitor High-Priority Rules

```python theme={null}
def monitor_high_priority_rules():
    """Monitor rules with priority >= 90"""
    response = requests.get(
        'http://api.gu1.ai/rules',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY'
        },
        params={
            'sortBy': 'priority',
            'sortOrder': 'desc',
            'pageSize': 100
        }
    )

    data = response.json()
    high_priority = [r for r in data['rules'] if r['priority'] >= 90]

    print(f"Found {len(high_priority)} high-priority rules:\n")

    for rule in high_priority:
        status_icon = '✅' if rule['enabled'] else '❌'
        print(f"{status_icon} [{rule['priority']}] {rule['name']}")
        print(f"   Category: {rule['category']}")
        print(f"   Executions: {rule['stats']['executions']}")
        print(f"   Success Rate: {rule['stats']['successes'] / max(rule['stats']['executions'], 1) * 100:.1f}%")
        print()

    return high_priority
```

### Find Rules by Risk Matrix

```javascript theme={null}
async function getRulesByMatrix(riskMatrixId) {
  const response = await fetch(
    `http://api.gu1.ai/rules?riskMatrixId=${riskMatrixId}&pageSize=100`,
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();

  return {
    matrixId: riskMatrixId,
    totalRules: parseInt(data.total),
    active: data.rules.filter(r => r.enabled).length,
    inactive: data.rules.filter(r => !r.enabled).length,
    byCategory: data.rules.reduce((acc, rule) => {
      acc[rule.category] = (acc[rule.category] || 0) + 1;
      return acc;
    }, {}),
    rules: data.rules
  };
}
```

### Search and Filter

```python theme={null}
def search_rules(search_term, filters=None):
    """Advanced rule search with multiple filters"""
    params = {
        'search': search_term,
        'pageSize': 50
    }

    if filters:
        params.update(filters)

    response = requests.get(
        'http://api.gu1.ai/rules',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY'
        },
        params=params
    )

    data = response.json()

    print(f"Search: '{search_term}'")
    if filters:
        print(f"Filters: {filters}")
    print(f"Results: {data['total']} rules found\n")

    for rule in data['rules']:
        print(f"- {rule['name']}")
        print(f"  Category: {rule['category']} | Status: {rule['status']}")
        print(f"  Score: {rule['score']} | Priority: {rule['priority']}")
        print()

    return data['rules']

# Example usage
search_rules('pep', {
    'category': 'aml',
    'status': 'active',
    'enabled': True
})
```

### Export Rules for Backup

```javascript theme={null}
async function exportAllRules() {
  const response = await fetch(
    'http://api.gu1.ai/rules?pageSize=100',
    {
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY'
      }
    }
  );

  const data = await response.json();

  // Create backup object
  const backup = {
    exportDate: new Date().toISOString(),
    totalRules: parseInt(data.total),
    rules: data.rules.map(rule => ({
      name: rule.name,
      description: rule.description,
      category: rule.category,
      targetEntityTypes: rule.targetEntityTypes,
      conditions: rule.conditions,
      actions: rule.actions,
      priority: rule.priority,
      score: rule.score,
      evaluationMode: rule.evaluationMode,
      scope: rule.scope,
      tags: rule.tags
    }))
  };

  // Save to file (Node.js)
  const fs = require('fs');
  fs.writeFileSync(
    `rules-backup-${Date.now()}.json`,
    JSON.stringify(backup, null, 2)
  );

  console.log(`✅ Exported ${backup.totalRules} rules`);

  return backup;
}
```

## Best Practices

1. **Use Pagination**: Always paginate when fetching large rule sets
2. **Filter Efficiently**: Combine filters to narrow results (category + status + enabled)
3. **Cache Results**: Cache frequently accessed rule lists
4. **Sort Strategically**: Sort by priority for execution order, by updatedAt for recent changes
5. **Monitor Performance**: Track rules with high failure rates using stats
6. **Use Tags**: Leverage tags for custom organization and filtering

## Performance Notes

* Default page size: 20 rules
* Maximum page size: 100 rules
* Average response time: 50-150ms
* Search indexes: name, description
* Filter indexes: status, category, enabled, targetEntityType, riskMatrixId

## See Also

* [Get Rule](/en/api-reference/rules/get) - Retrieve specific rule details
* [Create Rule](/en/api-reference/rules/create) - Create new rules
* [Update Rule](/en/api-reference/rules/update) - Modify existing rules
* [Execute Rule](/en/api-reference/rules/execute) - Test rule execution
