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

# Update an entity by ID

> Update attributes and data for an existing person or company in the gu1 universal entity model for KYC, KYB, and ongoing risk analysis.

## Overview

Updates an existing entity's attributes and data. When the entity has an assigned risk matrix whose triggers include **`entity_updated`**, the rules engine may run automatically after the update (respecting optional matrix `watchFields` and `skipRulesExecution`). Real-time update events and audit trails are always recorded.

## Endpoint

```
PATCH http://api.gu1.ai/entities/{id}
```

## Authentication

Requires a valid API key in the Authorization header:

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

## Path Parameters

<ParamField path="id" type="string" required>
  The gu1 ID of the entity to update
</ParamField>

## Request Body

All fields from the create schema are available except `type` (entity type cannot be changed). All fields are optional - only include the fields you want to update.

<ParamField body="name" type="string">
  Update the entity's display name
</ParamField>

<Note>
  **External ID** cannot be updated with this endpoint. Use [Change external ID](/en/api-reference/person/change-external-id) (`POST /entities/change-external-id`) with a mandatory `reason` (min. 5 characters). `PATCH` update routes ignore `externalId` in the body.
</Note>

<ParamField body="taxId" type="string">
  Update tax identification number
</ParamField>

<ParamField body="email" type="string | null">
  Update root-level contact email. Omit to leave unchanged; send `null` to clear.
</ParamField>

<ParamField body="phone" type="string | null">
  Update root-level contact phone. Omit to leave unchanged; send `null` to clear.
</ParamField>

<ParamField body="nationality" type="string | null">
  Root nationality (ISO 3166-1 alpha-2 when stored). Omit to leave unchanged; `null` clears. Updating `entityData` person/company nationality may refresh the root field when sent together.
</ParamField>

<ParamField body="countryCode" type="string">
  Update ISO 3166-1 alpha-2 country code
</ParamField>

<ParamField body="attributes" type="object">
  Update custom attributes (merges with existing top-level keys).

  Attributes are stored **verbatim** — the shape you send is the shape you get back on read.

  **Uncategorized (flat):** scalar or array values at the top level.

  ```json theme={null}
  { "phone": "+54...", "mcc": "5411" }
  ```

  **Categorized (nested):** a top-level object groups its inner keys under that category. The object key *is* the category — use identifier-safe keys (e.g. `contact`, `category_billing`) so they work in rule paths.

  ```json theme={null}
  {
    "contact": { "phone": "+54..." },
    "commercial": { "mcc": "5411" }
  }
  ```

  Rules and webhooks read the stored shape: flat keys as `attributes.phone`, nested keys as `attributes.contact.phone`.
</ParamField>

<ParamField body="entityData" type="object">
  Update type-specific data (merges with existing entityData)
</ParamField>

<ParamField body="status" type="string">
  Entity lifecycle status (`active`, `inactive`, `blocked`, `under_review`, `suspended`, `pending_verification`, `expired`, `rejected`, `deleted`).

  **Required with `reason`**: Any status change must include `reason` for audit.
</ParamField>

<ParamField body="reason" type="string">
  Reason for the update (especially important when changing status to `blocked` or `rejected`).

  **Required when**: Changing status to blocked, rejected, or suspended.

  **Best practice**: Always provide a reason for audit trail purposes, even when not required.
</ParamField>

<ParamField body="changeStatusManual" type="boolean" default="false">
  When `true`, **automatic** status updates are disabled for this entity: risk matrix rules and automation actions such as `set_entity_status` do not change `status`. Manual updates via this endpoint (or the UI) still apply.

  * Default: `false` (rules and automations may change status when configured).
  * Set to `false` explicitly to remove the lock and allow automatic status changes again.
  * Does not disable risk score calculation or other rule side effects—only **status** writes from rules/automations.

  **Required with `reason`**: if `changeStatusManual` changes (enable or disable), send `reason` in the same PATCH body for audit (same as status changes).
</ParamField>

### Risk Matrices

Assign or replace which risk matrices apply to this entity. Same semantics as [Create entity](/en/api-reference/entities/create) (`riskMatrixId` / `riskMatrixIds`).

<ParamField body="riskMatrixId" type="string | string[] | null">
  Legacy: one UUID, an array of UUIDs, or `null` to clear all assigned matrices. When `riskMatrixIds` is sent non-empty, it takes precedence over this field.
</ParamField>

<ParamField body="riskMatrixIds" type="string[]">
  Preferred for **multiple** matrices: ordered list of UUIDs belonging to your organization. Send `[]` (or `riskMatrixId: null`) to remove all assignments. Each UUID must exist in your org; otherwise the API returns `400` with code `INVALID_RISK_MATRIX`.
</ParamField>

<ParamField body="skipRulesExecution" type="boolean" default="false">
  When `true`, skips automatic risk matrix evaluation on update even if assigned matrices include the `entity_updated` trigger.
</ParamField>

