Chapter 13
Automating Tableau Server

As your Tableau Server deployment expands, the number of users and amount of data you have to manage will grow. Tableau provides three command-line tools and a set of APIs (Application Program Interfaces) that will help you automate routine tasks. Most of the functions these tools provide are available directly within Tableau Server’s user interface.

Using Windows Notepad (or your favorite text editor), you can automate tabcmd to run via a batch file. Then, by using Windows Task Scheduler, you can trigger the batch file to run at a specific time or based on a specific triggering event. Publishers can use similar techniques to automate extract refreshes without opening Tableau Desktop or leveraging Tableau Server by using the Data Extract Command-Line Utility. Of course, many popular scripting or programming tools can call Tableau’s command-line functions to automate tasks. How you use these tools is limited only by your desire and creativity.

If you are a system administrator and accustomed to writing script and using the Windows Command Processor and Windows Task Scheduler, you will not have difficulty incorporating any of Tableau’s command-line tools or APIs into your existing toolset. Many people don’t use these utilities because their full functionality is not clearly understood, or they have not seen specific use case examples. Tableau Software provides some good introductory videos on their website. You can find those by searching for “On Demand Training” and looking in the Server section for the tabcmd and tabadmin videos.

Tableau Server’s APIs

Tableau added a set of APIs in V8 that provide administrators with additional tools for automating routine and complex tasks. These APIs include the following:

  • Tableau Server REST API
  • Data Extract API

With the Tableau Server REST API, administrators are provided another mechanism for managing Tableau Server resources programmatically. Unlike the tabcmd utility, the REST API is a web service that does not require an installer or need to be called from the command line.

The Data Extract API offers users the ability to create extract files from a variety of data sources using their language of choice—Python, C/C++, or Java. Prior to the availability of the Data Extract API, users were required to use Tableau Desktop or the Tableau Data Extract Utility to connect to and extract their data sources.

What Do tabcmd and tabadmin Do?

Tableau’s two command-line tools are tabcmd and tabadmin. Tabcmd provides functions for performing workflow tasks such as publishing workbooks, adding users, or exporting workbooks as image or data files. Tabadmin is designed for server administration—configuring server options, activating users, resetting passwords, and other tasks associated with managing the deployment and usage of Server within the enterprise.

A person with publishing rights might want to use tabcmd to automate repetitive tasks associated with updating and publishing data sources. A server administrator can leverage tabadmin to set up a new site, grant or revoke user rights, back up data, alter default session time-out settings (get input from Tableau Support or a qualified Tableau Partner before changing these settings), or reset user passwords. Think of tabcmd as a tool for helping those who publish and share. tabadmin is an automation tool for staff with administration responsibilities—helping them control access, tweak settings, or observe system status.

Installing the Command-Line Tools

When Tableau Server is installed, tabcmd and tabadmin are automatically installed in Tableau Server’s bin folder. Depending on the operating system being used (Window 32-bit or 64-bit), the program will be installed in one of these locations:

  • 32-bit:C:Program FilesTableauTableau Server9.1in
  • 64-bit:C:Program Files (x86)TableauTableau Server9.1in

If you are using a different version of Tableau Server, the portion of the address that says 9.1 should be replaced with the specific version number that you are using. If you are running a distributed environment—with multiple worker machines—and you want to utilize tabcmd on one or more of the worker boxes, you must install tabcmd on those other machines. Tableau provides an installer program for doing that. Those programs are

  • 32-bit:C:Program FilesTableauTableau Server9.1extrasTabcmdinstaller.exe
  • 64-bit:C:Program FilesTableauTableau Server9.1extrasTabcmdinstaller.exe

Copy the Tabcmdinstaller.exe program to the computer that you want to install it on and double-click the file to run the program. The program provides prompts as it installs. Tableau Software recommends installing the tabcmd program on the root drive (C: abcmd).

Because the setup program doesn’t automatically add the bin folder containing tabcmd or tabadmin to the Windows PATH system variable, you have to manually navigate to the bin folder subdirectory to use the programs. This can be avoided if you modify your computer’s PATH system variable to include the path to the bin folder. Doing this allows you to run the executable commands without needing to manually enter the directory location of the bin folder. To start using tabcmd, open the Windows Command Prompt. Figure 13-1 shows you how to do that in a Windows 7 environment.

c13f001.tif

Figure 13-1: Opening Windows Command Prompt

