API/SDK Reference

Rulebricks API

🔎

Looking for API documentation based on specific rules you've published? Find our Automated Documentation (opens in a new tab) feature in the API section of your Rulebricks Dashboard.


SDK Banner

Rulebricks SDK's make it possible to use rules in your applications in as few as 3 lines of code. We currently support Python, Node.js/Typescript, C#, Java, Ruby, and Go.

The Python and Node.js SDKs also include our Forge module, which provides powerful utilities that help you programmatically create and manage rules.

Python SDK

The Rulebricks Python SDK (opens in a new tab) provides convenient access to the Rulebricks API from Python. SDK usage largely mirrors the API itself, with methods for solving rules, bulk solving rules, and more.

Find detailed examples of using this SDK in our examples repository (opens in a new tab).

Installation

Add this dependency to your project's build file:

pip install rulebricks
# or
poetry add rulebricks

Configuration

Before using the SDK, configure your API key. You can find your API key in your Rulebricks Dashboard.

import rulebricks as rb
 
# Replace 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX' with your actual API key
rb.configure(
    api_key="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
    # base_url="https://rulebricks.com" # Optional: Use this to override the default base URL for private cloud deployments
    # timeout=10 # Optional: Use this to override the default timeout in seconds
)

Basic Usage

Using the SDK to interact with the Rulebricks API in a synchronous manner is simple.

Here's an example of how to use our Python SDK to solve a rule:

import rulebricks as rb
 
# Set the API key
rb.configure(
    api_key="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
)
 
result = rb.rules.solve(
    slug="tJOCd8XXXX",
    request={
        "customer_id": "anc39as3",
        "purchase_history": ["t-shirt", "mug"],
        "account_age_days": 4,
        "last_purchase_days_ago": 3,
        "email_subscription": False
    }
)
 
print(result)

Asynchronous Usage

For asynchronous API calls, access methods via the async_api attribute.

This allows you to leverage Python's asyncio library for non-blocking operations:

import rulebricks as rb
import asyncio
 
# Set the API key
rb.configure(
    api_key="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
)
 
async def main():
    async_result = await rb.async_api.rules.solve(
        slug="tJOCd8XXXX",
        request={
            "customer_id": "anc39as3",
            "purchase_history": ["t-shirt", "mug"],
            "account_age_days": 4,
            "last_purchase_days_ago": 3,
            "email_subscription": False
        }
    )
    print(async_result)
 
if __name__ == "__main__":
    asyncio.run(main())

Using a combination of solve, bulk_solve, parallel_solve and flows in synchronous or asynchronous modes gives you high flexibility to interact with the Rulebricks API in a way that best suits your application's needs.

Forge SDK

The Forge SDK is a powerful tool within the Rulebricks package that allows you to programmatically create and manage rules. It provides a flexible and intuitive way to define rule sets, conditions, and responses.

Purpose

The Forge SDK enables you to:

  • Define complex rule structures
  • Create and manage conditions within rules
  • Specify request and response schemas
  • Generate rule representations in various formats (JSON, tabular, file)
Creating a Rule
from rulebricks.forge import Rule
 
import rulebricks as rb
 
# Initialize a new rule
rule = Rule()
 
# Set basic metadata
rule.set_name("Customer Discount Rule") \
    .set_description("Determines customer discount eligibility based on purchase history")
 
# Define fields
purchase_count = rule.add_number_field("purchase_count", "Number of purchases", 0)
is_subscribed = rule.add_boolean_field("is_subscribed", "Newsletter subscription status", False)
customer_type = rule.add_string_field("customer_type", "Customer type", "regular")
 
# Define response fields
# Note we do not create variables for response fields
rule.add_boolean_response("discount_eligible", "Discount eligibility", False)
rule.add_number_response("discount_amount", "Discount percentage", 0)
 
# Add conditions
# By default, conditions are ANDed together
rule.when(
    purchase_count=purchase_count.greater_than(10), # "...and "
    is_subscribed=is_subscribed.equals(True), # "...and "
    customer_type=customer_type.equals("regular")
).then(
    discount_eligible=True,
    discount_amount=5
)
 