<Note>
  Updating matrices **assigns** them on the entity record only; assignment alone does not run rules.

  **Rules on update:** If the entity has at least one assigned matrix with trigger `entity_updated`, and `skipRulesExecution` is not `true`, the API runs the rules engine after a successful field change. Matrices may optionally restrict this with **`watchFields`** (only run when listed paths change, e.g. `email`, `attributes.clientTypes`). The `entity.updated` webhook includes `rulesExecutionSummary` when rules ran or were skipped with a reason.

  The same body fields apply to [Update by external ID](/en/api-reference/entities/update-by-external-id) and `PATCH /entities/by-tax-id/{taxId}`.
</Note>

## Response

<ResponseField name="entity" type="object">
  The updated entity object with all current values
</ResponseField>

<ResponseField name="previousEntity" type="object">
  The entity state before the update (for audit/comparison)
</ResponseField>

<Note>
  The HTTP response body does **not** include `rulesExecutionSummary`. When rules run (or are skipped), summary details are attached to the **`entity.updated`** webhook payload.
</Note>

## Behavior

When you update an entity, the system:

1. **Records the change** in the audit trail with before/after values
2. **Runs risk matrices** when assigned matrices include `entity_updated`, `skipRulesExecution` is not `true`, and optional `watchFields` on the matrix match changed paths
3. **Emits real-time event** to notify connected clients of the update
4. **Fires `entity.updated` webhook** with `changes` and optional `rulesExecutionSummary`

## Examples

### Update Person Income

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000 \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityData": {
        "person": {
          "income": 95000,
          "occupation": "Senior Software Engineer"
        }
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityData: {
          person: {
            income: 95000,
            occupation: 'Senior Software Engineer'
          }
        }
      })
    }
  );

  const result = await response.json();
  console.log('Updated entity:', result.entity);
  console.log('Re-evaluation triggered:', result.evaluation.id);
  ```

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

  response = requests.patch(
      'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityData': {
              'person': {
                  'income': 95000,
                  'occupation': 'Senior Software Engineer'
              }
          }
      }
  )

  result = response.json()
  print(f"Updated entity: {result['entity']['name']}")
  print(f"Re-evaluation ID: {result['evaluation']['id']}")
  ```
</CodeGroup>

### Update Company Information

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/entities/660e9511-f39c-52e5-b827-557766551111 \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityData": {
        "company": {
          "employeeCount": 75,
          "revenue": 7500000
        }
      },
      "attributes": {
        "partnershipTier": "platinum",
        "monthlyVolume": 500000
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities/660e9511-f39c-52e5-b827-557766551111',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityData: {
          company: {
            employeeCount: 75,
            revenue: 7500000
          }
        },
        attributes: {
          partnershipTier: 'platinum',
          monthlyVolume: 500000
        }
      })
    }
  );

  const result = await response.json();
  console.log('Company updated:', result.entity.name);
  console.log('New revenue:', result.entity.entityData.company.revenue);
  ```

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

  response = requests.patch(
      'http://api.gu1.ai/entities/660e9511-f39c-52e5-b827-557766551111',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityData': {
              'company': {
                  'employeeCount': 75,
                  'revenue': 7500000
              }
          },
          'attributes': {
              'partnershipTier': 'platinum',
              'monthlyVolume': 500000
          }
      }
  )

  result = response.json()
  print(f"Company updated: {result['entity']['name']}")
  print(f"New revenue: ${result['entity']['entityData']['company']['revenue']:,}")
  ```
</CodeGroup>

### Update Custom Attributes Only

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000 \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "attributes": {
        "accountTier": "premium",
        "loyaltyPoints": 15000,
        "lastLoginDate": "2024-10-03T14:00:00Z"
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        attributes: {
          accountTier: 'premium',
          loyaltyPoints: 15000,
          lastLoginDate: '2024-10-03T14:00:00Z'
        }
      })
    }
  );

  const result = await response.json();
  console.log('Attributes updated:', result.entity.attributes);
  ```

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

  response = requests.patch(
      'http://api.gu1.ai/entities/550e8400-e29b-41d4-a716-446655440000',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'attributes': {
              'accountTier': 'premium',
              'loyaltyPoints': 15000,
              'lastLoginDate': '2024-10-03T14:00:00Z'
          }
      }
  )

  result = response.json()
  print(f"Attributes updated: {result['entity']['attributes']}")
  ```
</CodeGroup>

### Update Transaction Status

