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.


Rulebricks SDK

Rulebricks SDK's make it possible to use rules in your applications in as few as 3 lines of code. We currently provide SDKs for Python, Node.js/Typescript, Java, and Go, with more coming soon.

Python

pypi (opens in a new tab)

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.

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

Here's an example of how to create a simple rule using the Forge SDK:

from rulebricks import RuleBuilder, RuleType
from rulebricks.forge import BooleanOperator, NumberOperator, StringOperator, boolean_op, number_op, string_op
 
# Initialize a new RuleBuilder
builder = RuleBuilder()
 
# Set name and description
builder.set_name("Customer Discount Eligibility")
builder.set_description("Determines if a customer is eligible for a discount based on their purchase history and account status.")
 
# Define schema
builder.add_request_field("purchase_count", "Purchase Count", RuleType.NUMBER, "Number of purchases made", 0)
builder.add_request_field("is_subscribed", "Is Subscribed", RuleType.BOOLEAN, "Whether the customer is subscribed to the newsletter", False)
builder.add_request_field("customer_type", "Customer Type", RuleType.STRING, "Type of customer (regular, premium, vip)", "regular")
 
builder.add_response_field("discount_eligible", "Discount Eligible", RuleType.BOOLEAN, "Whether the customer is eligible for a discount", False)
builder.add_response_field("discount_percentage", "Discount Percentage", RuleType.NUMBER, "Percentage of discount to apply", 0)
 
# Create conditions
condition1 = builder.add_condition()
builder.update_condition(condition1, "purchase_count", *number_op(NumberOperator.GREATER_THAN_OR_EQUAL_TO)(10))
builder.update_condition(condition1, "is_subscribed", *boolean_op(BooleanOperator.IS_TRUE)())
builder.update_condition(condition1, "customer_type", *string_op(StringOperator.EQUALS)("regular"))
builder.set_condition_response(condition1, "discount_eligible", True)
builder.set_condition_response(condition1, "discount_percentage", 5)
 
condition2 = builder.add_condition()
builder.update_condition(condition2, "customer_type", *string_op(StringOperator.EQUALS)("premium"))
builder.set_condition_response(condition2, "discount_eligible", True)
builder.set_condition_response(condition2, "discount_percentage", 10)
Available Operators

The Forge SDK provides a range of operators for different data types. You can find the full list of available operators in the following files:

  • src/rulebricks/forge/operators.py

This file contains the definitions for BooleanOperator, NumberOperator, StringOperator, DateOperator, and ListOperator.

Outputting Rules

The Forge SDK offers several ways to output your rules:

  1. JSON Output

    To get a JSON representation of your rule:

    json_output = builder.to_json()
    print(json_output)
  2. Pretty Print (Tabular Format)

    To get a human-readable tabular representation of your rule:

    table_output = builder.to_table()
    print(table_output)

    This might produce output similar to:

    +---------------+---------------+-----------------+-------------------+----------------------+
    | purchase_count | is_subscribed |  customer_type  | discount_eligible | discount_percentage  |
    +===============+===============+=================+===================+======================+
    | greater than   | is true       | equals          | True              | 5                    |
    | or equal to    | ()            | (regular)       |                   |                      |
    | (10)           |               |                 |                   |                      |
    +---------------+---------------+-----------------+-------------------+----------------------+
    | -              | -             | equals          | True              | 10                   |
    |                |               | (premium)       |                   |                      |
    +---------------+---------------+-----------------+-------------------+----------------------+
  3. Export to File

    To export your rule to a file for import through the Rulebricks UI:

    filename = builder.export()
    print(f"Rule exported to: {filename}")

    This will create a file with the .rbx extension in your current directory. The filename will be based on the rule name you set, with "-Generated.rbx" appended.

Complete Example

Here's a complete example that demonstrates creating a rule and using all output methods:

from rulebricks import RuleBuilder, RuleType
from rulebricks.forge import BooleanOperator, NumberOperator, StringOperator, boolean_op, number_op, string_op
 
