Skip to main content

Rulebricks – Python SDK

pypi

The Rulebricks Python SDK provides convenient access to the Rulebricks API from Python.

Documentation

API reference documentation is available here.

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}")

Feedback and Contributions

Feedback is vital as we continue to improve the SDK and add more features. Please report any issues or suggest improvements through our GitHub issues page. Contributions to the SDK are welcome via pull requests.

Metadata

Release files for rulebricks 0.2.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rulebricks 0.2.0
File Size Uploaded
rulebricks-0.2.0.tar.gz 18.2 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for rulebricks 0.2.0
File Interpreter ABI Platform
rulebricks-0.2.0-py3-none-any.whl Python 3 none any Details

Total release size: 43.8 kB

Release files / rulebricks-0.2.0.tar.gz

Download URL rulebricks-0.2.0.tar.gz
Size 18.2 kB
Tags Source
SHA-256 checksum
How to use checksums
81dc7d16c7a81f98261184d689b8646260a1e9c66465423dc0349cdef36147e3
BLAKE2b-256 checksum
How to use checksums
cce166fd4f38a05c1e634485c99b1a08778bf1f40af30c42707e7d85a6727a67
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.7.17 Linux/5.15.0-1067-azure

Release files / rulebricks-0.2.0-py3-none-any.whl

Download URL rulebricks-0.2.0-py3-none-any.whl
Size 25.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
a27d9d3a88c974be755f36fb0e9d439d57ab04035df57db2ad3631924fa4fc66
BLAKE2b-256 checksum
How to use checksums
3c356591728b6e658e2aa6406eb08a82998d6d88711d098979918e03d0749fc1
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via poetry/1.5.1 CPython/3.7.17 Linux/5.15.0-1067-azure

Release history Release notifications | RSS feed

2.6.8

2 release files

2.6.7

2 release files

2.6.6

2 release files

2.6.5

2 release files

2.6.4

2 release files

2.6.3

2 release files

2.6.2

2 release files

2.6.0

2 release files

2.5.9

2 release files

2.5.0

2 release files

2.0.0

2 release files

1.5.3

2 release files

1.5.2

2 release files

1.5.1

2 release files

1.5.0

2 release files

1.4.0

2 release files

1.3.0

2 release files

1.1.0

2 release files

1.0.0

2 release files

0.5.0

2 release files

0.4.5

2 release files

0.4.4

2 release files

0.4.3

2 release files

0.4.2

2 release files

0.4.1

2 release files

0.4.0

2 release files

0.3.8

2 release files

0.3.7

2 release files

0.3.5

2 release files

0.3.3

2 release files

0.3.1

2 release files

0.3.0

2 release files

This release

0.2.0 This release

2 release files

0.1.7

2 release files

0.1.5

2 release files

0.1.4

2 release files

0.1.3

2 release files

0.1.2

2 release files

0.1.1

2 release files

0.1.0

2 release files

0.0.9

2 release files

0.0.8

2 release files

0.0.6

2 release files

0.0.5

2 release files

0.0.4

2 release files

0.0.3

2 release files

0.0.1

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page