Kickstart an Alteryx Workflow with Alteryx API - CNDRO.LLC
2742
post-template-default,single,single-post,postid-2742,single-format-standard,wp-custom-logo,theme-bridge,bridge-core-2.9.4,woocommerce-no-js,tribe-no-js,ehf-template-bridge,ehf-stylesheet-bridge-child,qode-page-transition-enabled,ajax_fade,page_not_loaded,,qode-title-hidden,qode_grid_1300,footer_responsive_adv,hide_top_bar_on_mobile_header,columns-4,qode-child-theme-ver-1.0.0,qode-theme-ver-27.8,qode-theme-bridge,qode_header_in_grid,wpb-js-composer js-comp-ver-6.7.0,vc_responsive,elementor-default,elementor-kit-2634,elementor-page elementor-page-2742

Kickstart an Alteryx Workflow with Alteryx API

An API  stands for Application Programming Interface. It is a specific set of codes or instructions and specifications used in software programs to communicate with other applications/devices. It is a software program that facilitates interaction with other software programs. What does Alteryx API do? Alteryx API allows you to programmatically interact with Alteryx products to extend and customize your experience. Alteryx provides different APIs and they are Alteryx Engine API, .NET API, Connect API, Gallery API, and Alteryx Analytics Hub(AAH) API.

This article will go through the steps to kickstart an Alteryx workflow with an Alteryx Gallery API. We would be solving a problem with the Alteryx API. Python will be the platform with which the Alteryx API communicates with the Alteryx Server Gallery. We will achieve this via the following steps:

  • Get server gallery API endpoint
  • Authenticate the connection to the Alteryx Server Gallery
  • Parse in the function’s parameter to connect with Alteryx Gallery
  • Use functions to kickstart Alteryx workflow
  • List all the workflows in the Gallery
  • Write codes to run your workflow

Step 1. Get the Server Gallery API credentials (API Key, Secret Key, and the Gallery URL)

We can get the credential from the admin section of the Alteryx Gallery as shown in the screenshot below. This credential includes the API key and the secret key, enabling us to connect and authenticate with the server.

Secondly, we need the URL of the gallery prepended with API endpoints. It will look like this https://dev-alteryx-cndro.com/. We can prepend the endpoints based on what we need to do.

Step 2. Authenticate with the Alteryx Gallery API

To do this we need to authenticate using the OAuth 1.0a signature which is described here https://github.com/Kong/mashape-oauth/blob/master/FLOWS.md#oauth-10a-one-legged.

Interestingly, there is a Python library that can help us to authenticate with the Alteryx Gallery. We are going to be using the package. You can find the package here GitHub — Theamazingdp/AlteryxGalleryAPI: Python for Connecting and Working with Alteryx Gallery API.

To ensure consistency, we created a Python Class object and function for each task in a python script. The first function buildOauthParams is to build the authentication parameter, the generateSignature is to authenticate the connection.

import time
import collections
import random
import math
import string
import sys
import requests
import base64
import urllib
import hmac
import hashlib
from credentials import apikey, apiSecret
from argparse import ArgumentParser
class Gallery(object):
    def __init__(self, apiLocation, apiKey, apiSecret):
        self.apiLocation = 'http://' + apiLocation + '/gallery/api/v1'
        self.apiKey = apiKey
        self.apiSecret = apiSecret
        #self.apiVerbose = apiVerbose
def buildOauthParams(self):
        return {'oauth_consumer_key': self.apiKey,
                'oauth_nonce': self.generate_nonce(5),
                'oauth_signature_method': 'HMAC-SHA1',
                'oauth_timestamp': str(int(math.floor(time.time()))),
                'oauth_version': '1.0'}
                
    def generateSignature(self, httpMethod, url, params):
        q = lambda x: requests.utils.quote(x, safe="~")
        sorted_params = collections.OrderedDict(sorted(params.items()))
normalized_params = urllib.parse.urlencode(sorted_params)
        base_string = "&".join((httpMethod.upper(), q(url), q(normalized_params)))