# Or, you can use `any` to OR your conditions
# rule.any(
#     purchase_count=purchase_count.less_than(10),
#     is_subscribed=is_subscribed.equals(False),
# ).then(
#     discount_eligible=False
# )
 
# Preview the rule locally
print(rule.to_table())
 
# Or, export the rule to a file
# rule.export()
#
# Or, publish the rule to your Rulebricks workspace
# rb.configure(
#     api_key="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
# )
# rule.set_workspace(rb)
# rule.publish()
Exporting Rules

Rules can be exported to files:

# Export with default filename
filename = rule.export()
 
# Export to specific directory
filename = rule.export(directory="/path/to/directory")
Tabular Visualization

Rules can be visualized in a table format using the to_table() method:

# Print rule in table format
print(rule.to_table())

This will produce a grid-formatted table showing all conditions and their corresponding responses:

+---------------+---------------+-----------------+-------------------+
| age           | income        | customer_type   | discount          |
+===============+===============+=================+===================+
| greater than  | between       | equals          | 20                |
| (30)          | (50000,      | (premium)       |                   |
|               | 100000)       |                 |                   |
+---------------+---------------+-----------------+-------------------+
| less than     | greater than  | equals          | 10                |
| (30)          | (30000)       | (standard)      |                   |
+---------------+---------------+-----------------+-------------------+

The table format makes it easy to:

  • Visualize all conditions at once
  • Compare different conditions
  • Verify rule logic
  • Share rule definitions with stakeholders
Best Practices
  1. Field References: Store field references in variables when you need to use them multiple times:

    age = rule.add_number_field("age")
    # Use age variable in multiple conditions
  2. Chaining: Use method chaining for cleaner code:

    rule.set_name("My Rule").set_description("Description")
  3. Condition Organization: Group related conditions together:

    # Premium customer condition
    rule.when(
        customer_type=customer_type.equals("premium"),
        purchase_count=purchase_count.greater_than(100)
    ).then(
        discount=20
    )
  4. Meaningful Names: Use descriptive names for fields and rules:

    # Good
    purchase_history = rule.add_list_field("purchase_history")
     
    # Not as clear
    ph = rule.add_list_field("ph")

Node.js/Typescript SDK

The Rulebricks Node.js library (opens in a new tab) provides convenient access to the Rulebricks API from JavaScript/TypeScript. SDK usage largely mirrors the API itself, with methods for solving rules, bulk solving rules, and more.

Find detailed examples of using this SDK in our examples repository (opens in a new tab).

Installation

npm install --save @rulebricks/sdk
# or
yarn add @rulebricks/sdk

Usage

import { RulebricksApiClient, Rule } from "@rulebricks/sdk";
import "dotenv/config";
 
// Initialize the Rulebricks client
const rb = new RulebricksApiClient({
  environment: process.env.RULEBRICKS_ENVIRONMENT || "https://rulebricks.com",
  apiKey:
    process.env.RULEBRICKS_API_KEY || "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX",
});
 
rb.rules.solve('tJOCd8XXXX', {
  customer_id: 'anc39as3',
  purchase_history: ['t-shirt', 'mug'],,
  account_age_days: 4,
  last_purchase_days_ago: 3,
  email_subscription: false,
}, {
  // Request options (Optional, leave empty for default values)
  // timeoutInSeconds: 10, (Optional: Use this to override the default timeout in seconds)
  // maxRetries: 3, (Optional: Use this to override the default number of retries)
}).then((result) => {
  console.log(result);
}).catch((err) => {
  console.error(err);
});

Forge SDK

The Forge SDK documented for Python above is also available for Node.js/Typescript. The Forge SDK provides powerful utilities that help you programmatically create and manage rules.

Most methods are mirrored in the Node.js/Typescript SDK, with the same functionality and usage patterns. See our examples repository (opens in a new tab) for detailed examples of using the Forge SDK in Node.js/Typescript.

Handling errors

When the API returns a non-success status code (4xx or 5xx response), a subclass of RulebricksApiError will be thrown:

try {
  // ...
} catch (err) {
  if (err instanceof RulebricksApiError) {
    console.log(err.statusCode) // 400
    console.log(err.message) // "BadRequestError"
    console.log(err.body) // list of errors
  }
}

Error codes are as followed:

Status CodeError Type
400BadRequestError
429RateLimitError
500InternalServerError

