How to Access Power BI API with Python
Pypowerbi.
Python library for PowerBI. Loosely modelled after the C# PowerBI library to keep things somehow consistent.
Installation (Pypowerbi)
Pypowerbi can be installed using pip.In the Command Prompt, type pip install pypowerbi to install your Python package
Adal
The ADAL for Python library makes it easy for python application to authenticate to Azure Active Directory (ADD) in order to access AAD protected web resources.
Requests
The requests module allows you to send HTTP requests using Python. The HTTP request returns a Response Object with all the response data.
Client_ID
The client ID is the unique application (client) ID assigned to you application by Azure AD when the app was registered.
Access Token.
Access tokens are used in token-based authentication to allow an application to access an API.
Python Script
First step is to import all libraries.
Import adal
Import requests
From pypowerbi.dataset import Column, Table, Dataset
From pypowerbi.client import PowerBIClient
authority_url = ‘https://login.microsoftonline.com/common/’
resource_url = ‘https://analysis.windows.net/powerbi/api‘
api_url = ‘https://login.live.com/oauth20_desktop.srf’
Change these to your credentials
client_id = ‘YOUR CLIENT ID’
username = YOUR USERNAME’
password = ‘YOUR PASSWORD!’
First you need to authenticate using adal
context = adal.AuthenticationContext(authority=authority_url,
validate_authority=True,
api_version=None)
Get your authentication token
token = context.acquire_token_with_username_password(resource=resource_url,
client_id=client_id,
username=username,
password=password)
Create your powerbi api client
client = PowerBIClient(api_url, token)
print(client.token)
Create your columns
columns = []
columns.append(Column(name=’id’, data_type=’Int64′))
columns.append(Column(name=’name’, data_type=’string’))
columns.append(Column(name=’is_interesting‘, data_type=’boolean‘))
columns.append(Column(name=’cost_usd‘, data_type=’double’))
columns.append(Column(name=’purchase_date‘, data_type=’datetime‘))
Create your tables
tables = []
tables.append(Table(name=’AnExampleTableName‘, columns=columns))
Create your dataset
dataset = Dataset(name=’AnExampleDatasetName‘, tables=tables)