Embedding real-time decisioning through APIs

0

This is the first post of two in a series focused on how to embed real-time decisioning with SAS. My following post on Embedding real-time decisioning through the Microsoft Power Platform is available here.

 

As technology advances, so are consumer expectations. In today's connected world, consumers are expecting touchpoints to be seamless and efficient. When applying for loans, mortgages, credit cards, insurance policies or even cellular plans online, consumers are looking to provide the requisite information once and get a response quickly. Today's consumers are less tolerant of radio silence after submitting their applications. They also do not appreciate supplementing their information over phone or email before a decision is made. Complex, inefficient, and slow processes cause organizations to lose customers.

But what if a consumer could fill out an application online and get their approval or pre-approval instantly? Such a process would be far more seamless, efficient, and enjoyable. And this process could still utilize machine learning to approve applicants that are likely to be profitable. The technology is available, we just need to standardize, automate, and embed the decisioning process. This post discusses both decision flows and APIs as they relate to embedding decision flows into webpages and applications using APIs.

Real-time decisioning: the role of decision flows

For real-time answers, a decision is stronger than a model. The output of a model is typically numeric. For example, a loan default model might return a score for a potential borrower as something like 0.556. This represents the probability that the potential borrower will default on their loan, but organizations must decide what to do with that number. Setting a cutoff to deny all loan applicants whose probability of default is greater than 0.5 or 50% is the simplest example of a decision flow. Decision flows can incorporate models, business rules, custom logic, and more. Thus, decision flows are useful for business applications because they can create standardized rules for utilizing the outputs of a model to mimic current processes. Once these processes are standardized, they can be automated to save time and reduce manual efforts.

Using SAS Intelligent Decisioning, organizations can build decision flows that utilize customer data, machine learning models, and business rules to create a custom process to fit their needs. Continuing with our loan default example, this decision flow could take customer information from their application, check their data against initial loan eligibility criteria, assign customer segments, score using a model specific to that segment to determine if a loan should be extended, and for approved loans start establishing loan terms.

Example SAS Intelligent Decisioning Flow

Once a standardized decision flow is established in SAS Intelligent Decisioning, the decisioning process can be easily automated. Clicking Publish  in the upper right-hand corner and selecting SAS Micro Analytics Service as the destination in the pop-up window will create a REST API endpoint to your decision. Save or remember the published name for later!

How to Publish a Decision Flow into MAS

Real-time decisioning: the role of APIs

An API, or Application Programming Interface, offers a standardized way to communicate between systems or services. We will specifically be using REST APIs. There are various components to a REST API, including the HTTP Method or Verb, the URL, the body, and headers. Possible HTTP Methods include POST, which creates a resource, GET, which retrieves a resource, PUT, which updates a resource and, DELETE, which deletes a resource. The URL identifies the path of the resource. The body passes data between services or systems, often in JavaScript Object Notation (JSON) format. Finally, headers are used to pass metadata, including authorization information.

You can call a REST API using a variety of methods, including using Curl, Postman, Go, JavaScript, or even Python using the requests package. The ubiquitous nature of the API makes it easy for developers to utilize. Calling an API from a web application requires just a few additional lines of code. Important to note, is that deployed decision are not the only APIs available on SAS Viya. SAS Viya was written such that SAS analytics, data, and services can all be accessed via API.

Real-time decisioning: API examples

In the Python code blocks below, we will use REST APIs to create an authorization token for SAS Viya, get information about the resources deployed in SAS Viya, and finally use a decision to score new data. First things first, when working with APIs on SAS Viya we will need an access token. The following block of Python code takes in credentials and saves an authorization token for our use in later API calls. It's using a POST method and passing the credentials in its body. If you're not working in Python, you can find the syntax for these APIs calls in curl, JavaScript, and go in the documentation.

# Import packages 
import getpass
from requests import request
import urllib3
urllib3.disable_warnings()
 
