### Install and Initialize dscc-gen Source: https://developers.google.com/data-studio/visualization/local-dev Run this command to install dscc-gen and initialize a new visualization project. Ensure npm 5.2.0 or later and gsutil are installed. ```bash npx @google/dscc-gen viz ``` -------------------------------- ### Start Local Development Server Source: https://developers.google.com/data-studio/visualization/local-dev Starts a local development server to preview your visualization in real-time as you make changes. ```bash npm run start ``` -------------------------------- ### Example: Asset Shared with Link Viewer Source: https://developers.google.com/data-studio/integrate/api/reference/types Shows an example of an asset shared with an editor and made viewable by anyone with the link. ```json { "permissions": { "OWNER": { "members": [ "user:gus@example.com" ] }, "EDITOR": { "members": [ "group:gus-team@example.com" ] }, "LINK_VIEWER": { "members": [ "allUsers" ] } }, "etag": "OBr4bWCCtl0" } ``` -------------------------------- ### Full Visualization Configuration Example Source: https://developers.google.com/data-studio/visualization/config-reference A comprehensive example demonstrating the structure of a visualization configuration, including data elements, style options, and interactions. ```json { "data": [{ "id": "concepts", "label": "concepts", "elements": [ { "id": "dimension1", "label": "first dimension", "type": "DIMENSION", "options": { "min": 1, "max": 3, "supportedTypes": ["DEFAULT"] } }, { "id": "metric", "label": "metric", "type": "METRIC", "options": { "min": 1, "max": 3 } } ] }], "style": [ { "id": "colors", "label": "Highlight Colors", "elements": [ { "id": "accentColor", "label": "Accent Color", "type": "SELECT_SINGLE", "defaultValue": "rain", "options": [ { "label": "Summer", "value": "summer" }, { "label": "Fall", "value": "fall" } ] }, { "id": "reverseColor", "label": "Show reverse color", "defaultValue": false, "type": "CHECKBOX" }, { "id": "fillColor", "label": "Fill Color", "defaultValue": { "color": "#0000ff" }, "type": "FILL_COLOR" }, { "id": "textOpacity", "label": "Text Opacity", "defaultValue": 0.2, "type": "OPACITY" }, { "id": "customText", "label": "Custom Text", "defaultValue": "0.2", "type": "TEXTINPUT" } ] }, { "id": "text", "label": "Highlight Text", "elements": [ { "id": "textFontSize", "label": "Font size", "defaultValue": 10, "type": "FONT_SIZE" }, { "id": "font", "label": "Font family", "defaultValue": "Arial", "type": "FONT_FAMILY" } ] } ], "interactions": [ { "id": "interactionsConfigId", "supportedActions": ["FILTER"] } ], "features": { "enableComparisonDateRange": false } } ``` -------------------------------- ### Permissions Example 2 Source: https://developers.google.com/data-studio/integrate/api/reference/types Example of an asset shared with one editor and viewable by anyone with the link. ```APIDOC A Data Studio asset shared with one editor and viewable by anyone with the link. ```json { "permissions": { "OWNER": { "members": [ "user:gus@example.com" ] }, "EDITOR": { "members": [ "group:gus-team@example.com" ] }, "LINK_VIEWER": { "members": [ "allUsers" ] } }, "etag": "OBr4bWCCtl0" } ``` ``` -------------------------------- ### Example manifest.json Source: https://developers.google.com/data-studio/visualization/manifest-reference This is an example of a manifest.json file for a community visualization package, demonstrating the structure and required fields for multiple components. ```json { "name": "ABC Visualizations Package", "organization": "ABC Inc.", "description": "A package of cool visualizations.", "logoUrl": "https://url", "organizationUrl": "https://url", "supportUrl": "https://url", "privacyPolicyUrl": "https://url", "termsOfServiceUrl": "https://url", "packageUrl": "https://url", "devMode": false, "components": [ { "id": "treemap", "name": "Treemap", "description": "Zoomable treemap with filter interactions", "iconUrl": "https://url.png", "infoUrl": "https://url", "resource": { "js": "gs://myViz-bucket-treemap/viz.js", "config": "gs://myViz-bucket-treemap/viz-config.json", "css": "gs://myViz-bucket-treemap/viz.css" } }, { "id": "histogram", "name": "Histogram", "description": "Histogram with filter interactions", "iconUrl": "https://url.png", "resource": { "js": "gs://myViz-bucket-histogram/viz.js", "config": "gs://myViz-bucket-histogram/viz-config.json", "css": "gs://myViz-bucket-histogram/viz.css" } } ] } ``` -------------------------------- ### Permissions Example 1 Source: https://developers.google.com/data-studio/integrate/api/reference/types Example of an asset shared with a three editors, including one owner. ```APIDOC ### Examples A Data Studio asset shared with a three editors: ```json { "permissions": { "OWNER": { "members": [ "user:gus@gmail.com" ] }, "EDITOR": { "members": [ "user:jen@gmail.com", "user:amy@gmail.com", "group:api@googlegroups.com" ] } }, "etag": "BwXe3ECCjl0=" } ``` ``` -------------------------------- ### Example Authentication Response Source: https://developers.google.com/data-studio/connector/reference An example of the response structure for defining a connector's authentication type and an optional help URL. ```json { "type": "USER_TOKEN", "helpUrl": "https://www.example.org/connector-auth-help" } ``` -------------------------------- ### Request Example Source: https://developers.google.com/data-studio/connector/reference An example of a `request` object used for fetching data, including sample configuration parameters, a specific date range, and requested fields. ```javascript { "configParams": { "multiSelectExample": "foo,bar", "singleSelectExample": "Lipsum", "singleTextExample": "Lorem Ipsum", "multiTextExample": "Dolor Sit Amet", "includeCheckExample": "true" }, "dateRange": { "endDate": "2017-07-16", "startDate": "2017-06-19" }, "fields": [ {"name": "count"}, {"name": "family"} ] } ``` -------------------------------- ### getConfig Request Example Source: https://developers.google.com/data-studio/connector/reference Example of a getConfig request for a user whose language is set to Italian. This demonstrates the expected structure for the languageCode parameter. ```javascript { languageCode: "it" } ``` -------------------------------- ### Example `getSchema()` and `getData()` Functions Source: https://developers.google.com/data-studio/connector/advanced-services This example shows how to implement `getSchema` and `getData` functions using BigQuery. It defines a SQL query string and a `getQueryConfig` function that dynamically builds the configuration object based on request parameters, including query parameters for URL and fast_fcp. ```javascript var sqlString = "" + "SELECT " + " _TABLE_SUFFIX AS yyyymm, " + " ROUND(SUM(IF(fcp.start < @fast_fcp, fcp.density, 0)), 4) AS fast_fcp, " + " ROUND(SUM(IF(fcp.start >= 1000 AND fcp.start < 3000, fcp.density, 0)), 4) AS avg_fcp, " + " ROUND(SUM(IF(fcp.start >= 3000, fcp.density, 0)), 4) AS slow_fcp " + "FROM " + " `chrome-ux-report.all.*`, " + " UNNEST(first_contentful_paint.histogram.bin) AS fcp " + "WHERE " + " origin = @url " + "GROUP BY " + " yyyymm " + "ORDER BY " + " yyyymm "; function getQueryConfig(request) { var url = (request.configParams && request.configParams.url); var projectId = (request.configParams && request.configParams.projectId); var authToken = ScriptApp.getOAuthToken(); return DataStudioApp.createCommunityConnector().newBigQueryConfig() .setAccessToken(authToken) .setUseStandardSql(true) .setBillingProjectId(projectId) .setQuery(sqlString) .addQueryParameter('url', bqTypes.STRING, url) .addQueryParameter('fast_fcp', bqTypes.INT64, '' + 1000) .build(); } function getSchema(request) { return getQueryConfig(request); } function getData(request) { return getQueryConfig(request) } ``` -------------------------------- ### Example Linking API URL with BigQuery Data Source Source: https://developers.google.com/data-studio/integrate/linking-api An example demonstrating how to set a report name and configure a BigQuery data source using Linking API parameters. ```url https://datastudio.google.com/reporting/create? c.reportId=12345 &r.reportName=MyNewReport &ds.ds0.connector=bigQuery &ds.ds0.datasourceName=MyNewDataSource &ds.ds0.projectId=project-1234 &ds.ds0.type=TABLE &ds.ds0.datasetId=456 &ds.ds0.tableId=789 ``` -------------------------------- ### Number Opacity Example Source: https://developers.google.com/data-studio/visualization/config-reference Example of a number value for opacity, ranging from 0 to 1 in increments of 0.10. ```json "opacity": 0.2 ``` -------------------------------- ### String Color Example Source: https://developers.google.com/data-studio/visualization/config-reference Example of a string value representing a hex color code. ```json "color": "#0000ff" ``` -------------------------------- ### Complete Data Studio Connector Code Example Source: https://developers.google.com/data-studio/connector/use-a-service-account This is a full example of a Data Studio connector script that uses a service account for BigQuery access. It includes functions for authentication, configuration, fields, schema, and data retrieval. ```javascript var cc = DataStudioApp.createCommunityConnector(); var scriptProperties = PropertiesService.getScriptProperties(); function isAdminUser() { return true; } function getAuthType() { var AuthTypes = cc.AuthType; return cc .newAuthTypeResponse() .setAuthType(AuthTypes.NONE) .build(); } function getConfig(request) { var config = cc.getConfig(); config .newInfo() .setId('generalInfo') .setText('This is an example connector to showcase row level security.'); return config.build(); } function getFields() { var fields = cc.getFields(); var types = cc.FieldType; var aggregations = cc.AggregationType; fields .newDimension() .setId('region') .setName('Region') .setType(types.TEXT); fields .newMetric() .setId('sales') .setName('Sales') .setType(types.NUMBER) .setAggregation(aggregations.SUM); fields .newDimension() .setId('date') .setName('Date') .setType(types.YEAR_MONTH_DAY); return fields; } function getSchema(request) { return {schema: getFields().build()}; } var SERVICE_ACCOUNT_CREDS = 'SERVICE_ACCOUNT_CREDS'; var SERVICE_ACCOUNT_KEY = 'private_key'; var SERVICE_ACCOUNT_EMAIL = 'client_email'; var BILLING_PROJECT_ID = 'project_id'; /** * Copy the entire credentials JSON file from creating a service account in GCP. */ function getServiceAccountCreds() { return JSON.parse(scriptProperties.getProperty(SERVICE_ACCOUNT_CREDS)); } function getOauthService() { var serviceAccountCreds = getServiceAccountCreds(); var serviceAccountKey = serviceAccountCreds[SERVICE_ACCOUNT_KEY]; var serviceAccountEmail = serviceAccountCreds[SERVICE_ACCOUNT_EMAIL]; return OAuth2.createService('RowLevelSecurity') .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth') .setTokenUrl('https://accounts.google.com/o/oauth2/token') .setPrivateKey(serviceAccountKey) .setIssuer(serviceAccountEmail) .setPropertyStore(scriptProperties) .setCache(CacheService.getScriptCache()) .setScope(['https://www.googleapis.com/auth/bigquery.readonly']); } var BASE_SQL = 'SELECT d.region, d.sales, d.date ' 'FROM `datastudio-solutions.row_level_security.data` d ' 'INNER JOIN `datastudio-solutions.row_level_security.access` a ' 'ON d.region = a.region ' 'where a.email=@email'; function getData(request) { var accessToken = getOauthService().getAccessToken(); var serviceAccountCreds = getServiceAccountCreds(); var billingProjectId = serviceAccountCreds[BILLING_PROJECT_ID]; var email = Session.getEffectiveUser().getEmail(); var bqTypes = DataStudioApp.createCommunityConnector().BigQueryParameterType; return cc .newBigQueryConfig() .setAccessToken(accessToken) .setBillingProjectId(billingProjectId) .setUseStandardSql(true) .setQuery(BASE_SQL) .addQueryParameter('email', bqTypes.STRING, email) .build(); } ``` -------------------------------- ### Example: Asset Shared with Editors Source: https://developers.google.com/data-studio/integrate/api/reference/types Illustrates how to define permissions for an asset shared with multiple editors and an owner. ```json { "permissions": { "OWNER": { "members": [ "user:gus@gmail.com" ] }, "EDITOR": { "members": [ "user:jen@gmail.com", "user:amy@gmail.com", "group:api@googlegroups.com" ] } }, "etag": "BwXe3ECCjl0=" } ``` -------------------------------- ### Complete BigQuery Row-Level Security Connector Example Source: https://developers.google.com/data-studio/connector/bigquery-row-level-security This is a complete example of a Data Studio community connector that implements row-level security for BigQuery. It includes authentication, configuration, schema definition, and data retrieval logic. ```javascript var cc = DataStudioApp.createCommunityConnector(); var scriptProperties = PropertiesService.getScriptProperties(); function isAdminUser() { return true; } function getAuthType() { var AuthTypes = cc.AuthType; return cc .newAuthTypeResponse() .setAuthType(AuthTypes.NONE) .build(); } function getConfig(request) { var config = cc.getConfig(); config .newInfo() .setId('generalInfo') .setText('This is an example connector to showcase row level security.'); return config.build(); } function getFields() { var fields = cc.getFields(); var types = cc.FieldType; var aggregations = cc.AggregationType; fields .newDimension() .setId('region') .setName('Region') .setType(types.TEXT); fields .newMetric() .setId('sales') .setName('Sales') .setType(types.NUMBER) .setAggregation(aggregations.SUM); fields .newDimension() .setId('date') .setName('Date') .setType(types.YEAR_MONTH_DAY); return fields; } function getSchema(request) { return {schema: getFields().build()}; } var SERVICE_ACCOUNT_CREDS = 'SERVICE_ACCOUNT_CREDS'; var SERVICE_ACCOUNT_KEY = 'private_key'; var SERVICE_ACCOUNT_EMAIL = 'client_email'; var BILLING_PROJECT_ID = 'project_id'; /** * Copy the entire credentials JSON file from creating a service account in GCP. */ function getServiceAccountCreds() { return JSON.parse(scriptProperties.getProperty(SERVICE_ACCOUNT_CREDS)); } function getOauthService() { var serviceAccountCreds = getServiceAccountCreds(); var serviceAccountKey = serviceAccountCreds[SERVICE_ACCOUNT_KEY]; var serviceAccountEmail = serviceAccountCreds[SERVICE_ACCOUNT_EMAIL]; return OAuth2.createService('RowLevelSecurity') .setAuthorizationBaseUrl('https://accounts.google.com/o/oauth2/auth') .setTokenUrl('https://accounts.google.com/o/oauth2/token') .setPrivateKey(serviceAccountKey) .setIssuer(serviceAccountEmail) .setPropertyStore(scriptProperties) .setCache(CacheService.getScriptCache()) .setScope(['https://www.googleapis.com/auth/bigquery.readonly']); } var BASE_SQL = 'SELECT d.region, d.sales, d.date ' + 'FROM `datastudio-solutions.row_level_security.data` d ' + 'INNER JOIN `datastudio-solutions.row_level_security.access` a ' + 'ON d.region = a.region ' + 'where a.email=@email'; function getData(request) { var accessToken = getOauthService().getAccessToken(); var serviceAccountCreds = getServiceAccountCreds(); var billingProjectId = serviceAccountCreds[BILLING_PROJECT_ID]; var email = Session.getEffectiveUser().getEmail(); var bqTypes = DataStudioApp.createCommunityConnector().BigQueryParameterType; return cc .newBigQueryConfig() .setAccessToken(accessToken) .setBillingProjectId(billingProjectId) .setUseStandardSql(true) .setQuery(BASE_SQL) .addQueryParameter('email', bqTypes.STRING, email) .build(); } ``` -------------------------------- ### Connector Configuration Example Source: https://developers.google.com/data-studio/connector/reference Shows the configuration for various input types like text boxes, select options, and checkboxes. The single-select value can be overridden in reports. ```json { configParams: [ { type: "TEXTINPUT", name: "exampleTextInput", displayName: "Single line text", helpText: "Helper text for single line text", placeholder: "Lorem Ipsum" }, { type: "TEXTAREA", name: "exampleTextArea", displayName: "Text area", helpText: "Helper text for text area", placeholder: "Lorem Ipsum" }, { type: "SELECT_SINGLE", name: "exampleSELECT_SINGLE", displayName: "Select single", helpText: "Helper text for select-single", parameterControl: { allowOverride: true }, options: [ { label: "Lorem foo", value: "lorem" }, { label: "Ipsum bar", value: "ipsum" }, { label: "Sit", value: "amet" } ] }, { type: "SELECT_MULTIPLE", name: "exampleSELECT_MULTIPLE", displayName: "Select multiple", helpText: "Helper text for select-multiple", options: [ { label: "Lipsum", value: "lipsum" }, { label: "Foo Bar", value: "foobar" }, { label: "Dolor Sit", value: "amet" } ] }, { type: "CHECKBOX", name: "exampleCheckbox", displayName: "This is a checkbox", helpText: "Helper text for checkbox" }, { type: "INFO", name: "exampleInfo", text: "Example instructions text used in Info" } ], dateRangeRequired: false } ``` -------------------------------- ### GetSchema Request Example Source: https://developers.google.com/data-studio/connector/reference An example of a JavaScript object used to request the schema, including user-provided values for configuration parameters. Note that SELECT_MULTIPLE values are comma-separated strings and CHECKBOX values are truthy. ```javascript { "configParams": { "exampleSelectMultiple": "foobar,amet", "exampleSelectSingle": "ipsum", "exampleTextInput": "Lorem Ipsum Dolor Sit Amet", "exampleTextArea": "NA", "exampleCheckbox": "true" } } ``` -------------------------------- ### Install dscc Library with npm Source: https://developers.google.com/data-studio/visualization/library Install the dscc library using npm for use in your Data Studio visualization projects. This is the recommended method for managing the library dependency. ```bash npm install --save @google/dscc ``` -------------------------------- ### Initiate Blank Report Creation Source: https://developers.google.com/data-studio/integrate/linking-api Use this URL to start the report creation workflow with a blank report. No specific parameters are required to initiate a blank report. ```url https://datastudio.google.com/reporting/create ``` -------------------------------- ### BigQuery TABLE Configuration Source: https://developers.google.com/data-studio/integrate/linking-api Configure a data source to query a specific BigQuery table. This example uses a table ID. ```URL https://datastudio.google.com/reporting/create? c.reportId=123abc **&ds.ds0.connector=bigQuery &ds.ds0.type=TABLE &ds.ds0.projectId=bigquery-public-data &ds.ds0.datasetId=samples &ds.ds0.tableId=shakespeare &ds.ds0.billingProjectId=myProject** ``` -------------------------------- ### Example Embed URL with Token Parameter Source: https://developers.google.com/data-studio/connector/embed-row-level-security This is an example of how to construct the embed URL for a Data Studio report, including a dynamically generated token value as a URL parameter. This allows the embedded report to receive user-specific filtering information. ```html `https://datastudio.google.com/embed/reporting/REPORT_ID/page/PAGE_ID?config=%7B%22ds0%22%3A%7B%22token%22%3A%22TOKEN_VALUE%22%7D%7D` ``` -------------------------------- ### Example Data Format: Array of Objects Source: https://developers.google.com/data-studio/visualization/library-guide Some visualizations expect data as an array of objects. This format is useful when each row represents a distinct record with named properties. ```javascript var data = [ {'colA': 'hello', 'colB', 'world'}, {'colA': 'hello', 'colB', 'world'} ]; ``` -------------------------------- ### Example Request Config Params Source: https://developers.google.com/data-studio/connector/stepped-configuration User-provided answers are passed via `request.configParams`. This object is undefined for the first `getConfig()` call and contains user answers for subsequent calls. ```javascript { state: 'CA', city: 'mountain_view' } ``` -------------------------------- ### Example Data Format: Array of Arrays Source: https://developers.google.com/data-studio/visualization/library-guide Some visualization libraries expect data as an array of arrays, where each inner array represents a row of data. ```javascript var data = [ ['hello', 1], ['world', 2] ]; ``` -------------------------------- ### BigQuery CUSTOM_QUERY Configuration Source: https://developers.google.com/data-studio/integrate/linking-api Configure a data source using a custom SQL query for BigQuery. This example specifies the SQL statement directly. ```URL https://datastudio.google.com/reporting/create? c.reportId=123abc **&ds.ds0.connector=bigQuery &ds.ds0.type=CUSTOM_QUERY &ds.ds0.projectId=bigquery-public-data &ds.ds0.sql=SELECT%20word%2C%20word_count%20FROM%20%60bigquery-public-data.samples.shakespeare%60 &ds.ds0.billingProjectId=myProject** ``` -------------------------------- ### Link to Community Connector Data Source Source: https://developers.google.com/data-studio/integrate/linking-api Connect to a Community Connector by specifying its connectorId and any required parameters. This example shows how to pass state and city parameters. ```url https://datastudio.google.com/reporting/create? c.reportId=161718pqr **&ds.ds5.connector=community &ds.ds5.connectorId=AqwqXxQshl94nJa0E0-1MsZXQL0DfCsJIMWk7dnx &ds.ds5.state=CA &ds.ds5.city=Sacramento** ``` -------------------------------- ### Example BigQuery Response Data Source: https://developers.google.com/data-studio/connector/reference An example of a BigQuery response containing schema and row data for a sales-related query. ```json { "schema": [ { "name": "OpportunityName", "dataType": "STRING" }, { "name": "IsVerified", "dataType": "BOOLEAN" }, { "name": "Created", "dataType": "STRING" }, { "name": "Amount", "dataType": "NUMBER" } ], "rows": [ { "values": ["Interesting", true, "2017-05-23", "120453.65"] }, { "values": ["SF", false, "2017-03-03", "362705286.92"] }, { "values": ["Spring Sale", true, "2017-04-21", "870.12"] } ], "filtersApplied": false } ``` -------------------------------- ### Configure Multiple Data Sources with Mixed Strategies Source: https://developers.google.com/data-studio/integrate/linking-api This example configures two data sources: one BigQuery data source is replaced entirely, while a Google Analytics data source is updated with a single parameter, using the template for others. ```url https://datastudio.google.com/reporting/create? c.reportId=7890 &r.reportName=MyNewReportWithMultipleDataSources **&ds.ds0.datasourceName=MyNewDataSource &ds.ds0.connector=bigQuery &ds.ds0.type=TABLE &ds.ds0.projectId=bigquery-public-data &ds.ds0.datasetId=samples &ds.ds0.tableId=shakespeare &ds.ds1.viewId=92320289** ``` -------------------------------- ### Build for Production Source: https://developers.google.com/data-studio/visualization/local-dev Builds your visualization project from `./src` to `./build` with caching enabled, optimized for production deployment. ```bash npm run build:prod ``` -------------------------------- ### CONTAINS Filter Example Source: https://developers.google.com/data-studio/connector/reference This example shows how to use the CONTAINS operator to filter data where the 'COUNTRY' field includes the character 'A'. ```json { "operator": "CONTAINS", "type": "INCLUDE", "values": ["A"], "fieldName": "COUNTRY" } ``` -------------------------------- ### Build for Development Source: https://developers.google.com/data-studio/visualization/local-dev Builds your visualization project from `./src` to `./build` with caching disabled, suitable for local development. ```bash npm run build:dev ``` -------------------------------- ### IN_LIST Filter Example Source: https://developers.google.com/data-studio/connector/reference This example shows how to use the IN_LIST operator to filter data where the 'Country' field is either 'USA' or 'CA'. ```json { "operator": "IN_LIST", "type": "INCLUDE", "values": ["USA", "CA"], "fieldName": "Country" } ``` -------------------------------- ### NUMERIC_GREATER_THAN Operator Example Source: https://developers.google.com/data-studio/connector/reference Use the NUMERIC_GREATER_THAN operator to include data where the 'Date' dimension is after a specific value. This example selects dates after 20190101. ```json { "operator": "NUMERIC_GREATER_THAN", "type": "INCLUDE", "values": ["20190101"], "fieldName": "Date" } ``` -------------------------------- ### Using Wildcard Alias for Multiple Data Sources Source: https://developers.google.com/data-studio/integrate/linking-api This example demonstrates how to use the `ds.*` wildcard alias to apply parameters to multiple data sources simultaneously, simplifying URL construction. ```url https://datastudio.google.com/reporting/create? c.reportId=7890 &ds.ds1.projectId=client-project &ds.ds1.datasetId=client-dataset &ds.ds2.projectId=client-project &ds.ds2.datasetId=client-dataset &ds.ds3.projectId=client-project &ds.ds3.datasetId=client-dataset ``` ```url https://datastudio.google.com/reporting/create? c.reportId=7890 &ds.*.projectId=client-project &ds.*.datasetId=client-dataset ``` -------------------------------- ### NUMERIC_LESS_THAN_OR_EQUAL Operator Example Source: https://developers.google.com/data-studio/connector/reference Use the NUMERIC_LESS_THAN_OR_EQUAL operator to filter data where the 'Date' dimension is on or before a specific value. This example includes dates up to and including 20190101. ```json { "operator": "NUMERIC_LESS_THAN_OR_EQUAL", "type": "INCLUDE", "values": ["20190101"], "fieldName": "Date" } ``` -------------------------------- ### NUMERIC_LESS_THAN Operator Example Source: https://developers.google.com/data-studio/connector/reference Use the NUMERIC_LESS_THAN operator to filter data where the 'Date' dimension is strictly before a specific value. This example selects dates before 20190101. ```json { "operator": "NUMERIC_LESS_THAN", "type": "INCLUDE", "values": ["20190101"], "fieldName": "Date" } ``` -------------------------------- ### Example Preconfigured Direct Link URL Source: https://developers.google.com/data-studio/connector/direct-links This is the resulting encoded URL for a direct link to the StackOverflow Questions community connector. It includes pre-populated configuration for the 'data-studio' tag. ```url https://datastudio.google.com/datasources/create?connectorConfig=%7B%22tagged%22%3A%22data-studio%22%2C%22pagesize%22%3A%2225%22%2C%22sort%22%3A%22activity%22%7D&reportTemplateId=1lR9CGfx3uyQp6oz7oAgA1rsqZViA-IQs&connectorId=AKfycbwGMj-oe532y-NEbMHo-KLUCEz0EEGOZj-3lhEgw7q65-hs-T_F9B3Qjw ``` -------------------------------- ### NUMERIC_GREATER_THAN_OR_EQUAL Operator Example Source: https://developers.google.com/data-studio/connector/reference Use the NUMERIC_GREATER_THAN_OR_EQUAL operator to filter data where the 'Date' dimension is on or after a specific value. This example includes dates from 20190101 onwards. ```json { "operator": "NUMERIC_GREATER_THAN_OR_EQUAL", "type": "INCLUDE", "values": ["20190101"], "fieldName": "Date" } ``` -------------------------------- ### IS_NULL Filter Example Source: https://developers.google.com/data-studio/connector/reference This example demonstrates the IS_NULL operator, which filters data to include rows where the 'COUNTRY' field is null. The 'values' field should be empty. ```json { "operator": "IS_NULL", "type": "INCLUDE", "values": [], "fieldName": "COUNTRY" } ``` -------------------------------- ### Define Connector Configuration in getConfig() Source: https://developers.google.com/data-studio/connector/build Implement the getConfig() function to define the user-facing configuration options for the connector. This example shows how to add informational text, a text input for package names, and set the date range requirement. ```javascript // https://developers.google.com/datastudio/connector/reference#getconfig function getConfig() { var config = cc.getConfig(); config .newInfo() .setId('instructions') .setText( 'Enter npm package names to fetch their download count. An invalid or blank entry will revert to the default value.' ); config .newTextInput() .setId('package') .setName( 'Enter a single package name or multiple names separated by commas (no spaces!)' ) .setHelpText('e.g. "googleapis" or "package,somepackage,anotherpackage"') .setPlaceholder(DEFAULT_PACKAGE) .setAllowOverride(true); config.setDateRangeRequired(true); return config.build(); } ``` -------------------------------- ### REGEXP_EXACT_MATCH Filter Example Source: https://developers.google.com/data-studio/connector/reference This example demonstrates the REGEXP_EXACT_MATCH operator, filtering data where the field (unspecified) exactly matches the regular expression '^R[A-Z]*K$'. ```json { "operator": "REGEXP_EXACT_MATCH", "type": "INCLUDE", "values": ["^R[A-Z]*K$"], "fieldName": "" } ``` -------------------------------- ### Set Multiple Parameters and Different Input Types Source: https://developers.google.com/data-studio/connector/data-source-parameters Example of a parameter object demonstrating how to set multiple parameters, including different input types like checkboxes, single-select, multi-select, and text inputs. ```json { "ds0.includeToday": true, "ds0.units": "Metric", "ds1.countries": ["Canada", "Mexico"], "ds1.labelName": "Population" } ``` -------------------------------- ### REGEXP_PARTIAL_MATCH Filter Example Source: https://developers.google.com/data-studio/connector/reference This example uses the REGEXP_PARTIAL_MATCH operator to filter data where the field (unspecified) contains values matching the case-insensitive regular expression 'R[A-Z]*'. ```json { "operator": "REGEXP_PARTIAL_MATCH", "type": "INCLUDE", "values": ["(?i)R[A-Z]*"], "fieldName": "" } ``` -------------------------------- ### Create New Community Connector Project Source: https://developers.google.com/data-studio/connector/local-development Run this command to initiate the creation of a new community connector project using `dscc-gen`. It will prompt for necessary details and set up a new Apps Script project. ```bash npx @google/dscc-gen connector ``` -------------------------------- ### EQUALS Filter Example Source: https://developers.google.com/data-studio/connector/reference This example demonstrates how to use the EQUALS operator to filter data where the 'Country' field exactly matches 'USA'. Ensure the 'values' field is an array. ```json { "operator": "EQUALS", "type": "INCLUDE", "values": ["USA"], "fieldName": "Country" } ``` -------------------------------- ### Example Connector Configuration JSON Source: https://developers.google.com/data-studio/connector/direct-links This JSON object defines the configuration parameters for the Stack Overflow community connector, specifying the tag, page size, and sort order. ```json { "tagged": "data-studio", "pagesize": 25, "sort": "activity" } ``` -------------------------------- ### BETWEEN Operator Example Source: https://developers.google.com/data-studio/connector/reference Use the BETWEEN operator to filter data where a dimension value falls within a specified date range. This example includes data from January 1st to January 31st, 2019. ```json { "operator": "BETWEEN", "type": "INCLUDE", "values": ["20190101", "20190131"], "fieldName": "Date" } ``` -------------------------------- ### Sample Style Element Configuration Source: https://developers.google.com/data-studio/visualization/define-config Defines a single style selector, such as opacity, for the properties panel. Includes a label for tooltips and an optional default value. ```json { "id": "linkOpacity", "label": "Link opacity", "type": "OPACITY", "defaultValue": "0.2" } ``` -------------------------------- ### Sample Features Configuration Source: https://developers.google.com/data-studio/visualization/define-config Enables or disables specific features for the community visualization, like comparison date range functionality. ```json "features": { "enableComparisonDateRange": true } ``` -------------------------------- ### Sample Style Section Configuration Source: https://developers.google.com/data-studio/visualization/define-config Groups multiple style elements to provide headings and logical organization within the properties panel's style section. ```json { "id": "styleGroup1", "label": "Header for style group", "elements": [ // insert Style Elements here ] } ``` -------------------------------- ### Configure BigQuery Connection Source: https://developers.google.com/data-studio/connector/reference Sets up a BigQuery configuration for a community connector, including billing project, query string, standard SQL usage, access token, and query parameters. Ensure you have the necessary BigQuery permissions. ```javascript var bqTypes = DataStudioApp.createCommunityConnector().BigQueryParameterType; var configuration = DataStudioApp.createCommunityConnector().newBigQueryConfig() .setBillingProjectId('billingProjectId') .setQuery('myQueryString') .setUseStandardSql(true) .setAccessToken('myAccessToken') .addQueryParameter('myUrlParameterName', bqTypes.STRING, 'myUrlParameterValue') .build(); ``` -------------------------------- ### Push Production Build to Prod Bucket Source: https://developers.google.com/data-studio/visualization/local-dev Copies the production-ready built files from the `./build` directory to your designated 'prod' Google Cloud Storage bucket. ```bash npm run push:prod ``` -------------------------------- ### Permissions: Get Source: https://developers.google.com/data-studio/integrate/api/reference Retrieves the permissions for a specific asset. ```APIDOC ## GET /assets/{assetName}/permissions ### Description Get permissions for an asset. ### Method GET ### Endpoint /assets/{assetName}/permissions ### Parameters #### Path Parameters - **assetName** (string) - Required - The name of the asset for which to retrieve permissions. ``` -------------------------------- ### Encoded Parameter String Example Source: https://developers.google.com/data-studio/connector/data-source-parameters The resulting URL-encoded string after processing the parameter object. ```text %7B%22ds0.zipcode%22%3A%2294094%22%7D ``` -------------------------------- ### Get Asset Permissions Source: https://developers.google.com/data-studio/integrate/api/reference/permissions/get Retrieves the permissions associated with a specific Data Studio asset. ```APIDOC ## GET /v1/assets/{assetName}/permissions ### Description Get the permissions for a Data Studio asset. ### Method GET ### Endpoint https://datastudio.googleapis.com/v1/assets/{assetName}/permissions ### Parameters #### Path Parameters - **assetName** (string) - Required - The name (ID) of the asset. ### Authorization This request requires the authorized user to have sufficient permissions to view asset permissions and authorization with at least one of the following scopes: Scope --- `https://www.googleapis.com/auth/datastudio.readonly` `https://www.googleapis.com/auth/datastudio` ### Request Body Do not supply a request body with this method. ### Response #### Success Response (200) If successful, this method returns a Permissions object. ``` -------------------------------- ### Branching Paths in Stepped Configuration Source: https://developers.google.com/data-studio/connector/stepped-configuration Implement branching logic in stepped configurations where additional questions are presented based on a user's selection. This example shows an extra 'State' question only if 'USA' is selected for 'Country'. ```javascript var cc = DataStudioApp.createCommunityConnector(); function getConfig(request) { var configParams = request.configParams; var isFirstRequest = configParams === undefined; var config = cc.getConfig(); if (isFirstRequest) { config.setIsSteppedConfig(true); } config .newSelectSingle() .setId('country') .setName('Country') // Set isDynamic to true so any changes to Country will clear the state // selections. .setIsDynamic(true) .addOption(config.newOptionBuilder().setLabel('United States').setValue('USA')) .addOption(config.newOptionBuilder().setLabel('Canada').setValue('CA')); if (!isFirstRequest) { // validate a valid value was selected for configParams.country if (configParams.country === undefined) { cc.newUserError().setText('You must choose a country.').throwException(); } switch (configParams.country) { case 'USA': { config .newSelectSingle() .setId('state') .setName('State') .addOption(config.newOptionBuilder().setLabel('New York').setValue('NY')) .addOption(config.newOptionBuilder().setLabel('Calfornia').setValue('CA')); break; } case 'CA': { // No additional configuration is needed for Canada. break; } default: { cc.newUserError() .setText('You must either select "CA" or "USA"') .throwException(); } } } return config.build(); } ``` -------------------------------- ### dateRange Object Source: https://developers.google.com/data-studio/visualization/library-reference The dateRange object provides the start and end dates for a given date range. ```APIDOC ## dateRange ### Description Provides the start and end dates of a default or comparison date range. ### Fields - **start** (string) - Required - Start date of the date range in YYYYMMDD format. - **end** (string) - Required - End date of the date range in YYYYMMDD format. ``` -------------------------------- ### Load Connector in Data Studio Source: https://developers.google.com/data-studio/connector/use Use this URL to load your connector in Data Studio. Replace HEAD_DEPLOYMENT_ID with your connector's Head Deployment ID obtained from Apps Script. ```html https://datastudio.google.com/datasources/create?connectorId=HEAD_DEPLOYMENT_ID ``` -------------------------------- ### Create BigQuery Configuration Object Source: https://developers.google.com/data-studio/connector/advanced-services Use this snippet to construct a BigQuery configuration object for Data Studio Advanced Services. It demonstrates setting the billing project ID, the query string, enabling Standard SQL, setting an access token, and adding a string query parameter. ```javascript var bqTypes = DataStudioApp.createCommunityConnector().BigQueryParameterType; var configuration = DataStudioApp.createCommunityConnector().newBigQueryConfig() // BigQuery billing project's Id. .setBillingProjectId('billingProjectId') // The query that will be executed. .setQuery('myQueryString') // Set to `true` to use StandardSQL. .setUseStandardSql(true) // The accessToken used for service execution. .setAccessToken('myAccessToken') // Adding a `STRING` query parameter. Other supported types are `BOOL`, // `FLOAT64`, and `INT64`. .addQueryParameter('myUrlParameterName', bqTypes.STRING, 'myUrlParameterValue') .build(); ``` -------------------------------- ### Set Specific Parameter Value Source: https://developers.google.com/data-studio/connector/data-source-parameters Example of a JSON object to set a specific parameter value for 'ds0.zipcode'. ```json { "ds0.zipcode": "94094" } ``` -------------------------------- ### Get Auth Type for None Source: https://developers.google.com/data-studio/connector/auth Returns the Auth Type of the connector as NONE. This indicates no authentication is required. ```javascript /** * Returns the Auth Type of this connector. * @return {object} The Auth type. */ function getAuthTypeNone() { const cc = DataStudioApp.createCommunityConnector(); return cc.newAuthTypeResponse().setAuthType(cc.AuthType.NONE).build(); } ``` -------------------------------- ### Link to Google Cloud Storage (Folder) Source: https://developers.google.com/data-studio/integrate/linking-api Configure a Google Cloud Storage data source to include all files within a specified folder. Set pathType to FOLDER and provide the folder path. ```url https://datastudio.google.com/reporting/create? c.reportId=231908kpf **&ds.ds50.connector=googleCloudStorage &ds.ds50.pathType=FOLDER &ds.ds50.path=MyBucket%2FMyData** ``` -------------------------------- ### Get Auth Type for OAuth2 Source: https://developers.google.com/data-studio/connector/auth Returns the Auth Type of the connector as OAuth2. This is required for OAuth2 authentication. ```javascript /** * Returns the Auth Type of this connector. * @return {object} The Auth type. */ function getAuthTypeOAuth2() { const cc = DataStudioApp.createCommunityConnector(); return cc.newAuthTypeResponse().setAuthType(cc.AuthType.OAUTH2).build(); } ``` -------------------------------- ### Implement getData() to Fetch and Return Data Source: https://developers.google.com/data-studio/connector/build This function is called to get data for the given request. Configuration parameters from `getConfig()` are provided in the `request` argument. It handles data fetching, normalization, formatting, and error handling. ```javascript // https://developers.google.com/datastudio/connector/reference#getdata function getData(request) { request.configParams = validateConfig(request.configParams); var requestedFields = getFields().forIds( request.fields.map(function(field) { return field.name; }) ); try { var apiResponse = fetchDataFromApi(request); var normalizedResponse = normalizeResponse(request, apiResponse); var data = getFormattedData(normalizedResponse, requestedFields); } catch (e) { cc.newUserError() .setDebugText('Error fetching data from API. Exception details: ' + e) .setText( 'The connector has encountered an unrecoverable error. Please try again later, or file an issue if this error persists.' ) .throwException(); } return { schema: requestedFields.build(), rows: data }; } ``` ```javascript /** * Gets response for UrlFetchApp. * * @param {Object} request Data request parameters. * @returns {string} Response text for UrlFetchApp. */ function fetchDataFromApi(request) { var url = [ 'https://api.npmjs.org/downloads/range/', request.dateRange.startDate, ':', request.dateRange.endDate, '/', request.configParams.package ].join(''); var response = UrlFetchApp.fetch(url); return response; } ``` ```javascript /** * Parses response string into an object. Also standardizes the object structure * for single vs multiple packages. * * @param {Object} request Data request parameters. * @param {string} responseString Response from the API. * @return {Object} Contains package names as keys and associated download count * information(object) as values. */ function normalizeResponse(request, responseString) { var response = JSON.parse(responseString); var package_list = request.configParams.package.split(','); var mapped_response = {}; if (package_list.length == 1) { mapped_response[package_list[0]] = response; } else { mapped_response = response; } return mapped_response; } ``` ```javascript /** * Formats the parsed response from external data source into correct tabular * format and returns only the requestedFields * * @param {Object} parsedResponse The response string from external data source * parsed into an object in a standard format. * @param {Array} requestedFields The fields requested in the getData request. * @returns {Array} Array containing rows of data in key-value pairs for each * field. */ function getFormattedData(response, requestedFields) { var data = []; Object.keys(response).map(function(packageName) { var package = response[packageName]; var downloadData = package.downloads; var formattedData = downloadData.map(function(dailyDownload) { return formatData(requestedFields, packageName, dailyDownload); }); data = data.concat(formattedData); }); return data; } ``` -------------------------------- ### InteractionType Filter Example Source: https://developers.google.com/data-studio/visualization/config-reference Configuration for interaction types. Currently, only 'FILTER' is supported, allowing the visualization to be used as a filter. ```json "FILTER" ``` -------------------------------- ### Initiate Blank Report Creation with Name Source: https://developers.google.com/data-studio/integrate/linking-api Initiate the report creation workflow for a blank report and set a specific name for the new report using the `r.reportName` parameter. ```url https://datastudio.google.com/reporting/create?r.reportName=MyNewReport ```