Search code examples
powerbipowerbi-datasource

How to update a data source via the API


I'm using a mix of the powershell powerbi management library and the rest api to update a datasource. (as documented here - https://learn.microsoft.com/en-us/rest/api/power-bi/datasets/updatedatasourcesingroup#datasourceconnectiondetails)

https://api.powerbi.com/v1.0/myorg/groups/{0}/datasets/{1}/Default.UpdateDatasources to update a data source. I'm passing in the workspace id for {0} and the dataset ID for {1}.

$datasets = Get-PowerBIDataset -WorkspaceId $workspaceObj.Id
foreach($dataset in $datasets)
{
    $DatasetId = $dataset.Id.Guid

    $json = 
@'
{{
    "updateDetails": [{{
            "datasourceSelector": {{
                "datasourceType": "AnalysisServices",
                "connectionDetails": {{
                    "server": "{0}",
                    "database": "{1}"
                }}
            }},
            "connectionDetails": {{
                "server": "{0}",
                "database": "{1}"
            }}
        }}
    ]
}}
'@
    $json = [string]::Format($json, $AasServer, $modelName)
    $apiDatasetUrl = [string]::Format('https://api.powerbi.com/v1.0/myorg/groups/{0}/datasets/{1}/Default.UpdateDatasources',$workspaceObj.Id , $DatasetId)
    Invoke-RestMethod -Headers $headers  -Method 'Post' -Body $json -Uri $apiDatasetUrl -ContentType 'application/json'
}

This results in a 404 error:

Dataset {guid} is not found

What am I doing wrong? I cannot understand how the dataset cannot be found, when the guid comes from the Power BI api.

I've also tried including the "datasourceId" and the "gatewayId" in the json body, but this does not have an effect.


Solution

  • The mistake was actually in my JSON, the first connectionDetails is the exact specification of the existing data source. The second connectionDetails contains the details to update. See below for correction (in capitals)

        $json = 
    @'
    {{
        "updateDetails": [{{
                "datasourceSelector": {{
                    "datasourceType": "AnalysisServices",
                    "connectionDetails": {{
                        "server": "MY-OLD-SERVER-NAME",
                        "database": "MY-OLD-MODEL-NAME"
                    }},
          "datasourceId": "{2}",
          "gatewayId": "{3}"
                }},
                "connectionDetails": {{
                    "server": "{0}",
                    "database": "{1}"
                }}
            }}
        ]
    }}