Call a Ruleset from Your Software

Introduction

This guide explains how to call a ruleset via its API from external software such as a web application.

Rulesets are a means to an end, and the purpose of a ruleset is to implement a business rule and make its functionality generally available to other software. Because then you only have to maintain the rule, and the external software always automatically uses the latest implementation. To do so, you need to call a ruleset via its API from your external software.

Usually, ruleset APIs are called from JavaScript (JS). Therefore, Rulecube automatically provides a JS example for each ruleset of how to call the set. And thus, this guide starts with calling a ruleset from JS.

But because calling the API of a ruleset only requires a POST request with an API key for authorization and a JSON input body, you can do this from any modern programming language or development environment. And for your reference, we'll also provide a Python example.

Before you begin

Procedure

Call a ruleset API from JS

JS and JS frameworks like React and Vue are the backbone of many web applications. Therefore, Rulecube integrates closely with JS, such as, for example, with the ability to include JS in expressions. But also by being able to easily call ruleset APIs from JS:

  1. Open your ruleset and click Docs. ↳ The Documentation page opens with the Summary tab activated.

  2. Click the Examples tab. ↳ Rulecube shows a fetch example for calling the ruleset via its API.

  3. Copy the fetch example.

  4. Move over to your code editor and create a new JS or HTML file with a basic skeleton to be functional.

  5. Add the following code to the file in the appropriate place—for example, to the <script> section in an HTML file:

    async function yourFunction() {
                
            }

    ⇨ Replace yourFunction with your preferred function name.

  6. Paste the copied fetch example into the function.

  7. Call the function from HTML or JS. For instance, like in this HTML snippet:

    <form action="javascript:yourFunction()">

    For example, your complete HTML file could look something like this for the ruleset that was created with our tutorial about applying entities:

    <html>
    
    <head>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">
        <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.3/dist/jquery.slim.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
    </head>
    
    <body>
        <div class="container">
            <h1 class="m-5">Loan Amount Calculator</h1>
            <div class="m-5">
                <form action="javascript:calculateAmount()">
                    <div class="row">
                        <div class="form-group col-6">
                            <label for="applicantname">Applicant name:</label>
                            <input type="text" class="form-control" id="applicantname">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col-3">
                            <label for="dateofbirth">Date of birth:</label>
                            <input type="date" class="form-control" id="dateofbirth">
                        </div>
                    </div>
                    <div class="row">
                        <div class="form-group col-3">
                            <label for="yearlyincome">Yearly income:</label>
                            <input type="number" class="form-control" id="yearlyincome">
                        </div>
                    </div>
                    <button type="submit" class="btn btn-primary">Calculate loan amount</button>
                </form>
                <div class="jumbotron">
                    <h4 class="ml-2 mb-3" id="overviewtitle">Overview</h4>
                    <div class="col-3">
                        <label for="age">Age:</label>
                        <input type="number" class="form-control" id="age" readonly>
                    </div>
                    <div class="col-3">
                        <label for="maxamount">Maximum loan amount:</label>
                        <input type="number" class="form-control" id="maxamount" readonly>
                    </div>
                </div>
            </div>
        </div>
    
        <script>
            async function calculateAmount() {
                let response = await fetch('<<Your rulecube URL>>/api/execute/ruleset', {
                    method: 'POST',
                    headers: {
                        "Authorization": 'YOUR_API_KEY',
                        "Content-Type": 'application/json'
                    },
                    body: JSON.stringify({
                        "name": "loanapplication",
                        "version": "1.0",
                        "options": {
                            "explain": false
                        },
                        "input": {
                            "LoanApplicant": {
                                "Name": document.getElementById("applicantname").value,
                                "DateOfBirth": document.getElementById("dateofbirth").value,
                                "YearlyIncome": document.getElementById("yearlyincome").value
                            }
                        }
                    })
                })
    
                if (response.ok) {
                    let result = await response.json();
                    console.log('Result:', result);
                    document.getElementById("overviewtitle").innerHTML = 'Overview for ' + document.getElementById("applicantname").value;
                    document.getElementById("age").setAttribute('value', result.result.LoanApplicant.Age);
                    document.getElementById("maxamount").setAttribute('value', result.result.LoanApplicant.MaximumLoanAmount);
                } else {
                    let error = await response.text();
                    console.error('Error executing:', error);
                }
            }
        </script>
    </body>
    
    </html>

  8. Replace <<Your rulecube URL>> with the correct base URL of your rulecube instance. E.g. https://app.rulecube.com

  9. Save your file.

  10. Test your JS or HTML file through the Inspect function of your browser.

Call a ruleset API from Python

Data Scientists often use Python to analyze data, and rulesets can play a big role in that by providing data and performing complex calculations. Furthermore, many data-driven websites are built with Python frameworks like Django and Flask. So, let's look at how to call a ruleset API from Python:

Step 1: Lookup your API key

  1. Select <<Your tenant>> from the Rulecube menu bar. ↳ Your Profile page opens and shows a section for API keys like this:

  2. Open a text editor and paste the copied API key into the editor.

Step 2: Create the Python script that calls the ruleset API

  1. If necessary, install the requests package with this command: pip install requests.

  2. Open your code editor and create a new Python file.

  3. Copy the following code into the file:

    import requests
    
    receive = requests.post("<<Your Rulecube url>>/api/execute/ruleset",
                            json={"name": "YOUR_RULESET",
                                  "version": "1.0",
                                  "options": {"explain": False},
                                  "input": {}
                                 },
                            headers={'Authorization': 'YOUR_API_KEY'})
    
    print(receive.json()['result'])

  4. Replace <<Your Rulecube url>> with your Rulecube base url (e.g. https://app.rulecube.com)

  5. Replace YOUR_RULESET and YOUR-API_KEY (from the text editor you copied the key into earlier) with your values.

  6. Move over to Rulecube and click Docs in your ruleset.

  7. Click the Examples tab. ↳ Rulecube shows a JS example of calling your ruleset, including the JSON input, which also applies to calling your ruleset from Python.

  8. Copy the complete input section from the JSON body.

  9. Return to your code editor and replace the empty input section with the copied version.

  10. Save your file.

  11. Test your Python script from your code editor or a command prompt.

Additional resources