Power BI Rest Datamining Report - no DMR needed

Modified on Tue, 24 Nov at 2:40 PM


TABLE OF CONTENTS


Running a ManagementStudio Datamining Report in Power BI using a Refresh Token

Overview

ManagementStudio Datamining Reports can be consumed directly by Power BI through the Datamining REST endpoint. This article describes a Power Query that authenticates using a ManagementStudio Refresh Token instead of a username and password.


In the example below the Power Query exchanges the long‑lived refresh token for a short‑lived JWT access token, then calls the Datamining Report endpoint to retrieve a two‑tier report: Devices (laptops only) with their linked Applications. The report definition is supplied entirely through request headers, so no saved Datamining Report is required.

Prerequisites

  • A dedicated ManagementStudio service account to be used for reporting.
  • The account must have the Create API Tokens / Certs role group permission in order to create API tokens.
  • The account must have access to the modules and to the project used in the request URL.
  • Refresh Token authentication is the recommended option for scheduled scripts and unattended automation, as access tokens rotate automatically.


Step 1 – Creating the Refresh Token in ManagementStudio

  1. In ManagementStudio, go to Administration > User Accounts and select the reporting service account.

  2. Right‑click the account and choose API Tokens > Create API Refresh Token.

  3. Configure the token options:

    • Token expiry – defaults to 90 days.
    • Access token duration – defaults to 3 hours; set this to 10 minutes (see Access Token Lifetime below).
  4. Click Create API Refresh Token.

  5. Copy the token immediately and store it securely. The token is displayed only once and cannot be recovered later.

  6. To retire the token at any time, select the account and choose API Tokens > Revoke API Refresh Token.

Note: This is the API Refresh Token, not the Auth Token created from the User Accounts ribbon using Create Auth Token. The Auth Token route is the simpler static‑token approach, where the token is pasted directly into the Token header, but it requires the administrator to know the account password and the token does not rotate.


Access Token Lifetime

The refresh token is the long‑lived secret; the access token is the credential that actually travels with every report request. The refresh token design exists precisely so that access tokens are short‑lived and rotate automatically.

Reducing the access token duration from the 3‑hour default to 10 minutes is a straightforward security improvement:

  • Smaller theft window. A captured bearer token – through logs, a proxy, or a screenshot – is only usable for minutes rather than hours.
  • Nothing is lost. The Power Query requests a brand‑new access token on every evaluation, so the longer lifetime is never actually used.
  • No operational cost. Keep the duration comfortably longer than the report execution time. Ten minutes is generous for a two‑tier Devices and Applications report; avoid going below a few minutes if the data source is later widened to very large device counts.


Step 2 – Creating the Power BI Parameters

In Power BI Desktop, go to Transform data > Manage parameters > New Parameter and create the following three parameters:

ParameterTypeExample valueNotes
MS-BaseUrlTexthttps://ms.yourserver.comFull instance URL, no trailing slash
MS-ProjectIdText1MS Project Id (ensure it is stored as text)
MS-RefreshTokenTextToken from Step 1Enable Hidden so it is not exposed on the report

Parameterising the base URL and project Id means a single query can serve Dev and Prod environments by changing parameter values only, with no environment identity hard‑coded in the .pbix file.

Note: Power BI parameter names containing a hyphen must be referenced as #"MS-BaseUrl", #"MS-ProjectId" and #"MS-RefreshToken", as used in the query below. To use bare references instead, name the parameters without hyphens (for example MSBaseUrl).


Step 3 – The Power Query

Open Transform data > Transform data, create a Blank Query, open the Advanced Editor and paste the following. Then click Close & Apply and confirm the expected row count in the Data pane.

