How to Use Tableau Webhook API to Get Alerts on Slack for Specific Events

Tasrie IT Services

Tasrie IT Services

·6 min read
How to Use Tableau Webhook API to Get Alerts on Slack for Specific Events

Integrating Tableau with Slack using webhooks allows for real-time alerts on various Tableau events, such as when a workbook is created or a data source is updated.

This guide will walk you through setting up Tableau webhooks to send notifications to a Slack channel for specific events.

What are tableau webhooks?

Tableau webhooks are a mechanism that allows external applications to receive notifications about specific events happening within a tableau server or tableau online. instead of constantly polling tableau for updates, webhooks enable a more efficient and real-time way to stay informed about changes and actions taken within your tableau environment.

What is tableau webhooks api?

The tableau webhooks api provides a set of endpoints that allow you to programmatically create, manage, and delete webhooks. with this api, you can define specific events to be monitored, and when those events occur, tableau will send a payload of information to a designated endpoint (e.g., a slack webhook url). this makes it possible to automate workflows and integrate tableau events seamlessly with other applications and services.

Uses of tableau webhooks

Tableau webhooks are particularly useful for:

real-time notifications: receive instant alerts for important events like workbook creations, data source updates, and user promotions. automation: trigger automated workflows in response to specific tableau events, enhancing operational efficiency. integration: integrate tableau with other tools and platforms (e.g., slack) to create a cohesive ecosystem for monitoring and managing data and analytics activities. monitoring and auditing: keep track of changes and actions in tableau to ensure compliance, security, and proper usage of resources.

Prerequisites

  • Tableau Server or Tableau Online: Ensure you have administrative access.
  • Tableau Token: Tableau personal access token. check here to know more on how to generate it
  • Slack Webhook URL: You'll need a Slack webhook URL to send notifications to a Slack channel.
  • Python Environment: Set up a Python environment to run the provided scripts.

Key Tableau Events

These are some of the key events you can monitor:

  • AdminPromoted
  • AdminDemoted
  • DatasourceUpdated
  • DatasourceCreated
  • DatasourceDeleted
  • DatasourceRefreshStarted
  • DatasourceRefreshSucceeded
  • DatasourceRefreshFailed
  • LabelCreated
  • LabelUpdated
  • LabelDeleted
  • SiteCreated
  • SiteUpdated
  • SiteDeleted
  • UserDeleted
  • ViewDeleted
  • WorkbookUpdated
  • WorkbookCreated
  • WorkbookDeleted
  • WorkbookRefreshStarted
  • WorkbookRefreshSucceeded
  • WorkbookRefreshFailed

Creating a Tableau Webhook

Here’s a Python Flask route to create a Tableau webhook:

python
@app.route('/create_tableau_webhook', methods=['POST'])
def create_tableau_webhook():
    if request.method == 'POST':
        data = request.json
        logging.info(f"Received data for Tableau webhook creation: {data}")

        webhook_name = data.get('name')
        event_type = data.get('event')
        destination_url = data.get('destination_url')

        if not webhook_name:
            logging.error("Webhook name is missing")
            return jsonify({'status': 'failure', 'error': 'Webhook name is required'}), 400

        if not event_type:
            logging.error("Event type is missing")
            return jsonify({'status': 'failure', 'error': 'Event type is required'}), 400

        if event_type not in VALID_TABLEAU_EVENTS:
            logging.error("Invalid event type")
            return jsonify({
                'status': 'failure',
                'error': f'Invalid event type: {event_type}. Please refer to the valid event types: https://help.tableau.com/current/developer/webhooks/en-us/docs/webhooks-events-payload.html'
            }), 400

        if not destination_url:
            logging.error("Destination URL is missing")
            return jsonify({'status': 'failure', 'error': 'Destination URL is required'}), 400
        logging.info(f"Webhook name: {webhook_name}")
        logging.info(f"Event type: {event_type}")
        logging.info(f"Destination URL: {destination_url}")

        # Create the XML payload
        token, site_id = sign_in(TABLEAU_SERVER, TABLEAU_USERNAME, TABLEAU_PASSWORD, TABLEAU_SITE_ID)
        ts_request = ET.Element('tsRequest')
        webhook_xml = ET.SubElement(ts_request, 'webhook', name=webhook_name, event=event_type)
        webhook_destination = ET.SubElement(webhook_xml, 'webhook-destination')
        ET.SubElement(webhook_destination, 'webhook-destination-http', method='POST', url=destination_url)
        xml_payload = ET.tostring(ts_request, encoding='utf-8', method='xml')
        logging.info(f"Calling tableau webhook api with payload: {xml_payload}")

        tableau_url = f"{TABLEAU_SERVER}/api/{VERSION}/sites/{site_id}/webhooks"
        headers = {
            'X-Tableau-Auth': token,
            'Content-Type': 'application/xml'
        }
        response = requests.post(tableau_url, data=xml_payload, headers=headers)

        if response.status_code == 201:
            logging.info("Tableau webhook created successfully")
            return jsonify({'status': 'success'}), 201
        else:
            logging.error(f"Failed to create Tableau webhook: {response.text}")
            return jsonify({'status': 'failure', 'error': response.text}), 500
    else:
        return jsonify({'status': 'failure'}), 400

