Excellent — connecting to a Power BI workspace using Python lets you automate publishing, refreshing, or managing datasets via the Power BI REST API.
Here’s a full, clean, copy-friendly guide (no code cells, no formatting issues).
You can select all and copy directly into your Python environment.
Connect to Power BI Workspace using Python
Step 1 — Install required Python libraries
pip install requests msal
Step 2 — Set up Azure AD app (Service Principal)
- Go to Azure Portal → Azure Active Directory → App registrations → New registration
- Note down:
- Application (client) ID
- Directory (tenant) ID
- Create a Client Secret under “Certificates & Secrets”.
- In Power BI Service → Admin portal → Tenant settings → Developer settings, enable:
- Allow service principals to use Power BI APIs
- Allow service principals to access Power BI workspaces
- Add your app to the target workspace:
- Power BI → Workspace → Access → Add → Enter app name → Assign role (Admin or Member)
Step 3 — Define authentication details in Python
import requests
import msal
Tenant ID, Client ID, and Client Secret from your Azure AD app
tenant_id = “YOUR_TENANT_ID”
client_id = “YOUR_CLIENT_ID”
client_secret = “YOUR_CLIENT_SECRET”
Power BI API scope and authority
authority = f”https://login.microsoftonline.com/{tenant_id}”
scope = [“https://analysis.windows.net/powerbi/api/.default”]
Create MSAL confidential client app
app = msal.ConfidentialClientApplication(
client_id,
authority=authority,
client_credential=client_secret
)
Get access token
token_result = app.acquire_token_for_client(scopes=scope)
access_token = token_result[“access_token”]
print(“Access token acquired successfully!”)
Step 4 — Connect to Power BI and list all workspaces
headers = {
“Authorization”: f”Bearer {access_token}”
}
response = requests.get(“https://api.powerbi.com/v1.0/myorg/groups”, headers=headers)
if response.status_code == 200:
workspaces = response.json()[“value”]
for ws in workspaces:
print(f”Name: {ws[‘name’]} | ID: {ws[‘id’]}”)
else:
print(“Error:”, response.status_code, response.text)
Step 5 — List all reports in a specific workspace
workspace_id = “YOUR_WORKSPACE_ID”
url = f”https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/reports”
response = requests.get(url, headers=headers)
if response.status_code == 200:
reports = response.json()[“value”]
for report in reports:
print(f”Report: {report[‘name’]} | ID: {report[‘id’]}”)
else:
print(“Error:”, response.status_code, response.text)
Step 6 — (Optional) Upload a new .pbix report to workspace
pbix_file_path = “C:\Reports\FinanceDashboard.pbix”
dataset_display_name = “FinanceDashboard”
url = f”https://api.powerbi.com/v1.0/myorg/groups/{workspace_id}/imports?datasetDisplayName={dataset_display_name}”
with open(pbix_file_path, “rb”) as pbix_file:
response = requests.post(
url,
headers={
“Authorization”: f”Bearer {access_token}”,
“Content-Type”: “application/octet-stream”
},
data=pbix_file
)
if response.status_code in [200, 202]:
print(“Report uploaded successfully!”)
else:
print(“Error:”, response.status_code, response.text)
✅ Notes
- The msal library handles secure Azure AD authentication.
- The access token is valid for about 1 hour — refresh when needed.
- You can perform additional actions using the Power BI REST API (refresh datasets, rebind reports, delete reports, etc.).
- For production automation, store secrets in Azure Key Vault.
Would you like me to extend this with dataset refresh automation (Python script that triggers a refresh and checks its status)?