If you are using a different version of Windows, find the accessories folder by searching your computer’s hard disk. Once you’ve entered the accessories folder, click Command Prompt to open the Command Prompt window. In order for you to have access to the tabcmd program files, you must first navigate to one of the bin folders listed in the first section. If you are using a 64-bit version of Windows, type in the following command and press Enter:

cd "C:Program Files(x86)TableauTableau Server9.1in" 

This will change the active directory to the bin folder that holds the tabcmd program. Assuming that your Tableau Server address is http://mytableauserver.com, and that your Tableau Server uses port 80, start a tabcmd session by typing the following into the Command Prompt window:

tabcmd login -s http://mytableauserver.com -u USER -p PASSWORD

The end of the string immediately following the “.com” is case sensitive.

After entering the tabcmd login command and the -s site URL, substitute the URL location of your Tableau Server installation. Then enter your username and password after the -u and -p global option variables.

The instance of Tableau Server used in this example is a local installation on a laptop. The username is Admin, and the password is Admin. The command-line entry to log into this server appears in Figure 13-2.

c13f002.tif

Figure 13-2: Tabcmd login example

Notice the portion of the script that includes the server address also includes an additional element (:8000). This defines the TCP/IP port for the local server instance and is required because the port assigned to the local server isn’t the default value Tableau Server normally uses. You can find more details regarding the default port settings in the Tableau Server online manual by searching for “TCP/IP Ports.” After completing this step, you can now issue other commands to Tableau Server.

Setting the Windows Path

If you want to avoid having to manually change your current directory to the Tableau Server bin folder every time you want to run an executable file, add the bin folder to your Windows PATH system variable. Edit PATH by going to the Windows Control Panel, clicking System and then Advanced System Settings, and selecting the Environmental Variables button to expose the dialog box you see in Figure 13-3.

c13f003.tif

Figure 13-3: Editing the PATH system variable through Control Panel

If this seems intimidating, free utilities are available on the web that make this process easier and provide a larger editing window. Figure 13-4 shows a free utility called Eveditor in which the PATH system variable has been edited to include bin folder.

c13f004.tif

Figure 13-4: Editing PATH using a free editing tool

Adding the path for the Tableau Server bin folder eliminates the need to manually type in the path every time you want to start tabcmd or tabadmin in a batch file. Later, you’ll see how to dynamically set PATH commands inside executable batch files—enabling dynamic setting of the file path so that tabcmd can always find the script it needs to execute.

Keep in mind that third-party tools (such as Eveditor - Windows Environment Variables Editor) are not supported by Tableau Software. You may be successful with Eveditor or other tools that you enjoy using, or you may experience problems. This is outside of Tableau Software’s control.

What Kind of Tasks Can Tabcmd Do?

The tabcmd utility provides the capability to automate routine tasks concerning workflow management activities related to the following:

  • Users, groups, projects, and sites
  • Data management, publishing, updating
  • Session management
  • Security, site listings
  • Server version information

The level of access and control is dependent on the type of administration rights assigned to the person using tabcmd. System administrators can manage data connections, groups, projects, and workbooks. They can add users to groups and projects. But they are not able to alter user licensing levels. Systems administrators have full rights—including the assignment of licensing levels for users and managing the server itself. System administrators can assign some administrative roles to site administrators. That role determines how much control will be given to a site administrator. Site administrators can manage groups, projects, workbooks, and data connections. If the system administrator permits it, they can also add or remove site users.

The tabcmd utility currently provides 27 functions with an additional 12 global option settings.

You can access a complete function reference in Tableau Server’s online manual in the tabcmd Commands section, located at http://onlinehelp.tableausoftware.com/current/server/en-us/tabcmd.htm.

Tabcmd also has a built-in help function for listing the available commands by entering Tabcmd Help Commands. Figure 13-5 shows the help command display.

c13f005.tif

Figure 13-5: The tabcmd help function display

Entering Tabcmd Help and then a specific command name causes more complete options for that single command to be displayed.

Learning to Leverage Tabcmd

In the following examples, you’ll see progressively more advanced ways to use tabcmd including:

  • Manually creating and running a tabcmd script
  • Creating a Windows batch (.bat) file to run a saved script
  • Using Windows Task Scheduler to automatically run a saved script

Manually Entering and Running a Script in Tabcmd

