Forum Discussion

rjhale's avatar
rjhale
Helper V
5 years ago
Solved

New API Endpoint with DAX Queries

MS recently announced support for DAX queries against published Power BI datasets through a new api endpoint: Announcing the public preview of Power BI REST API support for DAX Queries | Microsoft Power BI Blog | Microsoft Power BI

 

I've attempted the same setup using PowerShell cmdlets, but no matter which DAX query I provide it, I don't get any data back.  The error I receive in PowerShell looks something like this: 


+ $result = Invoke-PowerBIRestMethod -Method Post -URL $requestURL -Bod ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : WriteError: (Microsoft.Power...werBIRestMethod:InvokePowerBIRestMethod) [Invoke-PowerBIRestMe
thod], AggregateException
+ FullyQualifiedErrorId : One or more errors occurred.,Microsoft.PowerBI.Commands.Profile.InvokePowerBIRestMethod

Cannot index into a null array.
+ $parsed.results[0].tables[0].rows | Format-List

 

Here is an example of one of the queries that I recently tried:

$requestURL = "datasets/8e66523b-b39b-42a5-a5b5-0d542365434/executeQueries"

$requestBody = @"
{
    "queries":
    [
        {
        "query": "SUMMARIZE(Proposals, Proposals[DOCUMENT_ID], \"Total\", SUM(Proposals[DOCUMENT_TOTAL_AMT]))"
        }
    ]
}
"@

Login-PowerBI
$result = Invoke-PowerBIRestMethod -Method Post -URL $requestURL -Body $requestBody

$parsed = $result | ConvertFrom-Json
$parsed.results[0].tables[0].rows | Format-List

 

Any thoughts on what I may be doing wrong here?  

  • rjhale's avatar
    rjhale
    5 years ago

    I finally got this partially worked out with the help of one of the very helpful Power BI engineers.  For some reason datasets in My Workspace don't seem to be getting proper build permissions, so I decided to switch to just testing datasets in my v2 workspaces.  

     

    I initally thought that I had to use the format https://api.powerbi.com/v1.0/myorg/groups/{groupId}/datasets/{datasetId} because that is what I'm accustomed to doing.  This will probably change as this gets closer to GA, but for now you actually just remove the parts about the group and reference the dataset directly.  For example: https://api.powerbi.com/v1.0/myorg/datasets/f388a618-2c93-41c5-8528-44c0c1129d70/executeQueries

     

    Once I made that change, I was able to return data from a Powershell script and Postman.  Still not sure about the permssions in My Workspace, but I'll likely never use that anway. 

