Materialise DAX Query Results in a Microsoft Fabric Lakehouse

Query the Capacity Metrics semantic model with DAX through the Power BI executeQueries API and store the results as a Delta table in your lakehouse.

In this article 7 sections
  1. Why query the semantic model
  2. What you need
  3. Run the DAX query through the API
  4. What comes back
  5. Write it to a staging table
  6. Fix the column names
  7. Where this goes next

The Fabric Capacity Metrics app gives you 14 days of history, and you cannot get at the database underneath it. If you want to analyse your capacity usage further back than that, the only way in is the semantic model itself: run DAX queries against it through the Power BI API and store the results in your own lakehouse.

Sometimes you have to be creative as a data engineer. When I walked through the Capacity Metrics app I promised a way to persist its data, and this is the first step: one PySpark notebook that pulls a table out of the semantic model with DAX and writes it to a Delta table.

I Materialized DAX Query Results in Microsoft Fabric! Watch on YouTube

Why query the semantic model

The Capacity Metrics app shows you all kinds of information about the usage of your Fabric capacity, and it is built on a semantic model. The data source behind that model is a Kusto database you cannot access, and there are no APIs for it either. So anything older than 14 days is out of view. On the day I recorded this, Tuesday 20 January, I could look back to Wednesday 7 January and no further.

If you want more history, you have to store the data yourself. And since the database is closed to you, that means querying the semantic model Microsoft gives you, with DAX.

Open the report and click Edit, and the Data pane lists the tables and columns in the model. A few of them are very interesting. The Items table, for example, holds every item on your capacities with its item kind: a warehouse, a Synapse notebook, an LLM plugin for Fabric data agents, and so on.

The Data pane of the Fabric Capacity Metrics report listing tables such as Capacities, CUDetail, Items and MetricsByItem
The tables in the Capacity Metrics semantic model

In practice I would like all of these tables materialised in a lakehouse on my own capacity, so I can look further back in time than the 14 days Microsoft gives me. I start with the Items table here, because it is small and it speaks for itself.

What you need

  • The Capacity Metrics semantic model.
  • Its workspace ID (the “group” in the Power BI API) and its dataset ID. When you open the semantic model in Fabric, both are in the URL: /groups/<workspace id>/datasets/<dataset id>/details.
  • A PySpark notebook and a lakehouse to write to. Mine is called Bronze.

Get a token

The notebook uses requests to call the Power BI API, and it needs a token before the API accepts the call.

Python
import requests

# Get your user token (no app registration needed!)
token = notebookutils.credentials.getToken("https://analysis.windows.net/powerbi/api")

notebookutils is Microsoft’s library in Fabric notebooks. getToken returns a Power BI API token based on the credentials of whoever runs the notebook, and the rest of the notebook uses that token to authenticate its API calls.

Printing the token is quite interesting: you get [REDACTED]. It is an authorisation key, so Fabric will not show it, and it will not end up in your logs either.

Set the constants

Python
# Set constants
DATASET_ID = "<dataset id>"
WORKSPACE_ID = "<workspace id>"
SRC_TABLE = "Items"
TGT_TABLE = "Staging_Items"

Fill in the two IDs from the URL. SRC_TABLE is the table in the semantic model and TGT_TABLE is the table in the lakehouse. I come back to why it is a staging table further down. Rerun this cell every time you change the table names.

Run the DAX query through the API

This cell is the heart of the notebook, and it is still only a little bit of readable code.

Python
url = f"https://api.powerbi.com/v1.0/myorg/groups/{WORKSPACE_ID}/datasets/{DATASET_ID}/executeQueries"

headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}

dax_query = f"""
EVALUATE
{SRC_TABLE}
"""

payload = {
    "queries": [{"query": dax_query}]
}

response = requests.post(url, headers=headers, json=payload)
result = response.json()

# Get the data as Spark DataFrame
rows = result["results"][0]["tables"][0]["rows"]
df = spark.createDataFrame(rows)