<CodeGroup>
  ```bash cURL theme={null}
  curl -X PATCH http://api.gu1.ai/entities/770f0622-g40d-63f6-c938-668877662222 \
    -H "Authorization: Bearer YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "entityData": {
        "transaction": {
          "status": "reviewed",
          "flagged": false
        }
      }
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch(
    'http://api.gu1.ai/entities/770f0622-g40d-63f6-c938-668877662222',
    {
      method: 'PATCH',
      headers: {
        'Authorization': 'Bearer YOUR_API_KEY',
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        entityData: {
          transaction: {
            status: 'reviewed',
            flagged: false
          }
        }
      })
    }
  );

  const result = await response.json();
  console.log('Transaction status updated');
  ```

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

  response = requests.patch(
      'http://api.gu1.ai/entities/770f0622-g40d-63f6-c938-668877662222',
      headers={
          'Authorization': 'Bearer YOUR_API_KEY',
          'Content-Type': 'application/json'
      },
      json={
          'entityData': {
              'transaction': {
                  'status': 'reviewed',
                  'flagged': False
              }
          }
      }
  )

  result = response.json()
  print("Transaction status updated")
  ```
</CodeGroup>

## Response Example

```json theme={null}
{
  "entity": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "externalId": "customer_12345",
    "organizationId": "8e2f89ab-c216-4eb4-90eb-ca5d44499aaa",
    "type": "person",
    "name": "María González",
    "taxId": "20-12345678-9",
    "countryCode": "AR",
    "riskScore": 22,
    "riskFactors": [...],
    "status": "active",
    "kycVerified": true,
    "entityData": {
      "person": {
        "firstName": "María",
        "lastName": "González",
        "dateOfBirth": "1985-03-15",
        "nationality": "AR",
        "occupation": "Senior Software Engineer",
        "income": 95000
      }
    },
    "attributes": {
      "email": "maria.gonzalez@example.com",
      "phone": "+54 11 1234-5678",
      "accountTier": "premium"
    },
    "createdAt": "2024-10-03T14:30:00.000Z",
    "updatedAt": "2024-10-03T16:45:00.000Z",
    "deletedAt": null
  },
  "evaluation": {
    "id": "eval_new_123",
    "entityId": "550e8400-e29b-41d4-a716-446655440000",
    "decision": "PENDING",
    "evaluationType": "SYSTEM",
    "reasons": ["Re-evaluation triggered by attribute change"],
    "rules": [],
    "entitySnapshot": {...}
  },
  "previousEntity": {
    "id": "550e8400-e29b-41d4-a716-446655440000",
    "entityData": {
      "person": {
        "occupation": "Software Engineer",
        "income": 85000
      }
    },
    "updatedAt": "2024-10-03T14:35:00.000Z"
  }
}
```

## Error Responses

### 404 Not Found

```json theme={null}
{
  "error": "Entity not found"
}
```

### 400 Bad Request - Invalid Data

```json theme={null}
{
  "error": "Validation failed",
  "details": ["Invalid country code format"]
}
```

### 401 Unauthorized

```json theme={null}
{
  "error": "Invalid or missing API key"
}
```

### 500 Internal Server Error

```json theme={null}
{
  "error": "Failed to update entity"
}
```

## Use Cases

### Update After KYC Verification

```javascript theme={null}
// After completing KYC verification, update the entity
const response = await fetch(`http://api.gu1.ai/entities/${entityId}`, {
  method: 'PATCH',
  headers: {
    'Authorization': 'Bearer YOUR_API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    attributes: {
      kycVerified: true,
      kycVerificationDate: new Date().toISOString(),
      kycProvider: 'manual_review'
    }
  })
});
```

### Progressive Profile Enrichment

```python theme={null}
# Enrich customer profile as more information becomes available
def update_customer_info(entity_id, new_data):
    response = requests.patch(
        f'http://api.gu1.ai/entities/{entity_id}',
        headers={
            'Authorization': 'Bearer YOUR_API_KEY',
            'Content-Type': 'application/json'
        },
        json={
            'entityData': {
                'person': new_data
            },
            'attributes': {
                'lastDataUpdate': datetime.now().isoformat(),
                'dataCompleteness': calculate_completeness(new_data)
            }
        }
    )
    return response.json()
```

### Transaction Resolution

```javascript theme={null}
// Mark a flagged transaction as resolved after investigation
async function resolveTransaction(txnId, resolution) {
  const response = await fetch(`http://api.gu1.ai/entities/${txnId}`, {
    method: 'PATCH',
    headers: {
      'Authorization': 'Bearer YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      entityData: {
        transaction: {
          status: 'resolved',
          flagged: false
        }
      },
      attributes: {
        resolutionDate: new Date().toISOString(),
        resolutionNotes: resolution,
        reviewedBy: 'compliance_team'
      }
    })
  });

  return response.json();
}
```

## Best Practices

1. **Partial Updates**: Only send the fields you want to change - no need to send the entire entity
2. **Monitor Re-evaluations**: Check the returned evaluation ID to track risk score recalculation
3. **Audit Trail**: Use the `previousEntity` in the response to maintain change history
4. **Real-time Sync**: Updates emit WebSocket events for real-time UI synchronization
5. **Idempotency**: Safe to retry - updates with same data will not create duplicate events

## Next Steps

* [Get Entity](/api-reference/entities/get) - View updated entity details
* [List Entities](/api-reference/entities/list) - Query entities with filters
* [Upsert Entity](/api-reference/entities/upsert) - Create or update in one operation
* [Request AI Analysis](/en/api-reference/entities/analyze) - Get updated risk assessment