C# SDK

The Rulebricks C# SDK (opens in a new tab) provides convenient access to the Rulebricks API from C# applications. SDK usage allows for solving rules, bulk solving rules, and more.

Installation

To install the Rulebricks C# SDK, add the following package to your project:

dotnet add package RulebricksApi

Configuration

Instantiate a RulebricksApiClient with your API key:

var client = new RulebricksApiClient("YOUR_API_KEY");

Basic Usage

Solve a rule:

var requestData = new Dictionary<string, object>
{
    { "dataKey", "dataValue" }
};
 
var result = client.Rules.Solve("<rule-slug>", requestData);

Bulk solve rules:

var requestDataList = new List<Dictionary<string, object>>
{
    new Dictionary<string, object> { { "dataKey", "dataValue" } }
};
 
var results = client.Rules.BulkSolve("<rule-slug>", requestDataList);

Parallel solving rules requires a particular format using $rule alongside respective data payloads:

var requestDataMap = new Dictionary<string, Dictionary<string, object>>
{
    { "eligibility", new Dictionary<string, object>
        {
            { "$rule", "1ef03ms" },
            { "customer_id", "anc39as3" },
            { "purchase_history", new List<string> { "t-shirt", "mug" } },
            { "account_age_days", 4 },
            { "last_purchase_days_ago", 3 },
            { "email_subscription", false }
        }
    },
    { "offers", new Dictionary<string, object>
        {
            { "$rule", "OvmsYwn" },
            { "customer_id", "anc39as3" },
            { "last_purchase_days_ago", 3 },
            { "selected_plan", "premium" }
        }
    }
};
 
var results = client.Rules.ParallelSolve(requestDataMap);

Error Handling

The SDK throws exceptions to indicate API errors:

try
{
    var result = client.Rules.Solve("<rule-slug>", requestData);
}
catch (Exception e)
{
    // Handle the error
}

Java SDK

The Rulebricks Java SDK (opens in a new tab) provides convenient access to the Rulebricks API from Java applications. SDK usage allows for solving rules, bulk solving rules, and more.

Installation

For Maven, add this dependency to your project's pom.xml file:

<dependency>
  <groupId>com.rulebricks</groupId>
  <artifactId>rulebricks-sdk-java</artifactId>
  <version>1.5.0</version>
</dependency>

For Gradle, add this to your build.gradle file:

implementation 'com.rulebricks:rulebricks-sdk-java:1.5.0'

Configuration

Instantiate a RulebricksApiClient with your API key:

RulebricksApiClient client = RulebricksApiClient.builder()
    .apiKey("YOUR_API_KEY")
    .build();

Basic Usage

Solve a rule:

Map<String, Object> requestData = new HashMap<>();
requestData.put("dataKey", "dataValue");
 
Map<String, Object> result = client.rules().solve("<rule-slug>", requestData);

Bulk solve rules:

List<Map<String, Object>> requestDataList = new ArrayList<>();
requestDataList.add(requestData);
 
List<Map<String, Object>> results = client.rules().bulkSolve("<rule-slug>", requestDataList);

Parallel solving rules requires a particular format using $rule alongside respective data payloads:

Map<String, Map<String, Object>> requestDataMap = new HashMap<>();
requestDataMap.put("eligibility", {
    "$rule": "1ef03ms",
    "customer_id": "anc39as3",
    "purchase_history": ["t-shirt", "mug"],
    "account_age_days": 4,
    "last_purchase_days_ago": 3,
    "email_subscription": false
});
requestDataMap.put("offers", {
    "$rule": "OvmsYwn",
    "customer_id": "anc39as3",
    "last_purchase_days_ago": 3,
    "selected_plan": "premium"
});
 
Map<String, Object> results = client.rules().parallelSolve(requestDataMap);

Error Handling

The SDK throws exceptions to indicate API errors:

try {
    Map<String, Object> result = client.rules().solve("<rule-slug>", requestData);
} catch (Exception e) {
    // Handle the error
}

Go SDK

License

The Rulebricks Go SDK (opens in a new tab) provides convenient access to the Rulebricks API from Go applications. SDK usage largely mirrors the API itself, with methods for solving rules, bulk solving rules, and more.

Installation