let
    // Instance base URL and project come from parameters so one query serves
    // every environment (Dev / QA / Prod) without editing the M code.
    Base       = #"MS-BaseUrl",
    ProjectId  = #"MS-ProjectId",

    // --- 1. Exchange the long-lived refresh token for a short-lived JWT ---
    // ManagementStudio performs a DLL version check on the API, and the
    // apiDllVersion header is mandatory even for REST callers that never
    // load the ManagementStudio DLL. A deliberately high value (9999999.999)
    // satisfies the check regardless of the server's installed version.
    // Do not remove or "tidy" this header - without it the request is rejected.
    TokenBinary = Web.Contents(
        Base,
        [
            RelativePath = ProjectId & "/api/refreshtoken",
            Headers = [
                Accept        = "*/*",
                apiDllVersion = "9999999.999",
                refreshToken  = #"MS-RefreshToken"
            ]
        ]
    ),
    TokenText   = Text.FromBinary(TokenBinary),

    // Accept either a JSON object containing "token" or a raw token string;
    // a stray newline or space inside a JWT causes a 401, so trim whitespace.
    Parsed      = try Json.Document(TokenText) otherwise TokenText,
    AccessToken =
        if Value.Is(Parsed, Record.Type) and Record.HasFields(Parsed, "token") then
            Text.Trim(Parsed[token])
        else if Value.Is(Parsed, Text.Type) then
            Text.Trim(Text.Remove(Parsed, {"#(tab)", "#(cr)", "#(lf)"}))
        else
            error "Unexpected token response shape",

    // --- 2. Run the Datamining Report. The report is defined entirely by ---
    // --- request headers, which is why the report Id in the path is 0.   ---
    // LT-* is the laptop naming convention; desktops and servers are excluded.

    // Filter Expression taken from the Datamining UI Filter statements.
