Execute Rule
curl --request POST \
--url http://api.gu1.ai/rules/{ruleId}/execute \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"entityId": "<string>",
"testMode": true,
"includeDebug": true
}
'import requests
url = "http://api.gu1.ai/rules/{ruleId}/execute"
payload = {
"entityId": "<string>",
"testMode": True,
"includeDebug": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({entityId: '<string>', testMode: true, includeDebug: true})
};
fetch('http://api.gu1.ai/rules/{ruleId}/execute', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/rules/{ruleId}/execute",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'entityId' => '<string>',
'testMode' => true,
'includeDebug' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/rules/{ruleId}/execute"
payload := strings.NewReader("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("http://api.gu1.ai/rules/{ruleId}/execute")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/rules/{ruleId}/execute")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}"
response = http.request(request)
puts response.read_body{
"matched": true,
"score": 123,
"executionTime": 123,
"conditions": {},
"actions": [
{}
],
"debug": {}
}API Reference
Execute Rule
Execute a rule against a specific entity for testing and validation β in the gu1 rules engine for compliance and risk detection, with examples for execute use.
POST
/
rules
/
{ruleId}
/
execute
Execute Rule
curl --request POST \
--url http://api.gu1.ai/rules/{ruleId}/execute \
--header 'Authorization: Bearer <token>' \
--header 'Content-Type: application/json' \
--data '
{
"entityId": "<string>",
"testMode": true,
"includeDebug": true
}
'import requests
url = "http://api.gu1.ai/rules/{ruleId}/execute"
payload = {
"entityId": "<string>",
"testMode": True,
"includeDebug": True
}
headers = {
"Authorization": "Bearer <token>",
"Content-Type": "application/json"
}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {Authorization: 'Bearer <token>', 'Content-Type': 'application/json'},
body: JSON.stringify({entityId: '<string>', testMode: true, includeDebug: true})
};
fetch('http://api.gu1.ai/rules/{ruleId}/execute', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "http://api.gu1.ai/rules/{ruleId}/execute",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'entityId' => '<string>',
'testMode' => true,
'includeDebug' => true
]),
CURLOPT_HTTPHEADER => [
"Authorization: Bearer <token>",
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "http://api.gu1.ai/rules/{ruleId}/execute"
payload := strings.NewReader("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("http://api.gu1.ai/rules/{ruleId}/execute")
.header("Authorization", "Bearer <token>")
.header("Content-Type", "application/json")
.body("{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}")
.asString();require 'uri'
require 'net/http'
url = URI("http://api.gu1.ai/rules/{ruleId}/execute")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["Authorization"] = 'Bearer <token>'
request["Content-Type"] = 'application/json'
request.body = "{\n \"entityId\": \"<string>\",\n \"testMode\": true,\n \"includeDebug\": true\n}"
response = http.request(request)
puts response.read_body{
"matched": true,
"score": 123,
"executionTime": 123,
"conditions": {},
"actions": [
{}
],
"debug": {}
}Overview
Executes a specific rule against an entity to test rule logic, validate conditions, and preview results before deploying to production. Useful for testing rules in shadow mode or debugging rule behavior.Endpoint
POST http://api.gu1.ai/rules/{ruleId}/execute
Authentication
Requires a valid API key in the Authorization header:Authorization: Bearer YOUR_API_KEY
Path Parameters
string
required
UUID of the rule to execute
Request Body
string
required
UUID of the entity to evaluate against the rule
boolean
default:"false"
If true, executes in test mode without creating alerts or modifying entities
boolean
default:"false"
If true, includes detailed debug information about condition evaluation
Response
boolean
Whether the rule conditions matched
number
Risk score assigned by the rule (if matched)
number
Execution time in milliseconds
object
Detailed evaluation results for each condition
array
Actions that would be executed (or were executed if not in test mode)
object
Debug information (if includeDebug=true)
Example Requests
Execute Rule in Test Mode
curl -X POST http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"entityId": "550e8400-e29b-41d4-a716-446655440000",
"testMode": true,
"includeDebug": true
}'
const response = await fetch(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entityId: '550e8400-e29b-41d4-a716-446655440000',
testMode: true,
includeDebug: true
})
}
);
const result = await response.json();
console.log('Rule matched:', result.matched);
console.log('Score:', result.score);
console.log('Execution time:', result.executionTime + 'ms');
import requests
response = requests.post(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entityId': '550e8400-e29b-41d4-a716-446655440000',
'testMode': True,
'includeDebug': True
}
)
result = response.json()
print(f"Rule matched: {result['matched']}")
print(f"Score: {result['score']}")
print(f"Execution time: {result['executionTime']}ms")
Execute Rule in Production Mode
curl -X POST http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"entityId": "550e8400-e29b-41d4-a716-446655440000",
"testMode": false
}'
const response = await fetch(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entityId: '550e8400-e29b-41d4-a716-446655440000',
testMode: false
})
}
);
const result = await response.json();
if (result.matched) {
console.log('Rule matched! Actions executed:', result.actions.length);
}
import requests
response = requests.post(
'http://api.gu1.ai/rules/e2cdd639-52cc-4749-9b16-927bfa5dfaea/execute',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entityId': '550e8400-e29b-41d4-a716-446655440000',
'testMode': False
}
)
result = response.json()
if result['matched']:
print(f"Rule matched! Actions executed: {len(result['actions'])}")
Response Examples
Successful Match with Debug Info
{
"matched": true,
"score": 85,
"executionTime": 45,
"conditions": {
"operator": "AND",
"result": true,
"conditions": [
{
"id": "cond-1",
"field": "enrichmentData.normalized.taxId",
"operator": "eq",
"expectedValue": "33.592.510/0001-54",
"actualValue": "33.592.510/0001-54",
"result": true
}
]
},
"actions": [
{
"type": "createAlert",
"status": "would_execute",
"details": {
"type": "COMPLIANCE",
"title": "Blocklisted Company Detected",
"severity": "CRITICAL"
}
},
{
"type": "updateEntityStatus",
"status": "would_execute",
"details": {
"status": "blocked",
"reason": "CNPJ in blocklist"
}
}
],
"debug": {
"entitySnapshot": {
"id": "550e8400-e29b-41d4-a716-446655440000",
"type": "company",
"taxId": "33.592.510/0001-54",
"name": "Test Company"
},
"conditionEvaluationOrder": ["cond-1"],
"shortCircuited": false,
"cacheHits": 0
}
}
No Match
{
"matched": false,
"score": 0,
"executionTime": 23,
"conditions": {
"operator": "AND",
"result": false,
"conditions": [
{
"id": "cond-1",
"field": "enrichmentData.normalized.taxId",
"operator": "eq",
"expectedValue": "33.592.510/0001-54",
"actualValue": "12.345.678/0001-90",
"result": false
}
]
},
"actions": [],
"debug": null
}
Production Mode - Actions Executed
{
"matched": true,
"score": 85,
"executionTime": 156,
"conditions": {
"operator": "AND",
"result": true,
"conditions": [...]
},
"actions": [
{
"type": "createAlert",
"status": "executed",
"alertId": "alert-uuid-123",
"details": {
"type": "COMPLIANCE",
"title": "Blocklisted Company Detected",
"severity": "CRITICAL"
}
},
{
"type": "updateEntityStatus",
"status": "executed",
"details": {
"previousStatus": "active",
"newStatus": "blocked",
"reason": "CNPJ in blocklist"
}
}
]
}
Error Responses
404 Not Found - Rule
{
"error": "Rule not found",
"ruleId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}
404 Not Found - Entity
{
"error": "Entity not found",
"entityId": "550e8400-e29b-41d4-a716-446655440000"
}
400 Bad Request - Type Mismatch
{
"error": "Entity type mismatch",
"details": {
"ruleTargetTypes": ["company"],
"entityType": "person",
"message": "This rule only applies to company entities"
}
}
400 Bad Request - Disabled Rule
{
"error": "Rule is disabled",
"ruleId": "e2cdd639-52cc-4749-9b16-927bfa5dfaea"
}
Use Cases
Testing New Rules
// Test a new rule against sample entities before enabling
async function testRuleAgainstSamples(ruleId, sampleEntityIds) {
const results = [];
for (const entityId of sampleEntityIds) {
const response = await fetch(
`http://api.gu1.ai/rules/${ruleId}/execute`,
{
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entityId,
testMode: true,
includeDebug: true
})
}
);
const result = await response.json();
results.push({
entityId,
matched: result.matched,
executionTime: result.executionTime
});
}
console.log('Test Results:', results);
console.log('Match rate:',
results.filter(r => r.matched).length / results.length * 100 + '%'
);
return results;
}
Debugging Rule Behavior
def debug_rule_execution(rule_id, entity_id):
"""Get detailed debug information for rule execution"""
response = requests.post(
f'http://api.gu1.ai/rules/{rule_id}/execute',
headers={
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
json={
'entityId': entity_id,
'testMode': True,
'includeDebug': True
}
)
result = response.json()
print(f"Rule Matched: {result['matched']}")
print(f"Execution Time: {result['executionTime']}ms")
print("\nCondition Evaluation:")
for condition in result['conditions']['conditions']:
print(f" - {condition['field']}: ", end='')
print(f"{condition['actualValue']} {condition['operator']} {condition['expectedValue']}")
print(f" Result: {'β
Pass' if condition['result'] else 'β Fail'}")
if result.get('debug'):
print("\nDebug Info:")
print(f" Short-circuited: {result['debug']['shortCircuited']}")
print(f" Cache hits: {result['debug']['cacheHits']}")
return result
Batch Testing
// Test multiple entities against a rule
async function batchTestRule(ruleId, entityIds) {
const batchSize = 10;
const results = {
total: entityIds.length,
matched: 0,
failed: 0,
avgExecutionTime: 0
};
for (let i = 0; i < entityIds.length; i += batchSize) {
const batch = entityIds.slice(i, i + batchSize);
const promises = batch.map(entityId =>
fetch(`http://api.gu1.ai/rules/${ruleId}/execute`, {
method: 'POST',
headers: {
'Authorization': 'Bearer YOUR_API_KEY',
'Content-Type': 'application/json'
},
body: JSON.stringify({
entityId,
testMode: true
})
}).then(r => r.json())
);
const batchResults = await Promise.all(promises);
batchResults.forEach(result => {
if (result.matched) results.matched++;
results.avgExecutionTime += result.executionTime;
});
}
results.avgExecutionTime = Math.round(
results.avgExecutionTime / entityIds.length
);
console.log('Batch Test Results:', results);
return results;
}
Best Practices
- Always Test First: Use
testMode: truebefore running rules in production - Enable Debug for Development: Use
includeDebug: trueto understand rule behavior - Test Edge Cases: Test with entities that should and shouldnβt match
- Monitor Execution Time: Optimize rules that take longer than 200ms
- Validate Actions: Review action details before enabling production mode
- Use Shadow Mode: Deploy rules with
status: "shadow"to log matches without executing actions
Performance Notes
- Average execution time: 50-150ms
- Sync rules block the request, async rules return immediately
- Complex nested conditions may increase execution time
- Array field evaluations with filters add ~10-30ms per array
See Also
- Create Rule - Create new rules
- Condition Fields Reference - Available condition fields
- List Rules - Query rules
- Update Rule - Modify existing rules
Was this page helpful?