def create_customer_discount_rule():
    builder = RuleBuilder()
 
    builder.set_name("Customer Discount Eligibility")
    builder.set_description("Determines if a customer is eligible for a discount based on their purchase history and account status.")
 
    builder.add_request_field("purchase_count", "Purchase Count", RuleType.NUMBER, "Number of purchases made", 0)
    builder.add_request_field("is_subscribed", "Is Subscribed", RuleType.BOOLEAN, "Whether the customer is subscribed to the newsletter", False)
    builder.add_request_field("customer_type", "Customer Type", RuleType.STRING, "Type of customer (regular, premium, vip)", "regular")
 
    builder.add_response_field("discount_eligible", "Discount Eligible", RuleType.BOOLEAN, "Whether the customer is eligible for a discount", False)
    builder.add_response_field("discount_percentage", "Discount Percentage", RuleType.NUMBER, "Percentage of discount to apply", 0)
 
    condition1 = builder.add_condition()
    builder.update_condition(condition1, "purchase_count", *number_op(NumberOperator.GREATER_THAN_OR_EQUAL_TO)(10))
    builder.update_condition(condition1, "is_subscribed", *boolean_op(BooleanOperator.IS_TRUE)())
    builder.update_condition(condition1, "customer_type", *string_op(StringOperator.EQUALS)("regular"))
    builder.set_condition_response(condition1, "discount_eligible", True)
    builder.set_condition_response(condition1, "discount_percentage", 5)
 
    condition2 = builder.add_condition()
    builder.update_condition(condition2, "customer_type", *string_op(StringOperator.EQUALS)("premium"))
    builder.set_condition_response(condition2, "discount_eligible", True)
    builder.set_condition_response(condition2, "discount_percentage", 10)
 
    return builder
 
if __name__ == "__main__":
    rule = create_customer_discount_rule()
 
    # JSON output
    print("JSON Output:")
    print(rule.to_json())
    print("\n")
 
    # Table output
    print("Table Output:")
    print(rule.to_table())
    print("\n")
 
    # Export to file
    filename = rule.export()
    print(f"Rule exported to: {filename}")

Node.js/Typescript

npm shield (opens in a new tab)

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.

Installation
npm install --save @rulebricks/api
# or
yarn add @rulebricks/api
Usage
import { RulebricksClient } from '@rulebricks/api';
 
const rulebricks = new RulebricksClient({
  apiKey: 'XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX',
  environment: 'https://rulebricks.com',
});
 
rulebricks.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);
});
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
Contributing

This library is generated programmatically. We suggest opening an issue (opens in a new tab) to discuss any issues or feature requests with us.

License

This project is licensed under the MIT License - see the LICENSE file for details.


Java

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.0.0</version>
</dependency>

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

implementation 'com.rulebricks:rulebricks-sdk-java:1.0.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
}
Feedback and Contributions

Feedback and contributions are welcome. Please report any issues or suggestions through the GitHub issue tracker (opens in a new tab).

License

The Rulebricks Java SDK is released under the MIT License. See the LICENSE file for more details.


Go

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
}
Feedback and Contributions

We welcome feedback and contributions to the SDK. Please report any issues or suggestions through the GitHub issue tracker (opens in a new tab).

For contributions, please submit a pull request with a clear description of the changes and any relevant tests.

License

The Rulebricks Go SDK is released under the MIT License. See the LICENSE file for more details.


C#

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
}
Feedback and Contributions

Feedback and contributions are welcome. Please report any issues or suggestions through the GitHub issue tracker (opens in a new tab).

License

The Rulebricks C# SDK is released under the MIT License. See the LICENSE file for more details.


Ruby

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
Feedback and Contributions

Feedback and contributions are welcome. Please report any issues or suggestions through the GitHub issue tracker (opens in a new tab).

License

The Rulebricks Ruby SDK is released under the MIT License. See the LICENSE file for more details.