FilterExpression = "Devices_Hostname LIKE 'LT-*'", DataText = Text.FromBinary( Web.Contents( Base, [ RelativePath = ProjectId & "/p/report/Datamining/0/PrefixedName/json", Headers = [ #"Auth-Token" = AccessToken, #"Datamining-Tier1-Module" = "Devices", #"Datamining-Tier1-Fields" = "Hostname, DeviceId", #"Datamining-Tier2-Module" = "Applications", #"Datamining-Tier2-Fields" = "Title, AppId", #"DataSource-FilterExpression" = FilterExpression ] ] ) ), // --- 3. Parse the JSON rows into a Power BI table --- Rows = Table.FromRecords(Json.Document(DataText)) in Rows


How It Works

StageBehaviour
Token exchangeGET {Base}/{projectId}/api/refreshtoken with the refresh token supplied in a request header. ManagementStudio exposes Login, Token, RefreshToken and VerifyToken routes on the API account controller; this call uses the refresh token route to obtain a JWT.
Access tokenA JWT signed by the server, carrying name, issuer, audience, not‑before and expiry claims. Its lifetime is the Access token duration configured in Step 1.
Project selectionThe project is carried only in the URL path (/{pId}/…). The token itself contains no project claim, so the project Id in the path must be correct.
Report executionGET {Base}/{projectId}/p/report/Datamining/{report}/{headerFormat}/{format}. The report Id is 0 because the report is ad‑hoc and fully described by headers; headerFormat is PrefixedName and format is json.
OutputThe JSON rows are converted into a Power BI table. With PrefixedName the returned columns are Devices_Hostname, Devices_DeviceId, Applications_Title and Applications_AppId.


Understanding the Filter Expression

The DataSource-FilterExpression header carries the same filter you would enter on the Advanced Filter & Sort tab of a Datamining Report in the ManagementStudio console. It is passed straight through and executed server‑side, before results are returned, rather than filtering in Power BI after extraction. This keeps the row count small and refreshes fast.

The value used in this article:

Devices_Hostname LIKE 'LT-*'

This returns only devices whose hostname begins with LT-, which is the naming convention used for laptops in this estate. Desktops and servers are excluded from the report entirely.

Syntax rules to observe when changing the filter:

  • Column references must use internal column names, formatted as ModuleName_ColumnName – hence Devices_Hostname, not Hostname.
  • LIKE is case‑insensitive and supports * or % wildcards. 'LT-*' matches a prefix; '*LT-*' would match anywhere in the string.
  • Conditions can be combined using OR, AND, IN, IS NULL and =, as in the documented examples UserMigrations_LastName LIKE 'Gordon*' and UserMigrations_EmployeeId IS NULL.
  • Do not wrap column names in square brackets. Brackets are reserved for tokens such as [Today] and [TimeStamp].
  • Use the Show Internal Column Names button in the Datamining Report ribbon to confirm internal names.


Report Headers Reference

HeaderExamplePurpose
Accept*/*Token request only
apiDllVersion9999999.999ManagementStudio performs a DLL version check on incoming API requests, and this header is required even though Power BI is a pure REST client that never loads the ManagementStudio DLL. Supplying a deliberately high value passes the check regardless of the version installed on the server. The header cannot be omitted, and removing it causes the request to fail.
refreshTokenfrom MS-RefreshTokenExchanged for a short‑lived access token
Auth-TokenThe JWT returned by the token exchangeDocumented authentication header for report endpoints
Datamining-Tier1-ModuleDevicesPrimary tier module
Datamining-Tier1-FieldsHostname, DeviceIdFields to include for the primary tier
Datamining-Tier2-ModuleApplicationsJoined tier module
Datamining-Tier2-FieldsTitle, AppIdFields to include for the joined tier
DataSource-FilterExpressionDevices_Hostname LIKE 'LT-*'Server‑side filter, identical syntax to the Datamining Report Advanced Filter

Tiers must be named sequentially (Tier1, Tier2) with Tier1 as the primary tier. Other useful headers from the same families include DataSource-All, DataSource-SortExpression, DataSource-IncludeArchived and Datamining-TierX-CustomFieldIds.

Scheduling Refreshes

Because the access token is generated fresh on every query evaluation, scheduled refresh requires no credential re‑entry and has no stale‑token problem.

  • Gateway. A On‑premises Data Gateway is required if ManagementStudio is not publicly reachable. Where the instance is published to the internet using a dynamic DNS hostname, confirm that the TLS certificate is trusted by the Power BI Service, otherwise refresh will fail during certificate validation.
  • Refresh token expiry. Set a reminder ahead of the 90‑day expiry, or configure a longer expiry when creating the token.


Troubleshooting

SymptomLikely cause
Unexpected token response shapeThe token endpoint returned neither JSON containing a token field nor a plain string – typically HTML from a login page, indicating an incorrect base URL or project Id.
Token request rejected while other headers look correctThe apiDllVersion header is missing, blank, or lower than the server‑installed version. This header is mandatory for all API consumers, including REST callers with no DLL. Restore the high dummy value.
401 on the report callExpired or revoked refresh token, whitespace inside the JWT, or an incorrect project Id in the path.
Empty result set with no errorThe filter column name does not match the header format. With PrefixedName the column is Devices_Hostname. Verify the internal column name and that the account can see the devices.
Filter matches nothingWildcard form. Confirm LT-* is genuinely the laptop prefix, or test with '*LT-*'.
Missing or unexpected columnsColumns are driven by Datamining-TierX-Fields. Use internal field names where a friendly name fails.
Device rows present but no application dataTier 2 is a joined tier and will only populate where devices have linked Applications.

Security Notes

  • Keep the refresh token in the hidden parameter only. Never inline it in the M code or expose it in a screenshot.
  • Use a dedicated service account scoped to only what the report requires, so it can be revoked without affecting a person.
  • Set the access token duration to the shortest practical value (10 minutes).
  • Revoke and re‑issue the token immediately if it is ever pasted into a support ticket or shared file.
  • For production servers and CI/CD pipelines, certificate authentication is the strongest option and removes stored secrets from scripts entirely.



Further Support

For additional assistance, visit the ManagementStudio Service Desk to search the knowledge base or submit a support ticket.

Was this article helpful?

That’s Great!

Thank you for your feedback

Sorry! We couldn't be helpful

Thank you for your feedback

Let us know how can we improve this article!

Select at least one of the reasons
CAPTCHA verification is required.

Feedback sent

We appreciate your effort and will try to fix the article