# Get information from user
host = input('Hostname:')
username = input('Username: ')
password = getpass.getpass('Password: ')
 
# Get token
url = host + '/SASLogon/oauth/token' 
r = request('POST', url,
            data='grant_type=password&username=%s&password=%s' %(username, password),
            headers={
                'Accept': 'application/json',
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            auth=('sas.ec', ''),
            verify=False)
 
# Save token
token = r.json()['access_token']

Hopefully you remember the decision's deployed name, but if not, have no fear. If you want to get information on everything deployed in MAS, run the following:

headers = {'Authorization': 'Bearer ' + token}
 
url = host + '/microanalyticScore/modules/'
 
r = request('GET', url, params={}, headers = headers, verify=False)
 
r.json()

With the name of the specific module we're interested in, we can see what inputs it is expecting and what outputs it generates. This can help us write a function to pass information from the web application to the API and return results back to the application. We will need the input variable names and expected variable types as well as the order of returned outputs for our function.

deployed_name= input("Deployed Name:")
 
 
headers = {'Authorization': 'Bearer ' + token}
 
url = host + '/microanalyticScore/modules/' + deployed_name + '/steps'
 
r = request('GET', url, params={}, headers = headers, verify=False)
 
r.json()

Finally, let's generate an example function. The data from the fields a consumer fills out in a webpage can be collected and passed to our function upon submit. The function will first create a JSON body with the input variables for the decision. Note that string variables and numeric variables need to be treated slightly differently when generating JSON data. Next it will pass the inputs to the API for scoring. Finally, the output can be parsed to pull the specific information from the decision, such as an approval/denial message to return to the potential applicant. Our webpage can then return that directly to the consumer.

def score_decision(num_input, string_input):
    # Prepare payload
    payload = '{"inputs":[{"name": "num_input", "value": '+str(num_input)+'},  {"name":"string_input", "value":"' + string_input + '"}]}'
 
    # Send request
    headers = {'Content-Type': 'application/vnd.sas.microanalytic.module.step.input+json', 
               'Authorization': 'Bearer ' + token}
 
    url = host + '/microanalyticScore/modules/' + deployed_name + '/steps/execute'
 
    r = request('POST', url, data=payload, headers = headers, verify=False)
 
    # Grab output
    action = r.json()['outputs'][2]['value']
 
    #Return values
    return action

Once the decision flow is embedded into the application, making changes to the decision, business rules, logic flow, or models is a breeze. Simply republish the model under the same name and specify Replace. As long as your input and output variables remain the same, your applications will call the updated decision without recoding.

Conclusion

SAS Intelligent Decisioning and SAS Micro Analytics Service make embedding a real-time decision into an application via APIs a breeze. This enables consumers to receive answers faster and more efficiently.

Stay tuned for my next post where we will look at another method for embedding real time decisioning into webpages and web applications!

Where to learn more

Building and embedding decision flows offer many opportunities for customization. Thus, there are a lot of places you can go from here to learn more.

To learn more about decisioning, please see:

To learn more about building web applications, please see:

To learn more about APIs, please see:

 

Share

About Author

Sophia Rowland

Product Manager | SAS Model Manager

Sophia Rowland is a Senior Product Manager focusing on ModelOps and MLOps at SAS. In her previous role as a data scientist, Sophia worked with dozens of organizations to solve a variety of problems using analytics. As an active speaker and writer, Sophia has spoken at events like All Things Open, SAS Explore, and SAS Innovate as well as written dozens of blogs and articles. As a staunch North Carolinian, Sophia holds degrees from both UNC-Chapel Hill and Duke including bachelor’s degrees in computer science and psychology and a Master of Science in Quantitative Management: Business Analytics from the Fuqua School of Business. Outside of work, Sophia enjoys reading an eclectic assortment of books, hiking throughout North Carolina, and staying upright while ice skating.

Related Posts

Comments are closed.

Back to Top