The most basic way of using tabcmd is to manually enter commands that can also be accessed from the Tableau Server manual. This is also a good way to test tabcmd before you attempt to create a script that automatically runs tabcmd.

A common task required of a content administrator is to create groups on Server and assign users to those groups. Figure 13-6 displays the script used to create a new group called Executives.

c13f006.tif

Figure 13-6: Adding a new group to server

The first command in Figure 11-6, tabcmd login, initiates a new session and prompts the user to enter a password. It is also possible to append the password to the end of the login command by adding -p or --password followed by your actual password. The script Tabcmd Creategroup “Executives” triggers the addition of the new group to server. At the bottom of the script, you can see that tabcmd provides a status while processing and then confirms that the operation succeeded.

The next step is to assign users to the group. By creating a list of valid usernames (egroupadd.csv) and saving it in the Tableau Server bin folder, tabcmd can assign the specified users to the executive group. Figure 13-7 shows a list of server users on the left (Allen, Bill, Cal, Dave, Eric). On the right you see the executed script.

This is the script used to add the users: tabcmd addusers "Executives" --users "egroupadd.csv".

These activities can be done directly in the Tableau Server GUI environment, but tabcmd may be a more efficient way to make group assignments if they change frequently or you have a large number of users to assign.

c13f007.tif

Figure 13-7: Adding users to the new group

Running Tabcmd Scripts Via Batch Files

If you find yourself using the same script repeatedly, you can use a text editor to create and save the script for reuse later. Windows includes a text editor program called Notepad that can be used to enter and save a tabcmd script. Notepad is normally located in the Windows accessories folder. Another Windows application—Task Scheduler—can be used to launch the script saved using Notepad. There are many other programming tools you can use for this purpose, but these are part of the Windows toolset.

The Steps Required to Create Batch Processing Scripts

Regardless of whether you prefer to use Windows Notepad or some other text editing software, the basic steps to create a batch process are the same:

  1. Create the tabcmd script in Notepad or another text editor.
  2. Save the script as a .bat executable file.
  3. Double-click the batch file to execute the script.

In this scenario, the script is still run manually, but you no longer have to type all of the instructions every time you want to make changes, export data, or update files. These may be activities you repeat periodically—often enough to warrant saving a script but not so often that you need to fully automate processing.

In the next example, you’ll see how to create a script in a text editor, save the script as a batch file, and then run the script using a CSV source file that provides the usernames and permissions needed to update Tableau Server.

Assume you have five new users to add and will be provisioning Interactor licenses for all of them. Figure 13-8 shows the CSV file with the names of the users.

c13f008.tif

Figure 13-8: CSV file containing new user list

Creating a robust script that will work flexibly is the goal. Doing that requires a little knowledge of Windows commands and tabcmd. Figure 13-9 shows one way to accomplish adding the users.

c13f009.tif

Figure 13-9: Creating and saving script in a .bat file

For the batch file to run properly, place it in the same directory as the CSV file that contains the users who need to be added to Tableau Server. The first line of the code in Figure 13-9, –@set PATH=%PATH%, defines the path for the file to search if any elements are not located there. These Windows commands allow you to define the path for the batch session only. This is a better practice than blending data files in with Windows system files (not a good practice). It also has the virtue of persisting only while the batch file is being executed—rendering the earlier example of permanently editing the PATH system variable unnecessary.

The rest of the script in Figure 13-9 includes tabcmd commands that are located in the bin folder specified by the set path command. In fact, you can define many different paths using this method for files that you want to keep separated.

The bullet list that follows may be easier to read than Figure 13-9. Alter the specific code where applicable to match your system’s setup and the name of the CSV file that you created to load new users:

  • Line 2: Log in to Tableau Server.
  • Line 3: Create the users from the newusers.csv file.
  • Line 4: Log out of Tableau Server.

When the program starts, you’ll see each command run, and when it is finished, the command window will close automatically. Figure 13-10 shows a screenshot of the Windows Command Processor window—running the script.

c13f010.eps

Figure 13-10: The executed script

As the program finishes, the screen automatically clears. If you want to keep it in view, add a fifth line to the script using the Pause command. With just a few lines of code, you can update many records this way. If you aren’t using Active Directory to secure Tableau Server, this method provides a quick way to mass load hundreds of users from a file.

Using Windows Scheduler to Fully Automate Scripts

