Overview
Power BI is primarily used for data visualization and business intelligence. It helps users connect to various data sources, transform and model data, and create interactive dashboards and reports to analyze and share insights. Essentially, it turns raw data into actionable insights through visualizations.
So, to fetch fresh data over the connected data source, a refresh is needed; it can be scheduled or manual.
If you want to perform some action based on refresh history, like trigger a refresh on failure or send an email, the Power BI Rest APIs come into play.
Power BI REST APIs allow you to automate tasks like
- Viewing dataset refresh history
- Triggering a dataset refresh
To use these APIs securely, you must first authenticate using Microsoft Azure AD and get an access token.
Authentication with Microsoft Azure
To use Power BI APIs, you need to:
- Register an App in Azure Portal
- Assign Permissions
- Use Python to get the access token
Steps to Register App
-
- Go to Azure Portal
- Navigate to: Azure Active Directory > App registrations > New registration
- Set:
- Name: Any name (e.g., PowerBI-API-App)
- Redirect URI: http://localhost (for desktop app)
- Once created, copy:
- Tenant ID
- Client ID
- Go to Certificates & secrets > Create a new Client Secret
Add API Permissions
- Go to API Permissions > Add a permission > Power BI Service
- Choose Delegated or Application permissions:
- Dataset.Read.All
- Dataset.ReadWrite.All
Get Access Token Using Python
import requests
TENANT_ID = “your-tenant-id”
CLIENT_ID = “your-client-id”
CLIENT_SECRET = “your-client-secret”
SCOPE = “https://analysis.windows.net/powerbi/api/.default”
def get_access_token():
url = f”https://login.microsoftonline.com/{TENANT_ID}/oauth2/v2.0/token”
data = {
“grant_type”: “client_credentials”,
“client_id”: CLIENT_ID,
“client_secret”: CLIENT_SECRET,
“scope”: SCOPE
}
response = requests.post(url, data=data)
return response.json().get(“access_token”)
Power BI API Endpoints
1. Get Dataset Refresh History
GET
https://api.powerbi.com/v1.0/myorg/groups/{groupId}/datasets/{datasetId}/refreshes
Returns the last refreshes for a dataset.
2. Trigger Dataset Refresh
POST
https://api.powerbi.com/v1.0/myorg/groups/{groupId}/datasets/{datasetId}/refreshes
Triggers a new refresh for the dataset.
Use API with Python
Fetch Refresh History
def get_refresh_history(group_id, dataset_id, access_token):
url = f”https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/refreshes”
headers = {
“Authorization”: f”Bearer {access_token}”
}
response = requests.get(url, headers=headers)
return response.json()
Trigger Refresh
def trigger_dataset_refresh(group_id, dataset_id, access_token):
url = f”https://api.powerbi.com/v1.0/myorg/groups/{group_id}/datasets/{dataset_id}/refreshes”
headers = {
“Authorization”: f”Bearer {access_token}”
}
response = requests.post(url, headers=headers)
return response.status_code, response.json()