Explanation:

  1. Receive Data: The route receives JSON data containing the webhook name, event type, and destination URL.
  2. Validation: It checks if all required fields are provided and if the event type is valid.
  3. Create Payload: It constructs an XML payload for the webhook request.
  4. Send Request: It sends the request to the Tableau API to create the webhook.
  5. Response Handling: It handles the API response, logging success or failure.

Listing and Deleting Webhooks

Listing Webhooks:

python
@app.route('/list_tableau_webhooks', methods=['GET'])
def list_tableau_webhooks():
    token, site_id = sign_in(TABLEAU_SERVER, TABLEAU_USERNAME, TABLEAU_PASSWORD, TABLEAU_SITE_ID)
    url = TABLEAU_SERVER + f"/api/{VERSION}/sites/{site_id}/webhooks"
    server_response = requests.get(url, headers={'x-tableau-auth': token})
    _check_status(server_response, 200)
    webhooks_data = []
    root = ET.fromstring(server_response.text)
    for _webhook in root.findall('.//{http://tableau.com/api}webhook'):
        webhook_data = {
            'id': _webhook.get('id'),
            'name': _webhook.get('name'),
            'event': _webhook.get('event'),
            'url': _webhook.find('.//{http://tableau.com/api}webhook-destination-http').get('url')
        }
        webhooks_data.append(webhook_data)

    return jsonify({'status': 'success', 'webhooks': webhooks_data}), 200

This route lists all webhooks by sending a GET request to the Tableau API and parsing the XML response.

Deleting a Webhook:

python
@app.route('/delete_tableau_webhook', methods=['POST'])
def delete_tableau_webhook():
    data = request.json
    webhook_id = data.get('webhook_id')

    if not webhook_id:
        logging.error("Missing required parameters: site_id or webhook_id")
        return jsonify({'status': 'failure', 'error': 'Missing required parameters: site_id or webhook_id'}), 400

    token, site_id = sign_in(TABLEAU_SERVER, TABLEAU_USERNAME, TABLEAU_PASSWORD, TABLEAU_SITE_ID)
    tableau_url = f"{TABLEAU_SERVER}/api/{VERSION}/sites/{site_id}/webhooks/{webhook_id}"
    headers = {
        'X-Tableau-Auth': token,
        'Content-Type': 'application/xml'
    }
    response = requests.delete(tableau_url, headers=headers)

    if response.status_code == 204:
        logging.info("Tableau webhook deleted successfully")
        return jsonify({'status': 'success'}), 204
    else:
        logging.error(f"Failed to delete Tableau webhook: {response.text}")
        return jsonify({'status': 'failure', 'error': response.text}), response.status_code

This route deletes a specified webhook by sending a DELETE request to the Tableau API.

Posting Tableau Events To Slack

once you have your webhooks set up in tableau, you can configure them to send alerts to slack using a slack incoming webhook url. the destination_url parameter in the webhook creation process should be your slack webhook url.

here’s a python flask route to handle incoming tableau webhook data and post it to slack:

python
@app.route('/webhook', methods=['post'])
def webhook():
    if request.method == 'post':
        data = request.json
        logging.info(f"received data: {data}")

        # extract necessary information
        event_type = data.get('event_type', 'unknown event')
        text = data.get('text', 'no additional information provided.')
        resource_name = data.get('resource_name', 'unknown resource')

        # post data to slack with attachments
        slack_data = {
            'channel': slack_channel,
            'attachments': [
                {
                    'fallback': f'{event_type} - {resource_name}',
                    'color': slack_color,
                    'pretext': f'{event_type}:',
                    'fields': [
                        {
                            'title': resource_name,
                            'value': text,
                            'short': false
                        }
                    ]
                }
            ]
        }
        response = requests.post(slack_webhook_url, json=slack_data)

        if response.status_code == 200:
            logging.info("alert posted to slack successfully")
            return jsonify({'status': 'success'}), 200
        else:
            logging.error(f"failed to post data to slack: {response.text}")
            return jsonify({'status': 'failure', 'error': response.text}), 500
    else:
        return jsonify({'status': 'failure'}), 400

Sending Alerts to Slack

Once you have your webhooks set up in Tableau, you can configure them to send alerts to Slack using a Slack Incoming Webhook URL. The destination_url parameter in the webhook creation process should be your Slack webhook URL.

By integrating Tableau webhooks with Slack, you ensure that your team stays informed about important events in real-time, improving responsiveness and collaboration.

Complete code is available at here. You can clone this git repository and run it on your local machine or run it as a docker container.

Conclusion

Setting up Tableau webhooks to send notifications to Slack is a powerful way to keep your team updated on critical events. By following the steps outlined in this guide, you can efficiently manage and monitor your Tableau environment.

We offer top-notch Tableau professional services to help you optimize and manage your Tableau environment. Whether you have questions or need assistance, our team is here to support you. Get in touch today for personalized help and solutions!

illustration
Need Expert Help ?

At Tasrie IT, we assist businesses in their growth and addressing intricate issues by utilizing advanced cloud technologies and contemporary platform engineering techniques.

Related Posts