By adding the batch file from the previous example to Windows Task Scheduler, the file can be updated based on a trigger event or a specific time schedule. For example, if you have an actively expanding user base, it might be necessary to create new users in the system every day. The system administrator could add new users to the Createuser.csv file and schedule updates every day at a specific time. Figure 11-12 shows the Task Scheduler application. A new task was created to add users to Tableau Server (daily). The following steps were used to define the schedule:

  1. General tab: Name and describe the task and set security options.
  2. Triggers tab: Define what causes the action (daily at 7:00 a.m.).
  3. Actions tab: Select the batch file to run (point to the Createuser.bat file).
  4. Conditions tab: Set desired limitations for the run to occur.
  5. Settings tab: Specify additional settings affecting the task behavior.

This will cause the file to be updated on a regular basis without the need for the batch file to be manually selected. Figure 13-11 shows the task scheduled for automatic update of new user additions.

c13f011.tif

Figure 13-11: Task Scheduler window

Even if you’re on vacation, updates can continue if you delegate the task of adding the usernames and license level to Newusers.csv.

Common Use Cases for Tabcmd

There are many different ways to utilize tabcmd to automate repetitive or intensive production issues. If you find yourself doing repetitive tasks consistently, you should consider using tabcmd to automate the process to Save time, improve accuracy, and enhance the way you can share and update files.

The examples presented next are intended as a sampling of the ways you could use tabcmd. You will undoubtedly think of many more ways to automate processes that repeatedly require your attention.

Retrieving Forecast Data from Workbooks

Tableau’s forecasting ability can be used to create initial projections based on historical patterns. The tabcmd Export function can be used to publish forecasted data points from a workbook view. Exporting data in CSV format can then be used to update a source database or a spreadsheet. This first-pass view of the forecast can then be tweaked and returned to a database and stored.

Even more commonly, historical data can be published as well. Even though it may be easier to analyze data using Tableau, some users may lack license access. You may wish to share exported PDF, PNG, or CSV files with vendors that don’t have access to Tableau. Alternatively, you might publish packaged workbooks specifically for partners and allow them to access specific groups on your server.

Manage Data Governance via tabcmd

You may want to create a quality control directory that you publish raw files to for review and then, after auditing and approval, use the Publish command to move the preliminary file into a production group or project. This is an interesting alternative to heavy-handed quality control. Instead of focusing on the end report, IT can focus on ensuring the quality of the data extract file and provide information to consumers with a vetted preliminary view that can be modified to suit specific needs.

Using tabadmin for Administrative Task Automation

The tabadmin toolset is intended for use by the designed server administrators responsible for configuring and maintaining Tableau Server’s data and metadata. Tabadmin has its own set of commands that are exclusively used for these purposes. You can find the complete list of Tabadmin commands at http://onlinehelp.tableau.com/current/server/en-us/tabadmin_cmd.htm.

Typically, a very limited number of technical staff members are tasked with the responsibility of developing, maintaining, and monitoring system performance. The tasks performed using Tabadmin include the following:

  • Tabadmin help
  • Conducting system backups and restores
  • Displaying information on system status
  • Cleaning service log files
  • Resetting the password for the Tableau Server account
  • Enabling or disabling access to Tableau Server’s Postgres database
  • Creating zipped log files
  • Stopping Tableau Server

Starting Tableau Server

The tabadmin command tool may also be useful for additional tasks. The recommendations in the list that follows should be attempted only under the direction of Tableau Software Support or a qualified Tableau Server Partner.

  • Altering default timeout provisions for queries
  • Changing default timeout limits for idle users
  • Creating a server log file
  • Configuring Tableau Server processes
  • Printing Tableau Server license information
  • Printing information on active users
  • Setting primary and secondary gateway hosts
  • Executing system changes via the configure command

The Tabadmin command-line utility is the primary tool maintaining the safety and performance of the server. Tableau Software provides extensive documentation on its website. Refer to Chapter 11 for more details on setup and configuration. Refer to Tableau’s online help, the Tableau Server Administrator Guide, at http://onlinehelp.tableau.com/current/server/en-us/help.htm#ports.htm, for details on default TCP/IP port settings.

Tableau’s online manual is an excellent resource for the latest information related to Tableau Server.

Automating Extracts with the Extract API

Tableau Server provides an easy-to-use extract refresh scheduler that meets the needs of most publishers and server administrators. There are times when a solution outside of Tableau Desktop and Tableau Server may be required. Two common scenarios are

  • Tableau does not provide a native connection to the data store you’d like to use.
  • Tableau Server cannot access the data you’d like to refresh.

