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

# Execute Enrichment

> Execute data enrichment integrations on entities (companies or persons) — using the gu1 risk scoring engine with configurable triggers.

## Overview

Execute one or more marketplace enrichment integrations to enhance entity data with information from external providers. Enrichments add additional fields to the entity without performing risk assessment.

This endpoint supports batch execution of multiple enrichments in a single request, optimizing cost and performance.

## Endpoint

```
POST http://api.gu1.ai/integration-execution/marketplace/enrichment
```

## Authentication

Requires a valid API key in the Authorization header:

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

## Request Body

<ParamField body="entityId" type="string" required>
  UUID of the entity (company or person) to enrich
</ParamField>

<ParamField body="integrationCodes" type="array<string>" required>
  Array of enrichment integration codes to execute. See [Provider Codes Reference](/en/api-reference/integrations/provider-codes) for available codes.

  At least one integration code is required.
</ParamField>

<ParamField body="parameters" type="object">
  Optional additional parameters for the integrations (default: `{}`)
</ParamField>

## Response

<ResponseField name="success" type="boolean">
  Whether all enrichments succeeded
</ResponseField>

<ResponseField name="results" type="array<object>">
  Array of individual enrichment results. Each result contains:

  * `success` (boolean) - Whether this enrichment succeeded
  * `enrichmentId` (string) - ID for viewing enrichment details
  * `integrationCode` (string) - The integration code that was executed
  * `result` (object) - Enrichment result data:
    * `fieldsEnriched` (`array<string>`) - List of fields that were enriched
    * `dataQuality` (object) - Data quality metrics
    * `summary` (string) - Human-readable summary
    * `enrichmentData` (object) - The enriched data
  * `executionTime` (number) - Execution time in milliseconds
  * `costCents` (number) - Cost in cents
  * `error` (object, optional) - Error details if failed
</ResponseField>

<ResponseField name="totalCostCents" type="number">
  Total cost for all enrichments in cents
</ResponseField>

<ResponseField name="totalExecutionTime" type="number">
  Total execution time for all enrichments in milliseconds
</ResponseField>

<ResponseField name="rulesResult" type="object">
  Result of rules execution when the rules engine runs after enrichment (if configured). When present, includes:

  * **success** (boolean) - Whether rules executed successfully
  * **rulesTriggered** (number) - Number of rules that were triggered
  * **alerts** (array) - Alerts generated by rules
  * **riskScore** (number) - Final calculated risk score
  * **decision** (string) - Final decision (APPROVE, REJECT, HOLD, REVIEW\_REQUIRED)
  * **rulesExecutionSummary** (object) - When rules ran, detailed summary; see below.
</ResponseField>

<ResponseField name="rulesExecutionSummary" type="object">
  **At the root of the response** (same as transactions API). Same value as `rulesResult.rulesExecutionSummary`. **Only present when rules ran after enrichment.** Summary of which rules matched (hit) vs did not match (no hit), executed actions, and total score.

  * **rulesHit** (array) - Rules whose conditions were met. Each item: **name**, **description**, **score**, **priority**, **category**, **status**, **conditions**, **actions**.
  * **rulesNoHit** (array) - Rules evaluated but conditions not met. Same structure as rulesHit.
  * **actionsExecuted** (object) - Aggregated executed actions: **alerts**, **suggestion**, **status**, **assignedUser**, **customKeys** (array of strings, optional) — custom action keys from rules that matched; for integrations/workflows.
  * **totalScore** (number) - Sum of score of all rules that hit (excluding shadow).
</ResponseField>

## Examples

### Execute Single Enrichment

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/integration-execution/marketplace/enrichment \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityId": "550e8400-e29b-41d4-a716-446655440000",
      "integrationCodes": ["br_cpfcnpj_complete_person_enrichment"]
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/integration-execution/marketplace/enrichment',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityId: '550e8400-e29b-41d4-a716-446655440000',
        integrationCodes: ['br_cpfcnpj_complete_person_enrichment']
      })
    }
  );

  const data = await response.json();
  console.log(`Enriched ${data.results[0].result.fieldsEnriched.length} fields`);
  ```

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

  response = requests.post(
      'http://api.gu1.ai/integration-execution/marketplace/enrichment',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityId': '550e8400-e29b-41d4-a716-446655440000',
          'integrationCodes': ['br_cpfcnpj_complete_person_enrichment']
      }
  )

  data = response.json()
  print(f"Enriched {len(data['results'][0]['result']['fieldsEnriched'])} fields")
  ```
</CodeGroup>

### Execute Multiple Enrichments (Batch)

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST http://api.gu1.ai/integration-execution/marketplace/enrichment \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityId": "550e8400-e29b-41d4-a716-446655440000",
      "integrationCodes": [
        "br_cpfcnpj_complete_person_enrichment",
        "br_serpro_cpf_status_enrichment",
        "global_clear_sale_person_enrichment"
      ]
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/integration-execution/marketplace/enrichment',
    {
      method: 'POST',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityId: '550e8400-e29b-41d4-a716-446655440000',
        integrationCodes: [
          'br_cpfcnpj_complete_person_enrichment',
          'br_serpro_cpf_status_enrichment',
          'global_clear_sale_person_enrichment'
        ]
      })
    }
  );

  const data = await response.json();
  console.log(`Total cost: ${data.totalCostCents / 100} tokens`);
  console.log(`${data.results.filter(r => r.success).length} of ${data.results.length} succeeded`);
  ```

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

  response = requests.post(
      'http://api.gu1.ai/integration-execution/marketplace/enrichment',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityId': '550e8400-e29b-41d4-a716-446655440000',
          'integrationCodes': [
              'br_cpfcnpj_complete_person_enrichment',
              'br_serpro_cpf_status_enrichment',
              'global_clear_sale_person_enrichment'
          ]
      }
  )

  data = response.json()
  successes = sum(1 for r in data['results'] if r['success'])
  print(f"{successes} of {len(data['results'])} enrichments succeeded")
  print(f"Total cost: {data['totalCostCents'] / 100} tokens")
  ```