To use the Rulebricks Go SDK in your project, you can install it using go get:

go get github.com/rulebricks/go-sdk

Configuration

Before you can start using the SDK, you need to configure it with your Rulebricks API key. You can do this by creating a client with the NewClient function and passing in your API key as a request option:

import (
    "github.com/rulebricks/go-sdk/client"
    "github.com/rulebricks/go-sdk/option"
    "net/http"
)
 
opts := option.WithAPIKey("YOUR_API_KEY")
client := client.NewClient(opts)

Basic Usage

To solve a rule with the SDK, you can use the Solve function of the client. Here's an example of how to solve a rule identified by its unique slug:

response, err := client.Rules.Solve(context.Background(), "<rule-slug>", map[string]interface{}{
    "data": "your-data-here",
})
if err != nil {
    // Handle error
}
// Use the response

For bulk operations, you can use the BulkSolve function to execute a rule against multiple data payloads:

responses, err := client.Rules.BulkSolve(context.Background(), "<rule-slug>", []map[string]interface{}{
    {"data": "first-payload"},
    {"data": "second-payload"},
    // Add more payloads as needed
})
if err != nil {
    // Handle error
}
// Use the responses

To execute multiple rules in parallel, use the ParallelSolve function, along with the special parallel solve format:

responses, err := client.Rules.ParallelSolve(context.Background(), map[string]interface{}{
    "eligibility":  {"$rule": "tJOCd8XX", "customer_id": "anc39as3", "purchase_history": []string{"t-shirt", "mug"}, "account_age_days": 4, "last_purchase_days_ago": 3, "email_subscription": false},
    "offers": {"$rule": "Ovms3XX", "customer_id": "anc39as3", "last_purchase_days_ago": 3, "selected_plan": "premium"},
    // Note the non top-level keyword $rule is used to identify the rule to be executed
    // alongside the data payload that should be passed to that particular rule
})
if err != nil {
    // Handle error
}
// Use the responses

Asynchronous Usage

The SDK supports asynchronous operations using Go routines. You can use the Solve, BulkSolve, and ParallelSolve functions within a goroutine for concurrent rule solving:

go func() {
    response, err := client.Rules.Solve(context.Background(), "<rule-slug>", map[string]interface{}{
        "data": "your-data-here",
    })
    if err != nil {
        // Handle error
    }
    // Use the response
}()

Error Handling

The SDK returns errors that can be handled in a typical Go error handling pattern:

response, err := client.Rules.Solve(...)
if err != nil {
    // Handle the error
}

Ruby SDK

License

The Rulebricks Ruby SDK (opens in a new tab) provides convenient access to the Rulebricks API from Ruby applications. SDK usage allows for solving rules, bulk solving rules, and more.

Installation

To install the Rulebricks Ruby SDK, add the following line to your Gemfile:

gem 'rulebricks_api_client'

Then run:

bundle install

Configuration

Configure the SDK with your API key:

require 'rulebricks_api_client'
 
RulebricksApiClient.configure do |config|
  config.api_key = 'YOUR_API_KEY'
end

Basic Usage

Solve a rule:

request_data = {
  dataKey: 'dataValue'
}
 
result = RulebricksApiClient::Rules.solve('<rule-slug>', request_data)

Bulk solve rules:

request_data_list = [
  { dataKey: 'dataValue' }
]
 
results = RulebricksApiClient::Rules.bulk_solve('<rule-slug>', request_data_list)

Parallel solving rules requires a particular format using $rule alongside respective data payloads:

request_data_map = {
  eligibility: {
    '$rule' => '1ef03ms',
    customer_id: 'anc39as3',
    purchase_history: ['t-shirt', 'mug'],
    account_age_days: 4,
    last_purchase_days_ago: 3,
    email_subscription: false
  },
  offers: {
    '$rule' => 'OvmsYwn',
    customer_id: 'anc39as3',
    last_purchase_days_ago: 3,
    selected_plan: 'premium'
  }
}
 
results = RulebricksApiClient::Rules.parallel_solve(request_data_map)

Error Handling

The SDK raises exceptions to indicate API errors:

begin
  result = RulebricksApiClient::Rules.solve('<rule-slug>', request_data)
rescue StandardError => e
  # Handle the error
end