Step by step:

  1. The URL calls the executeQueries API on api.powerbi.com for one group (the workspace ID) and one dataset (the dataset ID).
  2. The API only accepts the call with an Authorization header that carries the bearer token from the first cell.
  3. The DAX query is just a piece of text: EVALUATE, a new line, and the source table. EVALUATE Items is the DAX equivalent of select * from items in SQL, so it returns every column and every row in the table that is visible to you.
  4. The payload wraps the query, and requests.post sends it to the URL with the headers.
  5. The rows come out of the JSON response and go into a Spark DataFrame through spark.createDataFrame.

On my capacity the cell ran in about 1.6 seconds, because it calls the Power BI API and waits for the results to come back. A larger table takes longer, depending on how much data has to come across the line.

What comes back

display(df) shows the result: 10 columns and 61 rows.

Notebook table view of the DataFrame with column headers such as Items[ItemName], Items[Key] and Items[Timestamp]
The raw result: every column is named Table[Column]

That is a lot of information about the items on your capacities. There is a capacity ID (my tenant has two capacities I have access to), workspace IDs and names, timestamps, a key (I think a combination of capacity ID and item ID), the item kind (lakehouse, dataset, notebook and so on), the name the user gave the item, and whether the item runs billable operations on your capacities. That makes it a very nice dimension once you start rebuilding the Capacity Metrics model on your own data. That is a job for later, though. For now it is all about storing what the DAX query returns.

Write it to a staging table

Python
df.write.format("delta").mode("overwrite").saveAsTable(f"{TGT_TABLE}")

The data goes into a Delta table in overwrite mode, because this is a staging table. Every day the notebook runs, it dumps the latest 14 days of data into it. When you rebuild the data model for real, you merge the staging table into a historical table. I explained how a merge works in Merging Dataframes in PySpark.

Fix the column names

The first run failed. I did not prepare this demo in advance, as you can see in the video:

AnalysisException: [DELTA_INVALID_CHARACTERS_IN_COLUMN_NAMES] Found invalid character(s) among ' ,;{}()\n\t=' in the column names of your schema.
Invalid column names: Items[Billable type].
Please use other characters and try again.
Alternatively, enable Column Mapping to keep using these characters.

DAX returns every column as Table[Column], and some column names contain spaces, which Delta does not accept. The error suggests column mapping as an alternative, but I went for clean names instead. I added a loop to the end of the DAX cell that does three things for every column: take the text between the square brackets, replace the spaces with underscores, and rename the column.

Python
# Clean column names
for col_name in df.columns:
    # Extract text between [ and ]
    clean_name = col_name.split('[')[1].split(']')[0]
    # Replace spaces with underscores
    clean_name = clean_name.replace(' ', '_')
    # Rename column
    df = df.withColumnRenamed(col_name, clean_name)

Run the DAX cell and display(df) again, and the headers are readable, without brackets or spaces. Billable type is now Billable_type.

Notebook table view with cleaned column headers Billable_type, ItemId, ItemKind, ItemName, Item, Key and Timestamp
After cleaning: plain column names Delta accepts

Now the write works. The first run has to create the table, so it takes a little longer: just under 10 seconds for me. Refresh the Tables folder of the lakehouse and staging_items is there.

Lakehouse explorer showing the staging_items table under Bronze, next to the write cell that finished in 9 seconds
The staging table in the Bronze lakehouse

Where this goes next

That is the whole pattern: a token, one call to executeQueries with an EVALUATE, a DataFrame, cleaned column names and a Delta write. Repeat it for the other tables in the Capacity Metrics model, run the notebook every day and merge each staging table into a historical table. Then you can look back further than the 14 days Microsoft gives you.

Bas Land · Microsoft Data Platform MVP

Bas has spent more than 12 years in the Microsoft data stack. He builds data platforms on Microsoft Fabric, teaches as a Microsoft Certified Trainer and speaks at conferences such as Power BI Gebruikersdagen.

↑↓to move ↵to open escto close