27 Replies

  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi rjhale 

    Code format looks like as below.

    { “queries”: [{“query”:”<Your DAX Query>“}], “serializerSettings”:{“incudeNulls”: true}}

    Please add the permissions for read and write in API permission in Azure Portal and see if the script then works.

    Please check whether you have enable the permission in Admin portal in Power BI Service. 

    Please check whether you have Build permission to this dataset and check whether this workspace is V2 instead of V1.

    Current limitations in a nutshell:

    1. Only 1 DAX query can be executed per REST API request.
    2. Each DAX query can have only 1 result set.
    3. Result sets are capped at 100k rows.
    4. Supported data types: string, numeric, boolean, blank, datetime and variant. Binary is not supported.
    5. Azure AS and SSAS do not support this DAX REST API.

    Best Regards,
    Rico Zhou

     

    If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.

    • rjhale's avatar
      rjhale
      Helper V

      Thanks for the reply.  I'm using the PowerShell cmdlets, and the documentation states "The Power BI Management cmdlets have the required app permissions to use the DAX REST API".  I don't think I should need adjust any App permissions in Azure because of this.  

       

      We have verified that the Allow XMLA Endpoints and Analyze in Excel setting is enabled for the entire organization.  Also, the account I'm using is the owner of the dataset, so it definitely has build permissions.  I've also tried publishing the dataset to "My Workspace" and a v2 workspace.  It doesn't seem to matter which workspace it's published to.  I get the same error regardless.  

       

      Any other ideas or suggestions?

       

    • rjhale's avatar
      rjhale
      Helper V

      Is there any chance this is only available to first/targeted release tenants or users?  It didn't state it anywhere in the blog post, but I just tested the same dataset in our test tenant and I was able to connect from the Powershell cmdlets.  I'm almost certain that our test tenant is first/targeted release. 

       

      Update: I'm not sure that would be the case either as my account has the targeted options enabed in both our test and production tenants.  

      • Anonymous's avatar
        Anonymous
        Not applicable

        I have exactly the same kind of issue as you rjhale. Same error message.
        I have also verified that the Rest API is enabled in the admin portal and that I have build access to the dataset.

        $requestUrl = 'https://api.powerbi.com/v1.0/myorg/datasets/e500cd5d-4e48-4feb-80d5-33435a5c9a16/executeQueries'

        $requestBody = @"
        { “queries”: [{“query”:”EVALUATE SUMMARIZECOLUMNS('Movements[countryCode]', \"Ship Count\", [shipCount])“}], “serializerSettings”:{“incudeNulls”: true}}
        "@

        Write-Host $requestBody

        Write-Host 'Logging in'
        Login-PowerBI
        Write-Host 'Logged In'
        $result = Invoke-PowerBIRestMethod -Method POST -Url $requestUrl -Body $requestBody
        Resolve-PowerBIError -Last
        Write-Host 'Invoked'
        $result
        $parsed = $result | ConvertFrom-Json
        $parsed.results[0].tables[0].rows | Format-List
        Write-Host 'Done'

         

        I get the following response:


        Logged In
        Invoke-PowerBIRestMethod : One or more errors occurred.
        At C:\Users\lchh\OneDrive - Bunker Holding Group\PowerShell\SampleDaxRestAPI.ps1:26 char:11
        + $result = Invoke-PowerBIRestMethod -Method POST -Url $requestUrl -Bod ...
        + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo : WriteError: (Microsoft.Power...werBIRestMethod:InvokePowerBIRestMethod) [Invoke-PowerBIRestMethod], AggregateException
        + FullyQualifiedErrorId : One or more errors occurred.,Microsoft.PowerBI.Commands.Profile.InvokePowerBIRestMethod

        Exception : System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (Bad Request).
        at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
        at Microsoft.PowerBI.Commands.Profile.InvokePowerBIRestMethod.<InvokeRestMethod>d__35.MoveNext()
        InnerException : False
        Message : Response status code does not indicate success: 400 (Bad Request).
        StackTrace : at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
        at Microsoft.PowerBI.Commands.Profile.InvokePowerBIRestMethod.<InvokeRestMethod>d__35.MoveNext()
        HelpLink :
        Source : System.Net.Http
        ErrorDetails :
        ErrorCategory : WriteError: (Microsoft.Power...werBIRestMethod:InvokePowerBIRestMethod) [Invoke-PowerBIRestMethod], AggregateException
        InvocationInfo : System.Management.Automation.InvocationInfo
        ScriptStackTrace : at <ScriptBlock>, C:\Users\lchh\OneDrive - Bunker Holding Group\PowerShell\SampleDaxRestAPI.ps1: line 26

        Invoked
        Cannot index into a null array.
        At C:\Users\lchh\OneDrive - Bunker Holding Group\PowerShell\SampleDaxRestAPI.ps1:31 char:1
        + $parsed.results[0].tables[0].rows | Format-List
        + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo : InvalidOperation: (:) [], RuntimeException
        + FullyQualifiedErrorId : NullArray

        Done


        Anonymous is there anyway that this is not rolled out to our Power BI tenants?

  • jhayes0128's avatar
    jhayes0128
    Frequent Visitor

    rjhale Anonymous Could you please post your full working code? I am also having the same issues but having a hard time following the fixes in this thread.

     

    My powershell code:

    $requestUrl = "datasets/291666dc-09a2-44e3-ba8b-24b590fd9331/executeQueries"



    $requestBody = @"
    { “queries”: [{“query”:”EVALUATE SUMMARIZE('Calendar','Calendar'[Year],"Days in year",COUNT('Calendar'[Date]))“}], “serializerSettings”:{“incudeNulls”: true}}
    "@



    Login-PowerBI
    $result = Invoke-PowerBIRestMethod -Method Post -Url $requestUrl -Body $requestBody
    $parsed = $result | ConvertFrom-Json
    $parsed.results[0].tables[0].rows | Format-List

     

    Error (same as yours):

    Invoke-PowerBIRestMethod : One or more errors occurred.
    At J:\test.ps1:35 char:11
    + $result = Invoke-PowerBIRestMethod -Method Post -Url $requestUrl -Bod ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : WriteError: (Microsoft.Power...werBIRestMethod:InvokePowerBIRestMethod) [Invoke-PowerBIRestMethod], AggregateExce
    ption
    + FullyQualifiedErrorId : One or more errors occurred.,Microsoft.PowerBI.Commands.Profile.InvokePowerBIRestMethod

     

    The error suggests that the DAX is wrong, but it's copy/pasted from the source .pbix file.

     

    I have tried removing the ' in the DAX. I have tried different urls. Same error every time. I'm losing it over here so any help you can provide is appreciated!!

     

    • rjhale's avatar
      rjhale
      Helper V

      One thing I noticed is that you didn't escape your double quotes in query.  In the blog post they Kay mentions and don’t forget to escape quotation marks with a backslash (\”).  The latest query that I copy and pasted from Power BI Desktop looked like this:

      DEFINE
        VAR __DS0Core = 
          SUMMARIZECOLUMNS(
            'Proposals'[DOCUMENT_ID],
            \"SumDOCUMENT_DIRECT_AMT\", CALCULATE(SUM('Proposals'[DOCUMENT_DIRECT_AMT]))
          )
      
        VAR __DS0PrimaryWindowed = 
          TOPN(501, __DS0Core, 'Proposals'[DOCUMENT_ID], 1)
      
      EVALUATE
        __DS0PrimaryWindowed
      
      ORDER BY
        'Proposals'[DOCUMENT_ID]

       

      Hope that helps.

      • jhayes0128's avatar
        jhayes0128
        Frequent Visitor

        Same error 😥 Would you be able to post your $requestBody?

        $requestBody = @"
        {“queries”: [{“query”:”EVALUATE SUMMARIZE('Calendar','Calendar'[Year],\"Days in year\",COUNT('Calendar'[Date]))“}], “serializerSettings”:{“incudeNulls”: true}}
        "@
  • Anonymous's avatar
    Anonymous
    Not applicable

    Hi All,

    Can someone pls point to what is missing in my approach.I spent lot of time trying to fix this but i coundt so far.

     

    I tried a lot of things but i got a different error now and not sure of the reason.I was able to run dataset refresh and GET methods but unsuccessful with this "executing of DAX"

    Error:

    Error is constantly pointing to something wrong at the client end request and i am not sure what more to fix.

     

    Here is my code:

    I tried the same with refreshes endpoint as below and the service principal was able to refresh the dataset.

    # refresh
    $uri = "https://api.powerbi.com/v1.0/myorg/groups/$GroupId/datasets/$DatasetId/refreshes"
    Invoke-RestMethod -Uri $uri –Headers $headers –Method POST –Verbose

     

    Note: 

    • I also used -Headers in the executequeries rest api but it didnt make a difference
    • I registered an Azure app ,obtained the AppID,secretvalue,tenantID.I provided dataset.read and write permission for the app to call REST api.
    • I created an AAD security group and added the service principal account into it as a member.
    • Installed and imported all MicrosoftPowerBIMgmt modules in powershell
    • Service principal is granted Admin on the dataset it is trying to query.
    • Workspace is  V2 

     

      • Anonymous's avatar
        Anonymous
        Not applicable

        I already tried that abs URL method and it doesnt work either.I get the same 400 (bad request) error.

        Could you please provide all the steps you took to get this working end to end.It will be very helpful for many of us.