secret_bytes = bytes("&".join([self.apiSecret, '']), 'ascii')
        base_bytes = bytes(base_string, 'ascii')
        sig = hmac.new(secret_bytes, base_bytes, hashlib.sha1)
return base64.b64encode(sig.digest())

In the above Python code, we wrote a function to connect and authenticate with the Alteryx Gallery. In the next steps, we are going to use these functions to connect.

Step 3: Parse in the function’s parameter to connect with ALTERYX GALLERY

Establish_connection = Gallery('https://dev-alteryx-cndro.com/', apiKey, apiSecret)

Step 4. Use these functions to kickstart Alteryx workflows with the Alteryx API

At this point, we will start communicating with the Alteryx Server Gallery resources using API. To do this, we will need to list all the workflows in the Gallery and then trace the workflow we need to execute using the API.

We will create a function that lists all the workflows, we will call it “subscription.” The python function is defined in the following lines of code. The function will output all the Alteryx Workflow in a subscription.

def subscription(self, search=""):
        method = 'GET'
        url = self.apiLocation + '/workflows/subscription/'
        params = self.buildOauthParams()
        if search != "":
            params.update({'search': search})
        signature = self.generateSignature(method, url, params)
        params.update({'oauth_signature': signature})
        try:
            output = requests.get(url, params=params)
            output.raise_for_status()
        except requests.exceptions.HTTPError as err:
            print(err)
            sys.exit(err)
        except requests.exceptions.RequestException as err2:
            print(err2)
            sys.exit(err2)
return output, output.json()

Step 5: List all the workflows in the Gallery

Here, we are going to use the workflow function we created.

list_all_workflows_on_server = Establish_connection.subscription()
def executeWorkflow(self, appId, **kwargs):
        method = 'POST'
        url = self.apiLocation + '/workflows/' + appId + '/jobs/'
        params = self.buildOauthParams()
        signature = self.generateSignature(method, url, params)
        params.update({'oauth_signature': signature})
if 'payload' in kwargs:
if self.apiVerbose:
                print('Payload included: %s' % kwargs['payload'])
payload_data = kwargs['payload']
try:
                output = requests.post(url, json=payload_data, headers={'Content-Type': 'application/json'}, params=params)
                output.raise_for_status()
            except requests.exceptions.HTTPError as err:
                print(err)
                sys.exit(err)
            except requests.exceptions.RequestException as err2:
                print(err2)
                sys.exit(err2)
else:
            if self.apiVerbose:
                print('No Payload included')
try:
                output = requests.post(url, params=params)
                output.raise_for_status()
            except requests.exceptions.HTTPError as err:
                print(err)
                sys.exit(err)
            except requests.exceptions.RequestException as err2:
                print(err2)
                sys.exit(err2)
return output, output.json()

Now that we have all the workflows in our subscriptions, we will isolate and get the information specific to the Alteryx workflow.

We will provide an interface to get the name of the workflow from our users. The program will ask you at execution which workflow (name) you are looking for.

Step 6: Write the following lines of code to run your workflow

Search_for_workflows = input('Hi, Please enter the name of your workflow you would like to run: ')
for workflow in list_all_workflows_on_server:
    if workflow['metaInfo']['name'] == Search_for_workflows:
        print('Congratulation, the name of the workflow you searched is available on the server')
        workflow_id = workflow['id']
        print('This is the workflow id for the name you searched on the server', workflow_id)
        #fire_up_a_workflow = Establish_connection.executeWorkflow(workflow_id)    
    elif workflow['metaInfo']['name'] != Search_for_workflows:
        print('Please make sure you entered the workflow name the right way or enter another workflow name to run')

Final Thoughts

Alteryx is a powerful, yet easy-to-use software that makes life super easy. Integrating this software with other applications using the Gallery API is golden. It helps to solve lots of data engineering problems at the enterprise level.

You can bring Alteryx into JavaScript applications, android applications, spark applications, etc. using the Gallery API. In an event-based trigger, you can instruct your application to kickstart an Alteryx workflow with the Gallery API when an event is executed.

If you have any questions please feel free to ask in the comment section.

No Comments

Post A Comment