The first scenario requires use of Tableau’s Data Extract API, while the second scenario can be handled by any publisher with Tableau Desktop installed on their machine.

Data Extract API

The Data Extract API provides developers with a tool for creating programs to access and manipulate data from any source and convert that data into a Tableau data extract file. The Data Extract API is especially useful in situations where the data source is not natively supported by Tableau. While it can also be used to automate extract creation and refreshes outside of Tableau Server, the Data Extract Command-Line Utility (http://onlinehelp.tableau.com/current/pro/online/mac/en-us/extracting_TDE.html) is able to handle those tasks without the need to write a program.

Using the Data Extract API does not require the purchase of Tableau Desktop or Tableau Server and is available in 32/64-bit versions for Python, C/C++, and Java on both Windows and Linux. Tableau does not offer a Mac solution at the time of this writing.

To get started, visit Tableau’s Get the Data Extract API page (http://www.tableau.com/data-extract-api). After accepting the license agreement, you’ll be given the option to download a package for your language and environment of choice. Each package includes documentation and samples that demonstrate usages of the API given the language and environment you’ve chosen. For this section, you’ll use Python because it is free, is easy to use, and has a large support community.

Download and install the latest version of Python 2.7.x from the Python website at https://www.python.org/downloads. Choose either the 32-bit or 64-bit version based on your hardware’s capability. For Windows users, Python provides an MSI package that will automate installation for you. By default, Python will install to the root of your C: drive with the version number embedded in the name: C:Python27. Rather than using this path every time you use Python, it is more efficient to add it to the PATH environment variable under Control Panel ⇒ System ⇒ Advanced system settings ⇒ Environment Variables.

Once Python has been installed, it is time to install Tableau’s Data Extract module. Navigate to the downloaded file and extract its contents. Within the extracted folder there will be a file named setup.py, which you can use to install the module. Open a Windows command prompt, navigate to the extracted folder, and type the following command: python setup.py install.

A number of log entries will be displayed as Python installs the module. Once it has finished, you’ll be taken back to the command prompt. To test whether the module was successfully installed, begin by opening the Python Interpreter by typing python.

You’ll be presented with a command-line console interface where you can enter commands after the >>> indicators. Test the module installation by typing import dataextract. If no errors are returned, the module has been installed correctly. Exit the Python Interpreter by typing exit().

Within the extracted folder is a samples directory. In that folder Tableau provides a sample Python script named csv2tde.py. You can use this script to turn any CSV file you have into a Tableau data extract files after you enable some simple updates to the corresponding schema.ini file. Running this script requires a single command. Begin by opening the schema.ini file in your favorite text editor. Its contents are

[myfilename.csv]
ColNameHeader=True
col1=col1name col2datatype
col2=col2name col2datatype
...

Within the schema.ini file, you provide the name of the CSV file and some information about the columns it contains. For each column, provide its name and match it to one of the following data types:

  • Bit
  • Byte
  • Short
  • Long
  • Integer
  • Single
  • Double
  • Date
  • DateTime
  • Text
  • Memo

Once finished, place your CSV file, schema.ini, and the csv2tde.py Python script in the same directory. Then, within your open command prompt, run the script by typing the following command: python csv2tde.py myfilename.csv.

As the script runs, you’ll see a notification informing you the extract is being created and the total elapsed time to complete the program run.

While in most scenarios you won’t be using the Extract API to generate extracts from CSV files, this script does a good job of showing the common steps to creating any Extract API program:

  1. Import the API module.
  2. Create an extract object.
  3. Specify the extract table definition (column names and data types).
  4. Create a table in the extract using the definition.
  5. Add rows consisting of data columns to the extract table by iterating through your data.
  6. Once complete, close the extract file using the close() function.

Let’s look at one way you might utilize the Data Extract API with Python to pull data from a website and append the information to a file.

Using the Extract API with Python

In this example, Python with the Data Extract API is used to create an extract file and then append new data to an existing Tableau data extract (.tde) file. The sample data pulls the average February temperature for the 48-contiguous U.S. states from a government website. The extract file created will have three columns:

  • Date
  • Average Temp
  • Anomaly

The lines in the example script that are preceded with a # sign are notes in the script that are ignored by Python. The first three lines in the program import the extract and other necessary modules. Important Python keywords used in this program include

  • def: Used to create a new user-defined function
  • try: Specifies exception handlers
  • finally: Executed at the end of a try statement to clean up resources
  • if: Used to determine which statements will be executed
  • return: Executes a function and returns a value
  • print: Print to console
  • with: Ensures the declared resource (extract file in this case) is closed even in the event of an exception

A small heading is printed before starting the real work. Two calls are made, each to download_noaa_data with slightly different requests. The download_noaa_data function is a utility function that performs the high-level actions, including pulling the data from the given URL and calling other functions to populate the extract. It is important to note that the extract is declared using the with statement to ensure that it is properly closed. It calls create_table_if_needed to ensure the Extract table is present. Then the script opens the table and retrieves the table definition. The weather data is parsed into the correct format next. Four lines of header text are skipped, and then each remaining line is split into individual components. These components are converted to Python types and passed into create_row. Exiting the with statement closes the file, and then the urlopen returned object is closed and the program exits.

The create_table_if_needed function checks for an existing Extract table and creates the table if one is not already present. It makes the TableDefinition with the columns and adds the table to the extract file using the addTable call. This part of the script uses the Type class constants to specify the types in the addColumn calls.

Create_row makes a Row object and sets the column values for the columns from the functions arguments. It then calls the insert method to insert the new row of data into the table.

Here is an example of how the Python script should look:

# Tableau Data Extract API requires Python 2.6 or higher and is not compatible with Python 3.
# http://onlinehelp.tableau.com/current/pro/online/en-us/extracting_TDE_API.html for more information.

import datetime
import urllib2
import dataextract as tde

# Given data for a row, create and add to extract.
def create_row(tde_table, tde_table_def, date, avg_temp, anomaly):
    tde_row = tde.Row(tde_table_def)
    tde_row.setDate(0, date.year, date.month, date.day)
    tde_row.setDouble(1, avg_temp)
    tde_row.setDouble(2, anomaly)
    tde_table.insert(tde_row)
    
def create_table_if_needed(tde_file):
    if not tde_file.hasTable('Extract'):
        tde_table_def = tde.TableDefinition()
        tde_table_def.addColumn('Date', tde.Type.DATE)
        tde_table_def.addColumn('AvgTemp', tde.Type.DOUBLE)
        tde_table_def.addColumn('Anomaly', tde.Type.DOUBLE)

        tde_file.addTable('Extract', tde_table_def)

def download_noaa_data(url):
    data = urllib2.urlopen(url)

    try:
        # Open extract, Extract table and table definition.
        with tde.Extract('our extract.tde') as tde_file:
            create_table_if_needed(tde_file)
            tde_table = tde_file.openTable('Extract')
            tde_table_def = tde_table.getTableDefinition()

            for line in data.readlines()[4:]:  # Skip header, add each line to extract
                print line
                raw_date, raw_avg, raw_anomaly = line.split(',')
                date = datetime.datetime.strptime(raw_date, '%Y%m').date()
                avg = float(raw_avg)
                anomaly = float(raw_anomaly)
                create_row(tde_table, tde_table_def, date, avg, anomaly)

    finally:
        data.close()

print 'Downloading United States 48-contiguous average temps from NOAA'
print 'Downloading from start to 2010...'
download_noaa_data('http://www.ncdc.noaa.gov/cag/time-series/us/110/00/tavg/1/02/1895-2010.csv?base_prd=true&firstbaseyear=1901&lastbaseyear=2000')

# Now append a second batch to same extract.
print 'Downloading after 2010...'
download_noaa_data('http://www.ncdc.noaa.gov/cag/time-series/us/110/00/tavg/1/02/2011-2015.csv?base_prd=true&firstbaseyear=1901&lastbaseyear=2000')

If you want to learn more about the Extract API, Tableau provides a series of videos on the API download page at www.tableau.com/products/api-download.

Data Extract Command-Line Utility

In cases where Tableau Server cannot directly access the data you’d like to refresh, the Data Extract Command-Line Utility can be used to automate refresh tasks. This is a common scenario when hosting your workbooks with Tableau Online, Tableau’s cloud-based hosting solution, rather than on premises.

The utility is available on any machine where Tableau Desktop is installed under Tableau’s Program Files path.

  • 32-bit:C:Program FilesTableauTableau 9.1in
  • 64-bit:C:Program Files (x86)TableauTableau 9.1in

Tableau’s online documentation (http://onlinehelp.tableau.com/current/pro/online/mac/en-us/extracting_TDE.html) provides a full list of command and parameter options available. Available commands include

  • refreshextract
  • addfiletoextract

Each command accepts a set of parameters, including a useful --help parameter, which provides additional information for many commands. Other parameters enable you to define where the data is located; the data source, username, and password (if required); where the extract should be published; and so on.

In the example that follows, you’ll see how to add data to an existing extract on Tableau Server, assuming the data is currently residing on your machine in a CSV file.

Begin by opening a command prompt and navigating to the Tableau Program Files path listed earlier. Next, type the following command:

      tableau addfiletoextract -s http://mytableauserver.com  -t  "MYSITENAME" -u MYUSERNAME -p MYPASSWORD --project "MYPROJECTNAME" --datasource MYDATASOURCE --original-file "C:PATHTOMYFILEFILENAME.CSV"

You can also refresh your data source using data residing in a database. Tableau automatically uses the same database and server specified in the published data source, but you’ll need to supply the --source-username and --source-password parameters if not using Windows Authentication to connect to the database.

REST API

Tableau’s REST (Representational State Transfer) API (Application Program Interface) enables you to manage Tableau Server programmatically. The REST API has been part of Tableau since 8.2, but it had to be turned on via tabadmin set api.server.enabled true before it was available. In Tableau Server 9, the REST API is turned on by default but can be disabled with tabadmin set api.server.enabled false.

For those unfamiliar with REST, it is an architecture that provides guidelines and best practices as put forth by the W3C (World Wide Web Consortium). All that means is that Tableau’s software engineers worked with a well-defined and vetted set of rules when building this service into Tableau Server.

For you, it means that you will communicate with Tableau Server using common HTTP methods, such as POST, GET, PUT, and DELETE. These requests must also be properly formatted as XML, as defined by Tableau (you’ll get to these details in just a moment).

Please note that the REST API can also be used with Tableau Online (Tableau’s Cloud offering), but it is limited to a subset of REST API methods. Check Tableau’s online help for details at http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#methods_not_available_in_tableau_online.

Initial Transactions

The REST API can be used most effectively by the system administrator who has full access to all of the REST API methods. Site administrators can also use the REST API but will not have access to all of the REST methods. Tableau’s REST API documentation indicates what and who can access these methods. At a high level, this is what an initial transaction looks like:

  • A user sends an XML-formatted HTTP request to the Tableau Server REST endpoint (the designated URI that accepts REST requests).
  • The REST service returns with its own XML formatted HTTP response, which tells you if your request was successful. If you were requesting some specific set of information, it will return that as well.
  • You can now parse out the information returned to use in your application.

Let’s take this high-level overview and see how you would use it to authenticate access to the service:

  1. The authentication endpoint is located at https://www.yourtableauserver.com/api/2.0/auth/signin.
  2. You POST XML formatted data to the endpoint in step 1:
    <tsRequest>
     <credentials name="username"  password="password" >
       <site contentUrl="site-name" />
     </credentials>
    </TsRequest>
  3. The code variables in the following list must be specified:
    • username: The user you are authenticating as.
    • password: The password for that user.
    • site-name: This is actually what Tableau normally calls the site ID. It is case sensitive. You must authenticate to a Tableau site. If it is the default site, you leave the site name empty.
  4. Tableau’s REST service will respond with an XML-formatted response of its own:
    <tsResponse 
       xmlns="http://tableausoftware.com/api" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://tableausoftware.com/api http://tableausoftware.com/api/ts-api-2.0.xsd">
     <credentials token="0ec4eb5fe07bb01b786b77f41bba87db">
       <site id="1f6b0e92-bf05-4c3f-bb43-02be4ed9e36f" contentUrl="my-site"/>
       <user id="93bd1906-d31b-4a12-86cf-e16fd0fa3efd"/>
     </credentials>
    </tsResponse>

This response includes some information that you will need to use to communicate and interact further with the REST API.

  • token: The token is an authentication passcode that you will need to use when making any other REST requests. It tells Tableau Server that you’ve already been authenticated.
  • site id: This is not the Tableau site ID as you normally know it. It is a unique identifier for the site that you are connecting to, which you will need to store for future/additional requests.
  • site contentURL: This is what Tableau documentation typically calls the site ID.
  • user id: Much like the site ID, this is a unique identifier for the user who is being acted upon. You will need to store this if you want to use it for future/additional requests.

In whatever language being utilized (Python, Ruby, JavaScript, or something else), you will need to extract the relevant values out of the XML response in order to use them for future requests.

If you are unfamiliar with programming and are not sure how to get started, try a free Chrome (Google Browser) extension called Postman. Postman is an easy way to get familiar with REST APIs, and it requires no programming experience. You simply install the extension, and then with the interface it provides, you define your endpoint, how you would like to send or request the data (POST, GET, PUT, DELETE, and so on), and the body of the message you’ll be sending. In this case, you POST the raw XML data, as you see in Figure 13-12.

c13f012.tif

Figure 13-12: Postman

Once you have entered in the information, you can click Send, and Tableau Server should reply with an XML response. If you have incorrectly entered in information, the REST API may respond with an error message. Carefully look over what the error message says and fix any mistakes.

A common error is to type in default for the contentUrl when, in fact, it should be left empty if you want to connect to the default site. If you need to authenticate to a different site, then enter that site in the Tableau site ID. If everything worked properly, you should receive a response that looks similar to Figure 13-13.

c13f013.tif

Figure 13-13: Response

Notice that the response contentUrl is empty. This is expected if you are connecting to Tableau’s default site (which in this example you are). If it is any other site, the site contentUrl will have a value.

Now you will have a token, a unique identifier site ID, and a unique identifier user ID that you can use to further interact with Tableau Server. The REST API allows you to interact with sites, projects, workbooks, data sources, users, groups, permissions, jobs, favorites, and publishing.

A full listing of functionality can be found at http://onlinehelp.tableau.com/current/api/rest_api/en-us/help.htm#REST/rest_api_ref.htm#API_Listing.

Let’s take a look at an example using Postman. It’s not immediately obvious how you should use the token retrieved. It would be fair to assume that there might be an additional XML tag that must be added to send the data back, but in this example there is not.

The token gets sent to Tableau via the Header. In Postman, there is a Header button, which will let you input a new header variable. The token header variable name is X-Tableau-Auth, and the value is the string of alphanumeric digits that were returned in the credentials token attribute when you authenticated. In this example the token provided is

1b505c0164aa0c73b959ca2f1af23813

Figure 13-14 shows the appearance in context.

To add a new project to our site, you can POST to a new endpoint:

/api/2.0/sites/site-id/projects
c13f014.tif

Figure 13-14: Response

You know that this is the endpoint because it is explicitly defined in the documentation as the URI to use when adding a project. The site-id section of the URI must be replaced with the unique identifier site ID, in this case:

2bc9d5f9-fdff-4715-98a6-0c4edb213961.

The request body structure is also defined in the documentation, so you know from there how to form this XML.

<tsRequest>
<project name="project-name"
description="project-description" />
</tsRequest>

You will replace project-name with the name of your project and the project-description with your description.

Once you’ve made your changes, click Send. This creates a new authenticated request to Tableau Server. If everything went well, you should see a 200 OK result. This indicates that the project was created successfully on your site. You can continue to use the authentication token for this session to pass any more requests to the server.

The preceding sample shows how to create something on the server, but you can also retrieve information in a similar fashion. For instance, if you want a list of users in a specific site, you can use the same principles to send a request to the appropriate endpoint: /api/2.0/sites/site-id/users/ with the authentication token header. There is no body XML data because you’re simply requesting info.

Tableau Server will respond with an XML response listing the users in the specified site. It is up to the application engineer to parse this data and use as needed.

Tableau’s REST API is a great way to manage the server or retrieve server data remotely. The recent updates to the REST API have greatly increased its capabilities, making it a formidable tool to include in your Tableau arsenal.

Tableau Software continues to improve Tableau Desktop and Tableau Server. In the appendixes that follow, you’ll find details on Tableau’s product ecosystem, supported database connectors, keyboard shortcuts for Windows and the Mac, and recommended hardware configurations for the desktop and server products.

If you are new to Tableau and are not familiar with SQL syntax, the function reference should be a helpful resource that you refer to often. It provides an extensive listing of Tableau functions with code samples and explanations that will give you an alphabetically sorted reference for entering the correct syntax for each function.

Finally, Appendix F provides an overview of the companion website where you will find all of the example files used in this book.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.93.175