I'm in the process of building an app that utilises Power BI Service's Rest API to build PBI dashboards. The documentation for this, however, seems to be sparse and incomplete. Getting an access token isn't, in and of itself, too difficult. If you go to any PBI Rest API doc (e.g. Push Datasets - Datasets PostDataset) and click "Try It" you can find an access token in the Request Preview. The difficult part is to have your code automatically retrieve the right token.
I have found at least one method to make this work, but I copy and pasted it from an online forum, don't exactly understand it, and can't get it to work with app passwords (which is essential). That piece of code is this.
def retrieve_access_token(email_address, password, my_org, client_id):
import adal
authority_url = f'https://login.microsoftonline.com/{my_org}.com'
context = adal.AuthenticationContext(
authority_url,
validate_authority=True,
api_version=None
)
token = context.acquire_token_with_username_password(
resource='https://analysis.windows.net/powerbi/api',
username=email_address,
password=password,
client_id=client_id
)
access_token = 'Bearer ' + token['accessToken']
return access_token
I think that code comes from the MS doc Acquire an access token (Python), but the doc gives no detail on the 'authority' or 'resource' values, which means there's no way to change this code to get it to work better if you can somehow get it to work at all.
I've built another function based on the YouTube video How to Execute Azure REST APIs with Postman, which I think is using a method similar to that outlined in the MS doc Microsoft identity platform and OAuth 2.0 authorization code flow. That code is able to retrieve an access token, and I've configured the Azure app registration with every permission available for Power BI, but it doesn't get any responses from the PBI Rest API, and it's unclear what the token is for. That code is this.
def get_access_token(tenant_id, client_id, client_secret):
url = f"https://login.microsoftonline.com/{tenant_id}/oauth2/token"
payload = {'grant_type': 'client_credentials',
'client_id': client_id,
'client_secret': client_secret,
'resource': 'https://management.azure.com/'}
headers = {'Cookie':
'fpc=Aj6jaa6czgFGoa7atKyYeA7IWmJdAQAAAPp_ctYOAAAA; x-ms-gateway-slice=prod; stsservicecookie=ests'}
response = requests.post(url, headers=headers, data = payload)
return 'Bearer ' + eval(response.text)['access_token']
Does anyone have any idea how to get an access token that works for the PBI Rest API just from using code (Python, if possible), and does anyone know how to get the app passwords to work with it? Doing all of this from Python has been an uphill battle, to say the least, and any help would be greatly appreciated.
NOTE: The my_org part of retrieve_access_token is pseudocode. For it to work you have to find your login.microsoftonline URL. I found that out through trial and error and can't direct you to any further information.