### Setup Virtual Environment and Install Dependencies Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/CONTRIBUTING.md Sets up a Python virtual environment, upgrades pip, and installs the project's required and optional development dependencies. This ensures a clean and isolated development environment. ```bash cd VizQL-Data-Service/python_sdk python -m venv --system-site-packages venv source venv/bin/activate # On Unix/MacOS virtualenv\Scripts\activate # On Windows python -m pip install --upgrade pip # Upgrade pip pip install -e . # Required dependencies # pip install -e .[dev] # Required and optional dependencies ``` -------------------------------- ### Run Examples with Authentication Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/CONTRIBUTING.md Executes example scripts for the VizQL Data Service Python Client, demonstrating synchronous and asynchronous operations. Supports authentication via username/password, Personal Access Token (PAT), or JWT. ```bash # Running the existing examples synchronously and asynchronously cd src/examples python examples.py --help # If `site` argument is left out, this will run against a default site that your token works for # If `async` argument is left out, the default examples run synchronously # Auth using username and password python examples.py --user "" --password "" --server "" # Auth using personal access token (PAT) python examples.py --pat-name "" --pat-secret "" --server "" --site "" --async # Auth using JWT python examples.py --jwt-token "" --server "" --site "" --async ``` -------------------------------- ### Install Development Dependencies and Run Tests Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/CONTRIBUTING.md This bash command installs the project's development dependencies, including testing tools, using pip. It is followed by the command to execute the test suite with verbose output, ensuring all tests pass before contributing. ```bash pip install -e ".[dev]" pytest tests/ -v ``` -------------------------------- ### Install VizQL Data Service Python SDK Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Instructions for installing the vizql-data-service-py package using pip. It also includes optional steps for setting up a Python virtual environment. ```bash python -m venv --system-site-packages venv # Optional command: set up a python virtual environment before installing the vizql_data_service_py package source venv/bin/activate # A continuation of the first command for Unix/MacOS users. This activates the virtual environment for Unix/MacOS venv\Scripts\activate # A continuation of the first command for Windows users. This activates the virtual environment for Windows pip install vizql-data-service-py ``` -------------------------------- ### Clone Repository Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/CONTRIBUTING.md Clones the VizQL Data Service repository from GitHub to your local machine. This is the first step in setting up the development environment. ```bash git clone https://github.com/tableau/VizQL-Data-Service.git ``` -------------------------------- ### Query with Match Filter for Strings in Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Apply pattern matching filters to string fields using 'startsWith', 'contains', and 'endsWith' operators. This example filters by 'State/Province' that starts with 'Cal' and contains 'or'. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, MeasureField, DimensionFilterField, MatchFilter, FilterType, Function ) # String pattern matching query = Query( fields=[ DimensionField(fieldCaption="State/Province"), MeasureField(fieldCaption="Sales", function=Function.SUM) ], filters=[ MatchFilter( field=DimensionFilterField(fieldCaption="State/Province"), filterType=FilterType.MATCH, startsWith="Cal", contains="or", exclude=False ) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Run Code Formatting and Linting Checks Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/CONTRIBUTING.md This snippet demonstrates the bash commands used to run automated code formatting (black), import sorting (isort), linting (flake8), and type checking (mypy) for the project. These checks ensure code consistency and quality. ```bash black . isort . flake8 . mypy . ``` -------------------------------- ### Query with Top N Filter in Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Retrieve the top or bottom N records based on a measure value. This example finds the top 10 states by total profit. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, MeasureField, DimensionFilterField, MeasureFilterField, TopNFilter, FilterType, Direction, Function ) # Get top 10 states by profit query = Query( fields=[ DimensionField(fieldCaption="State/Province"), MeasureField(fieldCaption="Profit", function=Function.SUM) ], filters=[ TopNFilter( field=DimensionFilterField(fieldCaption="State/Province"), filterType=FilterType.TOP, howMany=10, fieldToMeasure=MeasureFilterField( fieldCaption="Profit", function=Function.SUM ), direction=Direction.TOP # or Direction.BOTTOM ) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Generate OpenAPI Client Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/CONTRIBUTING.md Generates the OpenAPI client stubs for the VizQL Data Service. This command creates Python code based on the OpenAPI specification, enabling interaction with the service. ```bash bash scripts/generate_stub.sh ``` ```bash scripts\generate_stub.bat ``` -------------------------------- ### Query with Condition Filter - Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Provides an example of filtering dimensions based on aggregated measure conditions using the vizql_data_service_py library. It shows how to display only states where total profit exceeds a specified threshold. Input is a Query object, output is a QueryRequest. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, MeasureField, CalculatedFilterField, ConditionFilter, ConditionalFilterCondition, FilterType, Function ) # Show only states where total profit exceeds threshold query = Query( fields=[ DimensionField(fieldCaption="State/Province", sortPriority=1), MeasureField(fieldCaption="Sales", function=Function.SUM) ], filters=[ ConditionFilter( field=CalculatedFilterField(calculation="[State/Province]"), filterType=FilterType.CONDITION, condition=ConditionalFilterCondition( fieldCaption="Profit", function=Function.SUM, comparison=">", value=50000 ) ) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Filter by Numeric Range in Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Filter query results based on a quantitative numerical range for a specific measure. This example filters sales between $100,000 and $500,000, excluding null values. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, MeasureField, MeasureFilterField, QuantitativeNumericalFilter, FilterType, QuantitativeFilterType, Function ) query = Query( fields=[ DimensionField(fieldCaption="Ship Mode"), MeasureField(fieldCaption="Sales", function=Function.SUM) ], filters=[ QuantitativeNumericalFilter( field=MeasureFilterField(fieldCaption="Sales", function=Function.SUM), filterType=FilterType.QUANTITATIVE_NUMERICAL, quantitativeFilterType=QuantitativeFilterType.RANGE, min=100000, max=500000, includeNulls=False ) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Query with Calculated Fields in Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Create custom calculations within your query using Tableau's calculation syntax. This example defines 'Average Order Value' and 'Profit Margin' as calculated fields. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, CalculatedField ) # Custom calculation for average order value query = Query( fields=[ DimensionField(fieldCaption="Category"), CalculatedField( fieldCaption="Average Order Value", calculation="SUM([Sales]) / COUNTD([Order ID])" ), CalculatedField( fieldCaption="Profit Margin", calculation="SUM([Profit]) / SUM([Sales])" ) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Authenticate and Query Data Sources using Tableau Server Client Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Demonstrates how to sign in to Tableau Server using various authentication methods (PAT, Username/Password, JWT), instantiate the VizQLDataServiceClient, read metadata from a datasource, and execute a query. It requires the `tableauserverclient` library. ```python import tableauserverclient as TSC from tableau_api_client.dataservice import VizQLDataServiceClient, Query, DimensionField, MeasureField, Function, ReadMetadataRequest, QueryRequest, Datasource # Choose one of these auth mechanisms tableau_auth = TSC.PersonalAccessTokenAuth('TOKEN_NAME', 'TOKEN_VALUE', 'SITENAME') # tableau_auth = TSC.TableauAuth('USERNAME', 'PASSWORD', 'SITENAME') # tableau_auth = TSC.JWTAuth('JWT', 'SITENAME') server_url = 'https://SERVER_URL' server = TSC.Server(server_url) # Define a sample datasource for context datasource = Datasource( datasourceLuid="" ) with server.auth.sign_in(tableau_auth): client = VizQLDataServiceClient(server_url, server, tableau_auth) # Define your query fields query = Query( # Example: sample Superstore data source # Aggregate SUM(Sales) by Category fields=[ DimensionField(fieldCaption="Category"), MeasureField(fieldCaption="Sales", function=Function.SUM), ] ) # Step 1: Read metadata read_metadata_request = ReadMetadataRequest( datasource=datasource ) # Assuming read_metadata is a valid object available in scope # read_metadata_response = read_metadata.sync( # client=client, body=read_metadata_request # ) # print(f"Read Metadata Response: {read_metadata_response}") # Step 2: Execute query query_request = QueryRequest( query=query, datasource=datasource ) # Assuming query_datasource is a valid object available in scope # query_response = query_datasource.sync( # client=client, body=query_request # ) # print(f"Query Datasource Response: {query_response}") ``` -------------------------------- ### VizQL Data Service Client Initialization and Usage Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Demonstrates how to initialize the VizQLDataServiceClient, sign in to Tableau Server, read metadata, and query a data source. ```APIDOC ## Initialize and Use VizQLDataServiceClient ### Description This section covers the initialization of the `VizQLDataServiceClient` and demonstrates a typical workflow involving signing into Tableau Server, reading metadata of a data source, and executing a query against it. ### Method N/A (Client-side Python code) ### Endpoint N/A (Client-side Python code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import tableauserverclient as TSC import ssl from vizql_data_service import ( VizQLDataServiceClient, Datasource, Connection, Query, DimensionField, MeasureField, Function, ReadMetadataRequest, QueryRequest ) # --- Authentication --- tableau_auth = TSC.PersonalAccessTokenAuth('TOKEN_NAME', 'TOKEN_VALUE', 'SITENAME') # Or use: # tableau_auth = TSC.TableauAuth('USERNAME', 'PASSWORD', 'SITENAME') # tableau_auth = TSC.JWTAuth('JWT', 'SITENAME') server_url = 'https://SERVER_URL' server = TSC.Server(server_url) # --- SSL Configuration Options --- # Default (verify_ssl=True) # Disable SSL verification (use with caution): verify_ssl=False # Custom CA bundle: verify_ssl="/path/to/ca-bundle.pem" # Custom SSL context: # ssl_context = ssl.create_default_context() # ssl_context.load_verify_locations(cafile="/path/to/ca-bundle.pem") # client = VizQLDataServiceClient(server_url, server, tableau_auth, verify_ssl=ssl_context) # Initialize client with desired SSL configuration client = VizQLDataServiceClient(server_url, server, tableau_auth, verify_ssl=True) # --- Data Source and Query Definition --- datasource = Datasource( datasourceLuid="", connections=[ Connection( connectionUsername="", connectionPassword="" ) ] ) query = Query( fields=[ DimensionField(fieldCaption="Category"), MeasureField(fieldCaption="Sales", function=Function.SUM), ] ) # --- Sign in and Execute Operations --- with server.auth.sign_in(tableau_auth): # Step 1: Read metadata read_metadata_request = ReadMetadataRequest(datasource=datasource) read_metadata_response = client.read_metadata.sync(body=read_metadata_request) print(f"Read Metadata Response: {read_metadata_response}") # Step 2: Execute query query_request = QueryRequest(query=query, datasource=datasource) query_response = client.query_datasource.sync(body=query_request) print(f"Query Datasource Response: {query_response}") ``` ### Response #### Success Response (200) Response format depends on the operation (`read_metadata` or `query_datasource`). Refer to the OpenAPI schema for detailed response structures. #### Response Example ```json { "example": "Response structure for Read Metadata or Query Datasource" } ``` ``` -------------------------------- ### Create Datasource Instance with Optional Connections Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Instantiates a Datasource object. It can optionally include connection details such as username and password for external data sources. This is a foundational step before performing other operations. ```python from tableau_api_client.dataservice import Datasource, Connection datasource = Datasource( datasourceLuid="", # Optional: Configure connections for external data sources connections=[ Connection( connectionUsername="", connectionPassword="" ) ] ) ``` -------------------------------- ### SSL Configuration Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Details on how to configure SSL verification for the VizQLDataServiceClient to handle certificate issues in different environments. ```APIDOC ## SSL Configuration ### Description This section explains how to configure SSL verification for the `VizQLDataServiceClient`. It's particularly useful in environments with custom certificates, VPNs, or self-signed certificates. ### Method N/A (Client-side Python code) ### Endpoint N/A (Client-side Python code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import tableauserverclient as TSC import ssl from vizql_data_service import VizQLDataServiceClient server_url = 'https://SERVER_URL' tableau_auth = TSC.PersonalAccessTokenAuth('TOKEN_NAME', 'TOKEN_VALUE', 'SITENAME') server = TSC.Server(server_url) # Option 1: Disable SSL verification (for development/testing ONLY) client_no_ssl = VizQLDataServiceClient(server_url, server, tableau_auth, verify_ssl=False) # Option 2: Use a custom CA bundle file client_custom_ca = VizQLDataServiceClient(server_url, server, tableau_auth, verify_ssl="/path/to/ca-bundle.pem") # Option 3: Use a custom SSL context for advanced configurations ssl_context = ssl.create_default_context() # Load a custom CA bundle for self-signed certificates ssl_context.load_verify_locations(cafile="/path/to/ca-bundle.pem") # For mutual TLS authentication, uncomment and provide paths to your client certificates # ssl_context.load_cert_chain(certfile="path/to/your/client.pem", keyfile="path/to/your/client.key") client_custom_context = VizQLDataServiceClient(server_url, server, tableau_auth, verify_ssl=ssl_context) print("SSL configurations applied.") ``` ### Response N/A (Client-side configuration) ### Security Note Disabling SSL verification (`verify_ssl=False`) should only be done in development or testing environments. Always use proper SSL certificates or custom CA bundles in production. ``` -------------------------------- ### Query with Parameters and Bins - Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Demonstrates how to override datasource parameter values at query time and create dynamic bins using the vizql_data_service_py library. It defines fields, parameters, and optionally binning for data aggregation. Input is a Query object, output is a QueryRequest sent to the datasource. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, BinField, CalculatedField, Parameter ) # Use parameters in query query = Query( fields=[ DimensionField(fieldCaption="Category"), CalculatedField( fieldCaption="Binned Profit", calculation="INT([Profit] / [Profit Bin Size]) * [Profit Bin Size]" ) ], parameters=[ Parameter(parameterCaption="Profit Bin Size", value=500) ] ) # Or create dynamic bins query_with_bin = Query( fields=[ BinField(fieldCaption="Profit", binSize=1000, sortPriority=1), MeasureField(fieldCaption="Sales", function=Function.SUM) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Get Datasource Logical Model Source: https://context7.com/tableau/vizql-data-service/llms.txt Retrieve the logical data model of a datasource, including table relationships. This function requires a VizQLDataServiceClient and a Datasource object with its LUID. It returns information about logical tables and their relationships. ```python from vizql_data_service_py import ( VizQLDataServiceClient, GetDatasourceModelRequest, Datasource, get_datasource_model ) # Get datasource logical model datasource = Datasource(datasourceLuid="abc123-datasource-luid") request = GetDatasourceModelRequest(datasource=datasource) response = get_datasource_model.sync(client=client, body=request) # Access logical tables for table in response.logicalTables: print(f"Table: {table.caption}, ID: {table.logicalTableId}") # Access table relationships for rel in response.logicalTableRelationships: print(f"From: {rel.fromLogicalTable.logicalTableId}") print(f"To: {rel.toLogicalTable.logicalTableId}") if rel.expression: for item in rel.expression.relationships: print(f" {item.fromField} {item.operator} {item.toField}") ``` -------------------------------- ### API Call Methods: Sync and Sync Detailed Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Demonstrates the two primary methods for making API calls using the VizQL Data Service SDK: `sync` for retrieving only the response data, and `sync_detailed` for obtaining the response data along with the HTTP status code and headers. This choice depends on whether detailed response information is required. ```python # Assuming client, read_metadata_request, and read_metadata are initialized # Simple way - just get the response data # response_sync = read_metadata.sync(client=client, body=read_metadata_request) # Detailed way - get response data, status code and headers # response_detailed, status, headers = read_metadata.sync_detailed(client=client, body=read_metadata_request) ``` -------------------------------- ### API Method Variations Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Explains the two ways to execute API calls: `sync()` for just the response data and `sync_detailed()` for response data, status code, and headers. ```APIDOC ## API Method Variations ### Description The VizQL Data Service SDK offers two methods for executing API calls: `sync()` and `sync_detailed()`. Choose the method based on whether you need only the response data or additional HTTP details like status codes and headers. ### Method N/A (Client-side Python code) ### Endpoint N/A (Client-side Python code) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python # Assuming 'client', 'read_metadata_request', and 'query_request' are already defined # Method 1: Using sync() - Retrieves only the response data response_sync = client.read_metadata.sync(body=read_metadata_request) print(f"Sync response: {response_sync}") # Method 2: Using sync_detailed() - Retrieves response data, status code, and headers response_detailed, status_code, headers = client.read_metadata.sync_detailed(body=read_metadata_request) print(f"Detailed response: {response_detailed}") print(f"Status Code: {status_code}") print(f"Headers: {headers}") # Both methods apply to other operations like query_datasource query_response_sync = client.query_datasource.sync(body=query_request) query_response_detailed, query_status, query_headers = client.query_datasource.sync_detailed(body=query_request) ``` ### Response #### Success Response (200) - `sync()`: Returns the parsed response data object. - `sync_detailed()`: Returns a tuple containing (response data object, HTTP status code, response headers dictionary). #### Response Example ```json { "example": "Response data structure for sync() method." } ``` ```python # Example for sync_detailed() response parts: # Status Code: 200 # Headers: {'Content-Type': 'application/json', ...} ``` ``` -------------------------------- ### Configure SSL Verification for VizQLDataServiceClient Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Illustrates different methods for configuring SSL certificate verification when initializing the VizQLDataServiceClient. Options include disabling verification, using a custom CA bundle, or providing a custom SSL context for advanced scenarios like mutual TLS authentication. This is crucial for environments with custom certificates or VPNs. ```python from tableau_api_client.dataservice import VizQLDataServiceClient import ssl server_url = 'https://SERVER_URL' tableau_auth = None # Assume auth is already set up # Disable SSL verification (for development/testing only) client_no_ssl = VizQLDataServiceClient(server_url, None, tableau_auth, verify_ssl=False) # Use custom CA bundle client_custom_ca = VizQLDataServiceClient(server_url, None, tableau_auth, verify_ssl="/path/to/ca-bundle.pem") # Use custom SSL context ssl_context = ssl.create_default_context() # Load a custom CA bundle (e.g., for self-signed certificates) ssl_context.load_verify_locations(cafile="/path/to/ca-bundle.pem") # Or load client certificates for mutual TLS authentication # ssl_context.load_cert_chain(certfile="path/to/your/client.pem", keyfile="path/to/your/client.key") client_ssl_context = VizQLDataServiceClient(server_url, None, tableau_auth, verify_ssl=ssl_context) ``` -------------------------------- ### Import Required Modules for VizQL Data Service Source: https://github.com/tableau/vizql-data-service/blob/main/python_sdk/README.md Demonstrates how to import necessary classes and functions from the vizql_data_service_py library for interacting with the VizQL Data Service. ```python from vizql_data_service_py import ( ReadMetadataRequest, QueryRequest, Datasource, Connection, VizQLDataServiceClient, read_metadata, query_datasource, DimensionField, MeasureField, Function, Query ) ``` -------------------------------- ### Query with Advanced Options - Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Demonstrates how to control query behavior with advanced options, such as specifying data format and row limits, using the vizql_data_service_py library. This snippet sets up a QueryRequest with additional options for data retrieval. Input is a Query object and options, output is a QueryRequest. ```python from vizql_data_service_py import ( Query, QueryRequest, QueryDatasourceOptions, ReturnFormat, DimensionField, MeasureField, Function ) # Example usage (assuming 'query', 'datasource', 'query_datasource', 'client' are defined) # options = QueryDatasourceOptions(returnFormat=ReturnFormat.JSON, rowLimit=100) # request = QueryRequest(query=query, datasource=datasource, options=options) # response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Configure SSL Verification Source: https://context7.com/tableau/vizql-data-service/llms.txt Configure SSL verification settings for the VizQLDataServiceClient, allowing for disabling verification, using custom CA bundles, or providing a custom SSL context for enhanced security in corporate environments. ```python import ssl from vizql_data_service_py import VizQLDataServiceClient # Disable SSL verification (development only) client = VizQLDataServiceClient( server_url, server, tableau_auth, verify_ssl=False ) # Use custom CA bundle client = VizQLDataServiceClient( server_url, server, tableau_auth, verify_ssl="/path/to/ca-bundle.pem" ) # Use custom SSL context ssl_context = ssl.create_default_context() ssl_context.load_verify_locations(cafile="/path/to/ca-bundle.pem") # Or load client certificates for mutual TLS # ssl_context.load_cert_chain(certfile="path/to/client.pem", keyfile="path/to/client.key") client = VizQLDataServiceClient( server_url, server, tableau_auth, verify_ssl=ssl_context ) ``` -------------------------------- ### Query Datasource with Advanced Options Source: https://context7.com/tableau/vizql-data-service/llms.txt Construct and execute a query against a datasource with various options like row limits, disaggregation, and debug mode. This function requires a configured client, datasource object, and query definition. ```python query = Query( fields=[ DimensionField(fieldCaption="Category"), MeasureField(fieldCaption="Sales", function=Function.SUM) ] ) options = QueryDatasourceOptions( returnFormat=ReturnFormat.OBJECTS, # or ReturnFormat.ARRAYS rowLimit=1000, disaggregate=False, # Set True for row-level data debug=False, bypassMetadataCache=False, interpretFieldCaptionsAsFieldNames=False ) request = QueryRequest(query=query, datasource=datasource, options=options) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Query with Context Filters - Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Illustrates the use of context filters to create independent filtering that affects other filters, implemented with the vizql_data_service_py library. It demonstrates applying a set filter as a context filter followed by a Top N filter. Input is a Query object, output is a QueryRequest. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, MeasureField, DimensionFilterField, MeasureFilterField, SetFilter, TopNFilter, FilterType, Direction, Function ) # Context filter applied first, then top N within that context query = Query( fields=[ DimensionField(fieldCaption="Sub-Category"), MeasureField(fieldCaption="Sales", function=Function.SUM) ], filters=[ SetFilter( field=DimensionFilterField(fieldCaption="Category"), filterType=FilterType.SET, values=["Furniture"], exclude=False, context=True # This filter executes first ), TopNFilter( field=DimensionFilterField(fieldCaption="Sub-Category"), filterType=FilterType.TOP, howMany=10, fieldToMeasure=MeasureFilterField( fieldCaption="Sales", function=Function.SUM ), direction=Direction.TOP ) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Query with Date Filters (Quantitative and Relative) in Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Demonstrates filtering data using both quantitative date ranges and relative date filters. The quantitative filter selects dates within a specified range, while the relative filter selects data based on a period relative to an anchor date. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, MeasureField, DimensionFilterField, QuantitativeDateFilter, RelativeDateFilter, FilterType, QuantitativeFilterType, PeriodType, DateRangeType, Function ) from datetime import date # Quantitative date filter query_quantitative = Query( fields=[ MeasureField(fieldCaption="Order Date", function=Function.YEAR), MeasureField(fieldCaption="Sales", function=Function.SUM) ], filters=[ QuantitativeDateFilter( field=DimensionFilterField(fieldCaption="Order Date"), filterType=FilterType.QUANTITATIVE_DATE, quantitativeFilterType=QuantitativeFilterType.RANGE, minDate=date(2020, 1, 1), maxDate=date(2023, 12, 31) ) ] ) # Relative date filter query_relative = Query( fields=[ MeasureField(fieldCaption="Order Date", function=Function.MONTH), MeasureField(fieldCaption="Sales", function=Function.SUM) ], filters=[ RelativeDateFilter( field=DimensionFilterField(fieldCaption="Order Date"), filterType=FilterType.DATE, periodType=PeriodType.MONTHS, dateRangeType=DateRangeType.LASTN, rangeN=6, anchorDate=date(2024, 1, 1) ) ] ) ``` -------------------------------- ### Query with Parameters API Source: https://context7.com/tableau/vizql-data-service/llms.txt Allows overriding datasource parameter values at query time. This is useful for dynamically setting parameters like bin sizes or other configurable values within your queries. ```APIDOC ## POST /tableau/vizql-data-service/query ### Description Submits a query to the VizQL data service, allowing for parameter overrides. ### Method POST ### Endpoint /tableau/vizql-data-service/query ### Parameters #### Request Body - **query** (object) - Required - The query object containing fields and parameters. - **fields** (array) - Required - List of fields to include in the query. - **parameters** (array) - Optional - List of parameters to override. - **parameterCaption** (string) - Required - The caption of the parameter. - **value** (any) - Required - The new value for the parameter. - **datasource** (object) - Required - The datasource to query. ### Request Example ```json { "query": { "fields": [ { "fieldCaption": "Category", "type": "DimensionField" }, { "fieldCaption": "Binned Profit", "calculation": "INT([Profit] / [Profit Bin Size]) * [Profit Bin Size]", "type": "CalculatedField" } ], "parameters": [ { "parameterCaption": "Profit Bin Size", "value": 500, "type": "Parameter" } ] }, "datasource": { ... } } ``` ### Response #### Success Response (200) - **results** (array) - The query results. #### Response Example ```json { "results": [ { ... } ] } ``` ``` -------------------------------- ### Query with Advanced Options API Source: https://context7.com/tableau/vizql-data-service/llms.txt Provides control over query behavior, including data format, row limits, and debugging options. ```APIDOC ## POST /tableau/vizql-data-service/query ### Description Submits a query to the VizQL data service with advanced options for controlling query behavior. ### Method POST ### Endpoint /tableau/vizql-data-service/query ### Parameters #### Request Body - **query** (object) - Required - The query object. - **fields** (array) - Required - List of fields to include. - **datasource** (object) - Required - The datasource to query. - **options** (object) - Optional - Advanced options for the query. - **returnFormat** (string) - Optional - The desired return format (e.g., JSON, CSV). - **rowLimit** (integer) - Optional - Maximum number of rows to return. - **debug** (boolean) - Optional - Enables debugging output. ### Request Example ```json { "query": { "fields": [ { "fieldCaption": "Category", "type": "DimensionField" }, { "fieldCaption": "Sales", "function": "SUM", "type": "MeasureField" } ] }, "datasource": { "options": { "returnFormat": "JSON", "rowLimit": 100, "debug": true }, ... } } ``` ### Response #### Success Response (200) - **results** (array) - The query results, formatted according to the specified options. #### Response Example ```json { "results": [ { ... } ] } ``` ``` -------------------------------- ### Access Detailed Response with Status and Headers Source: https://context7.com/tableau/vizql-data-service/llms.txt Access detailed response information, including HTTP status codes and headers, for query and metadata requests. This method allows for granular inspection of the request outcome beyond just the parsed content. ```python from vizql_data_service_py import query_datasource, read_metadata # Get detailed response with status and headers response_obj = query_datasource.sync_detailed(client=client, body=query_request) print(f"Status Code: {response_obj.status_code}") print(f"Headers: {response_obj.headers}") print(f"Content: {response_obj.content}") # Access parsed data if response_obj.parsed: data = response_obj.parsed.data print(f"Rows: {len(data)}") # Also works for metadata metadata_response = read_metadata.sync_detailed(client=client, body=metadata_request) print(f"Metadata Status: {metadata_response.status_code}") ``` -------------------------------- ### Query Tableau Data Source with Aggregations using Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Executes a query against a Tableau published data source, including aggregations, using the VizQL Data Service Python SDK. Supports specifying dimensions and measures with aggregation functions. Requires authentication and the vizql-data-service-py library. ```python from vizql_data_service_py import ( VizQLDataServiceClient, QueryRequest, Query, Datasource, DimensionField, MeasureField, Function, query_datasource ) import tableauserverclient as TSC # Authenticate tableau_auth = TSC.PersonalAccessTokenAuth('TOKEN_NAME', 'TOKEN_VALUE', 'SITENAME') server_url = 'https://your-server.com' server = TSC.Server(server_url) with server.auth.sign_in(tableau_auth): client = VizQLDataServiceClient(server_url, server, tableau_auth) datasource = Datasource(datasourceLuid="abc123-datasource-luid") # Create a simple aggregation query query = Query( fields=[ DimensionField(fieldCaption="Category", sortPriority=1), MeasureField(fieldCaption="Sales", function=Function.SUM), MeasureField(fieldCaption="Profit", function=Function.AVG) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) # Process results for row in response.data: print(row) ``` -------------------------------- ### Query with Table Calculations - Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Shows how to apply table calculations, such as calculating the difference from the previous row, using the vizql_data_service_py library. It defines fields with specific sorting and applies table calculations with dimension references. Input is a Query object, output is a QueryRequest. ```python from vizql_data_service_py import ( Query, QueryRequest, DimensionField, TableCalcField, TableCalcFieldReference, DifferenceTableCalcSpecification, TableCalcType, Function ) # Calculate difference from previous row query = Query( fields=[ DimensionField(fieldCaption="Region", sortPriority=1), DimensionField(fieldCaption="Segment", sortPriority=2), TableCalcField( fieldCaption="Sales", function=Function.SUM, tableCalculation=DifferenceTableCalcSpecification( tableCalcType=TableCalcType.DIFFERENCE_FROM.value, dimensions=[ TableCalcFieldReference(fieldCaption="Region"), TableCalcFieldReference(fieldCaption="Segment") ], relativeTo="PREVIOUS" ) ) ] ) request = QueryRequest(query=query, datasource=datasource) response = query_datasource.sync(client=client, body=request) ``` -------------------------------- ### Query Data Source API Source: https://context7.com/tableau/vizql-data-service/llms.txt Execute queries against published data sources with specified fields, aggregations, and filters. ```APIDOC ## POST /api/query ### Description Executes a query against a specified Tableau published data source. ### Method POST ### Endpoint /api/query ### Parameters #### Request Body - **datasource** (object) - Required - Information about the data source. - **datasourceLuid** (string) - Required - The unique identifier for the data source. - **connections** (array) - Optional - Connection details for the data source. - **connectionUsername** (string) - Optional - The username for connecting to the data source. - **connectionPassword** (string) - Optional - The password for connecting to the data source. - **query** (object) - Required - Defines the query to be executed. - **fields** (array) - Required - The fields to include in the query results. - **fieldCaption** (string) - Required - The display name of the field. - **function** (string) - Optional - The aggregation function to apply (e.g., "SUM", "AVG"). - **sortPriority** (integer) - Optional - The priority for sorting. - **filters** (array) - Optional - Filters to apply to the query. ### Request Example ```json { "datasource": { "datasourceLuid": "abc123-datasource-luid" }, "query": { "fields": [ { "fieldCaption": "Category", "sortPriority": 1 }, { "fieldCaption": "Sales", "function": "SUM" }, { "fieldCaption": "Profit", "function": "AVG" } ] } } ``` ### Response #### Success Response (200) - **data** (array) - An array of result rows. #### Response Example ```json [ {"Category": "Electronics", "Sales": 10000.50, "Profit": 2500.75}, {"Category": "Furniture", "Sales": 8000.00, "Profit": 1500.20} ] ``` ``` -------------------------------- ### Read Tableau Data Source Metadata using Python Source: https://context7.com/tableau/vizql-data-service/llms.txt Retrieves metadata for a Tableau published data source using the VizQL Data Service Python SDK. It requires authentication with Tableau Server and provides details about fields, data types, roles, and formulas. Dependencies include the vizql-data-service-py and tableauserverclient libraries. ```python from vizql_data_service_py import ( VizQLDataServiceClient, ReadMetadataRequest, Datasource, Connection, read_metadata ) import tableauserverclient as TSC # Authenticate with Tableau Server tableau_auth = TSC.PersonalAccessTokenAuth('TOKEN_NAME', 'TOKEN_VALUE', 'SITENAME') server_url = 'https://your-server.com' server = TSC.Server(server_url) with server.auth.sign_in(tableau_auth): # Initialize client client = VizQLDataServiceClient(server_url, server, tableau_auth) # Create datasource with optional connection credentials datasource = Datasource( datasourceLuid="abc123-datasource-luid", connections=[ Connection( connectionUsername="db_user", connectionPassword="db_password" ) ] ) # Read metadata request = ReadMetadataRequest(datasource=datasource) response = read_metadata.sync(client=client, body=request) # Access field metadata for field in response.data: print(f"Field: {field.fieldCaption}, Type: {field.dataType}, Role: {field.fieldRole}") ``` -------------------------------- ### Read Metadata API Source: https://context7.com/tableau/vizql-data-service/llms.txt Retrieve comprehensive metadata about a published data source including field names, data types, roles, and formulas. ```APIDOC ## GET /api/metadata ### Description Retrieves metadata for a specified Tableau published data source. ### Method GET ### Endpoint /api/metadata ### Parameters #### Query Parameters - **datasourceLuid** (string) - Required - The unique identifier for the data source. - **connectionUsername** (string) - Optional - The username for connecting to the data source. - **connectionPassword** (string) - Optional - The password for connecting to the data source. ### Request Example ```json { "datasourceLuid": "abc123-datasource-luid", "connectionUsername": "db_user", "connectionPassword": "db_password" } ``` ### Response #### Success Response (200) - **data** (array) - An array of field metadata objects. - **fieldCaption** (string) - The display name of the field. - **dataType** (string) - The data type of the field (e.g., "string", "integer"). - **fieldRole** (string) - The role of the field (e.g., "dimension", "measure"). #### Response Example ```json { "data": [ { "fieldCaption": "Category", "dataType": "string", "fieldRole": "dimension" }, { "fieldCaption": "Sales", "dataType": "float", "fieldRole": "measure" } ] } ``` ``` -------------------------------- ### Execute Queries Asynchronously Source: https://context7.com/tableau/vizql-data-service/llms.txt Execute queries asynchronously for improved performance in concurrent scenarios. This asynchronous function requires an event loop and a configured VizQLDataServiceClient. It returns the queried data. ```python import asyncio from vizql_data_service_py import ( VizQLDataServiceClient, QueryRequest, Query, DimensionField, MeasureField, Function, query_datasource ) import tableauserverclient as TSC async def execute_async_query(): tableau_auth = TSC.PersonalAccessTokenAuth('TOKEN_NAME', 'TOKEN_VALUE', 'SITENAME') server_url = 'https://your-server.com' server = TSC.Server(server_url) with server.auth.sign_in(tableau_auth): client = VizQLDataServiceClient(server_url, server, tableau_auth) datasource = Datasource(datasourceLuid="abc123-datasource-luid") query = Query( fields=[ DimensionField(fieldCaption="Category"), MeasureField(fieldCaption="Sales", function=Function.SUM) ] ) request = QueryRequest(query=query, datasource=datasource) # Async query execution response = await query_datasource.asyncio(client=client, body=request) return response.data # Run async query results = asyncio.run(execute_async_query()) ```