Open MercatoDocsSearch docsAPI reference

REST API

Business Rules API

Use the rules API when another application needs to configure a decision or evaluate records against it. The examples distinguish rule definitions, rule sets, execution and logs.

Base URL

/api/business_rules

Authentication

All Business Rules API endpoints require authentication. Include your API key or session token in the request headers.

curl -X GET "$BASE_URL/api/business_rules/rules" \
  -H "Authorization: Bearer <access-token>" \
  -H "Accept: application/json"

Multi-Tenant Scoping

All endpoints are automatically scoped to your tenant and organization based on your authentication context. You cannot access rules, sets, or logs from other tenants.

The API automatically injects:

RBAC Features

Access to Business Rules API is controlled by these features:

FeatureDescription
business_rules.rules.viewList and view rules
business_rules.rules.createCreate new rules
business_rules.rules.editUpdate existing rules
business_rules.rules.deleteDelete rules
business_rules.rules.executeExecute rules manually
business_rules.logs.viewView execution logs

Contact your administrator if you receive 403 Forbidden responses.

Response Format

Success Responses

Successful responses return JSON with appropriate HTTP status codes:

List Response:

{
  "data": [...],
  "pagination": {
    "page": 1,
    "pageSize": 20,
    "total": 150,
    "totalPages": 8
  }
}

Single Resource:

{
  "id": "uuid",
  "ruleId": "RULE_ID",
  ...
}

Error Responses

Errors return JSON with error details:

{
  "error": "Error message",
  "code": "ERROR_CODE",
  "details": {}
}

Common Status Codes:

Rate Limiting

API requests are rate-limited to prevent abuse:

Rate limit headers are included in responses:

X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1234567890

Pagination

List endpoints support pagination with query parameters:

Example:

curl -X GET "$BASE_URL/api/business_rules/rules?page=2&pageSize=50"

Response:

{
  "data": [...],
  "pagination": {
    "page": 2,
    "pageSize": 50,
    "total": 150,
    "totalPages": 3
  }
}

Filtering and Sorting

List endpoints support filtering and sorting:

Filters: Pass as query parameters

?ruleType=GUARD&enabled=true&entityType=WorkOrder

Sorting: Use sortField and sortDir

?sortField=priority&sortDir=desc

Search: Use search parameter

?search=material

Endpoints

Rules Management

Rule Execution

Execution Logs

Rule Sets

Environment Setup

Set these environment variables for API examples:

export BASE_URL="http://localhost:3000"
export API_KEY="<api-key>"

All subsequent examples assume these variables are set.

Common Workflows

Create and Execute a Rule

# 1. Create a rule
curl -X POST "$BASE_URL/api/business_rules/rules" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "ruleId": "TEST_RULE",
    "ruleName": "Test Rule",
    "ruleType": "VALIDATION",
    "entityType": "Order",
    "conditionExpression": {
      "field": "total",
      "operator": ">",
      "value": 1000
    },
    "successActions": [
      {
        "type": "LOG",
        "config": {"level": "info", "message": "Large order detected"}
      }
    ],
    "enabled": true,
    "priority": 100,
    "version": 1
  }'

# 2. Execute the rule
curl -X POST "$BASE_URL/api/business_rules/execute" \
  -H "Authorization: Bearer $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "entityType": "Order",
    "entityId": "order-123",
    "eventType": "afterCreate",
    "data": {"total": 1500},
    "dryRun": false
  }'

# 3. Check execution logs
curl -X GET "$BASE_URL/api/business_rules/logs?entityId=order-123" \
  -H "Authorization: Bearer $API_KEY"

Bulk Rule Management

# List all GUARD rules
curl -X GET "$BASE_URL/api/business_rules/rules?ruleType=GUARD" \
  -H "Authorization: Bearer $API_KEY"

# Disable rules by updating each
for ruleId in RULE_1 RULE_2 RULE_3; do
  curl -X PUT "$BASE_URL/api/business_rules/rules" \
    -H "Authorization: Bearer $API_KEY" \
    -H "Content-Type: application/json" \
    -d "{\"ruleId\": \"$ruleId\", \"enabled\": false}"
done

Query Execution History

# Get logs for failed executions
curl -X GET "$BASE_URL/api/business_rules/logs?executionResult=FAILURE&pageSize=100" \
  -H "Authorization: Bearer $API_KEY"

# Get logs for specific rule
curl -X GET "$BASE_URL/api/business_rules/logs?ruleId=MATERIAL_CHECK&sortField=executedAt&sortDir=desc" \
  -H "Authorization: Bearer $API_KEY"

SDK and Client Libraries

Official client libraries are available:

Install and use:

import { BusinessRulesClient } from "@open-mercato/api-client";

const client = new BusinessRulesClient({
  baseUrl: "http://localhost:3000",
  apiKey: process.env.API_KEY,
});

const rules = await client.rules.list({ ruleType: "GUARD" });
const result = await client.execute({
  entityType: "Order",
  entityId: "order-123",
  eventType: "afterCreate",
  data: { total: 1500 },
});

Webhooks and Events

Business rules can emit events that trigger webhooks. Configure webhook URLs in rule actions:

{
  "type": "CALL_WEBHOOK",
  "config": {
    "url": "https://your-app.com/webhooks/rule-executed",
    "method": "POST",
    "payload": "{\"ruleId\": \"{{ruleId}}\", \"result\": \"{{result}}\"}"
  }
}

Webhook requests include:

Best Practices

Use Dry Run: Test rule execution with dryRun: true before running in production

Monitor Execution Logs: Regularly review logs for errors and performance issues

Set Appropriate Timeouts: Rules execute with timeouts to prevent runaway execution

Handle Errors: API calls can fail; implement retry logic with exponential backoff

Cache Rule Data: Cache rule lists if querying frequently; invalidate when rules change

Use Pagination: Don't fetch all data at once; use pagination for large result sets

Filter Aggressively: Use filters to reduce data transfer and improve performance

Secure API Keys: Store API keys securely; rotate regularly; use different keys per environment

Troubleshooting

403 Forbidden: Check RBAC features assigned to your user

404 Not Found: Verify resource ID and tenant scope

400 Bad Request: Review error details for validation failures

Rate Limited: Implement backoff and respect rate limit headers

Timeout: Rule execution can timeout; check logs for slow rules

Next Steps

Previous: Authentication and permissions API · Next: Execute business rules through the API