Forum Discussion
How to Pass values to the Power BI Filter via API (while Generating PPTX from Power BI Report)
Hi Team, I am using the Power BI trail account and wants to fetch the filtered Report content. But at the end I am getting long HTML reponse. Below is my Python Code. Please let me know where I am wrong here.
Below is the code-
import requests
def get_access_token(client_id, client_secret, username, password, scope, token_url):
data = {
'grant_type': 'password',
'client_id': client_id,
'client_secret': client_secret,
'username': username,
'password': password,
'scope': scope
}
response = requests.post(token_url, data=data)
print(response.text)
access_token = response.json().get('access_token')
print(access_token)
return access_token
def get_embed_token(access_token, report_id, filters, dataset_id, group_id):
url = f"https://api.powerbi.com/v1.0/myorg/groups/{group_id}/reports/{report_id}/GenerateToken"
headers = {
'Authorization': f'Bearer {access_token}',
'Content-Type': 'application/json'
}
body = {
'accessLevel': 'View',
'datasetId': dataset_id,
'filters': filters # Corrected to pass as a dictionary
}
response = requests.post(url, headers=headers, json=body)
print(response.text)
embed_token = response.json().get('token')
print(embed_token)
return embed_token
def fetch_report_data(emb_url, embed_token):
headers = {'Authorization': f'Bearer {embed_token}',
'Content-Type': 'application/x-www-form-urlencoded'
}
response = requests.get(emb_url, headers=headers)
print(response.status_code)
print(emb_url)
report_data = response.text
#report_data =response.json()
return report_data
def main():
# Power BI credentials and parameters
client_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
client_secret = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
username = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
scope = 'https://analysis.windows.net/powerbi/api/.default'
token_url = 'https://login.microsoftonline.com/65df6efa-f78b-4336-9681-654c7fd66c53/oauth2/v2.0/token'
report_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxx'
group_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
emb_url = f'https://app.powerbi.com/reportEmbed?reportId={report_id}&groupId={group_id}'
dataset_id = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
# Filters to apply
filters = {
'name': 'Id',
'operator': 'eq',
'value': '00018bcgypygtvgt15'
}
# Obtain access token
access_token = get_access_token(client_id, client_secret, username, password, scope, token_url)
# Get embed token
embed_token = get_embed_token(access_token, report_id, filters, dataset_id, group_id)
# Fetch report data
report_data = fetch_report_data(emb_url, embed_token)
print(report_data)
if __name__ == "__main__":
main()