Craft Superset chart in React that leverage on Superset backend
Superset UI is a collection of packages written in React that helps us to connect, get data from Superset backend and display it in the chosen visualization.
The goal of this article is to:
Create Superset charts using Superset-UI to request for data, including authentication.
Assuming that you have a Superset backend running or you could set it up easily using docker as specified in this guide. We will be using sample data provided by the Superset UI.
Enable CORS and authentication
To enable the CORS and authentication, you will need to configure Superset backend. Create a config file superset_config_docker.py
and add it to your PYTHONPATH
. Here is the configuration needed to enable CORS and authentication:
ENABLE_CORS = TrueCORS_OPTIONS = {
'supports_credentials': True,
'allow_headers': ['X-CSRFToken', 'Content-Type', 'Origin', 'X-Requested-With','Accept'],
'resources': [
'/superset/csrf_token/', # auth
'/superset/explore_json/*', # legacy query API
'/api/v1/chart/data', # new query API
],
'origins': ['http://localhost:9001']
}
Update the origins with your Superset client URL.
Create Superset client
import { SupersetClient } from '@superset-ui/core';const client = SupersetClient.configure({
credentials: 'include',
host: 'localhost:8088',
protocol: 'http:',
mode: 'cors',
});client.init();
Update the host with your Superset backend.
Create Superset table
Import the necessary packages provided by @superset-ui:
import { ChartDataProvider, QueryFormData, SuperChart } from '@superset-ui/core';import TableChartPlugin from '@superset-ui/plugin-chart-table';
Register the table chart plugin:
new TableChartPlugin().configure({ key: 'table' }).register();
Configure the Superset chart:
const formData: Partial<QueryFormData> = {
datasource: '3__table',
viz_type: 'table',
url_params: {},
time_range_endpoints: ['inclusive', 'exclusive'],
granularity_sqla: 'ds',
time_grain_sqla: 'P1D',
time_range: '100 years ago : now',
query_mode: 'aggregate',
groupby: ['gender'],
metrics: ['count'],
all_columns: ['name', 'gender'],
percent_metrics: [],
order_by_cols: [],
row_limit: 50000,
order_desc: true,
adhoc_filters: [],
table_timestamp_format: 'smart_date',
color_pn: true,
show_cell_bars: true,
queryFields: {
groupby: 'groupby',
metrics: 'metrics'
},
applied_time_extras: {},
where: '',
having: '',
having_filters: [],
filters: []
};return (
<ChartDataProvider client={client} formData={formData}>
{({ loading, error, payload }) => { if (loading) return <div>Loading...</div>; if (error) return renderError(error); if (payload) {
console.log('payload', payload); return (
<SuperChart
chartType="table"
formData={formData}
queryData={payload.queryData}
width={400}
height={200}
/>
);
} return null; }}
</ChartDataProvider>
);
In the sample above, I am querying an aggregated data of birth_names
, showing the total newborns grouped by gender.
Create Superset bar chart
Using the similar approach above, I am trying to create the visualization in bar chart.
Import the necessary packages provided by @superset-ui:
import { NVD3ChartPreset } from '@superset-ui/legacy-preset-chart-nvd3';
Register the NVD3 chart plugin:
new NVD3ChartPreset().register();
Configure the Superset chart:
const formData: Partial<QueryFormData> = {
datasource: '3__table',
viz_type: 'dist_bar',
url_params: {},
time_range_endpoints: ['inclusive', 'exclusive'],
granularity_sqla: 'ds',
time_range: '100 years ago : now',
metrics: ['count'],
adhoc_filters: [],
groupby: ['gender'],
columns: [],
row_limit: 50000,
color_scheme: 'SUPERSET_DEFAULT',
label_colors: {},
queryFields: {
metrics: 'metrics',
groupby: 'groupby',
columns: 'groupby'
},
show_legend: true,
y_axis_format: 'SMART_NUMBER',
bottom_margin: 'auto',
x_ticks_layout: 'auto',
applied_time_extras: {},
where: '',
having: '',
having_filters: [],
filters: []
};return (
<ChartDataProvider client={client} formData={formData}>
{({ loading, error, payload }) => { if (loading) return <div>Loading...</div>; if (error) return renderError(error); if (payload) {
console.log('payload', payload); return (
<SuperChart
chartType="bar"
formData={formData}
queryData={payload.queryData}
width={400}
height={00}
/>
);
} return null; }}
</ChartDataProvider>
);
And here is the visualization in bar chart.
Using existing chart created from Superset
If you have existing chart, you can simplify the formData as follows:
const formData: Partial<QueryFormData> = {
slice_id: 82,
viz_type: 'dist_bar'
};
The visualization is same as the one created in Superset.
Adding extra filters in existing chart
const formData: Partial<QueryFormData> = {
slice_id: 82,
viz_type: 'dist_bar',
extra_filters: [{
col: 'gender',
op: '==',
val: 'girl'
}]
}
The extra filter is applied to the existing chart.
Cheers 🎉