API 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.


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.