</CodeGroup>

## Response Example

### Successful Enrichment

```json theme={null}
{
  "success": true,
  "results": [
    {
      "success": true,
      "enrichmentId": "enrich_abc123",
      "integrationCode": "br_cpfcnpj_complete_person_enrichment",
      "result": {
        "fieldsEnriched": [
          "fullName",
          "dateOfBirth",
          "taxId",
          "address",
          "city",
          "state",
          "postalCode"
        ],
        "dataQuality": {
          "overall": 85,
          "completeness": 90,
          "confidence": 85,
          "freshness": 100,
          "consistency": 100,
          "sourceReliability": "high",
          "lastUpdated": "2024-12-24T10:30:00.000Z"
        },
        "summary": "Enriched 7 fields from CPF/CNPJ Complete Enrichment",
        "enrichmentData": {
          "fullName": "João Silva",
          "dateOfBirth": "1985-05-15",
          "taxId": "123.456.789-00",
          "address": {
            "street": "Rua Example",
            "number": "123",
            "city": "São Paulo",
            "state": "SP",
            "postalCode": "01234-567"
          }
        }
      },
      "executionTime": 342,
      "costCents": 100
    }
  ],
  "totalCostCents": 100,
  "totalExecutionTime": 342,
  "rulesResult": null
}
```

### Partial Failure (Some Enrichments Failed)

```json theme={null}
{
  "success": false,
  "results": [
    {
      "success": true,
      "enrichmentId": "enrich_abc123",
      "integrationCode": "br_cpfcnpj_complete_person_enrichment",
      "result": { ... },
      "executionTime": 342,
      "costCents": 100
    },
    {
      "success": false,
      "integrationCode": "br_serpro_cpf_status_enrichment",
      "executionTime": 150,
      "costCents": 0,
      "error": {
        "code": "PROVIDER_ERROR",
        "message": "CPF not found in Serpro database"
      }
    }
  ],
  "totalCostCents": 100,
  "totalExecutionTime": 492
}
```

## Error Responses

### 404 Not Found - Entity Not Found

```json theme={null}
{
  "success": false,
  "results": [],
  "totalCostCents": 0,
  "totalExecutionTime": 0,
  "error": {
    "code": "ENTITY_NOT_FOUND",
    "message": "Entity not found"
  }
}
```

### 400 Bad Request - Invalid Integration Code

```json theme={null}
{
  "success": false,
  "results": [],
  "totalCostCents": 0,
  "totalExecutionTime": 0,
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "At least one integration code is required"
  }
}
```

### 401 Unauthorized

```json theme={null}
{
  "success": false,
  "results": [],
  "totalCostCents": 0,
  "totalExecutionTime": 0,
  "error": {
    "code": "MISSING_ORGANIZATION",
    "message": "Organization ID is required"
  }
}
```

## Pricing

* Each enrichment has its own cost (see integration catalog)
* Failed enrichments are NOT charged
* Costs are deducted from your organization's token balance
* 1 token = 100 cents = \$1.00 USD

## Best Practices

1. **Batch Enrichments**: Execute multiple enrichments in one request to optimize performance
2. **Error Handling**: Check individual `success` fields in results array
3. **Cost Management**: Monitor `totalCostCents` to track usage
4. **Provider Selection**: Choose enrichments based on your entity's country and required fields
5. **View Details**: Use the `enrichmentId` to view complete enrichment details later

## Automatic Rules Execution

When enrichments succeed, the rules engine may automatically execute based on your risk matrix configuration. The `rulesResult` field contains the rules execution outcome.

## Use Cases

### Progressive Data Enrichment

```javascript theme={null}
// Start with basic enrichment
const basicResponse = await enrichEntity(entityId, [
  'br_cpfcnpj_basic_person_enrichment'
]);

// If more data needed, run complete enrichment
if (basicResponse.results[0].result.dataQuality.overall < 80) {
  await enrichEntity(entityId, [
    'br_cpfcnpj_complete_person_enrichment'
  ]);
}
```

### Multi-Provider Strategy

```python theme={null}
# Enrich from multiple providers for redundancy
integrations = [
    'br_cpfcnpj_complete_person_enrichment',
    'br_serpro_cpf_validation_enrichment',
    'global_clear_sale_person_enrichment'
]

response = enrich_entity(entity_id, integrations)

# Use data from the provider with best quality
best_result = max(
    response['results'],
    key=lambda r: r['result']['dataQuality']['overall'] if r['success'] else 0
)
```

## Next Steps

* [Provider Codes Reference](/en/api-reference/integrations/provider-codes) - View all available enrichment codes
* [Person Provider Codes](/en/api-reference/integrations/person-provider-codes) - Person-specific enrichments
* [Company Provider Codes](/en/api-reference/integrations/company-provider-codes) - Company-specific enrichments
* [Execute Risk Matrix](/en/api-reference/risk-matrix/execute-risk-matrix) - Run risk analysis after enrichment
