Forum Discussion
Access Power BI API with Python
- 9 years ago
jb007 wrote:
My requirement is to push real time data into Power BI using Python to first read from a database and then send the data inside a Streaming dataset in Power BI.
The first thing I want is to make a simple "get" call to Power BI.
The official documentation explains the processes of connecting to Power BI via the REST API for either a Client App or a Web App. However, I'm using Python - not sure if that is either a client app or a web app.
Anyway, I am able to get the accessToken using the adal library and the method .acquire_token_with_client_credentials, which asks for authority_uri, tenant, client_id and client_secret (notice this is not asking for username and password). By the way, I've also tried getting the accessToken with .acquire_token_with_username_password, but that didn't work.
Unfortunately, when I use the below code with the obtained accessToken, I get a response 403.#accessToken is received using the adal libary headers = {'Authorization': 'Bearer ' + accessToken, 'Content-Type': 'application/json'} read_datasets = requests.get('https://api.powerbi.com/v1.0/myorg/datasets', headers=headers) #shockingly, this will result in a response 403After reading other stackoverflow posts and looking at console apps, I believe the reason this doesn't work is because there is no user sign-in process.
This thread mentions that using Client Credentials is not enough (it is enough to get the accessToken, but not enough to use the APIs)
Not sure how to proceed, but what I need is perhaps a way to keep using this adal template that gives me the accessToken, and also to provide my username and password (in a silent way, i.e. via the scrip, without GUI), and together with the accessToken, to access the APIs.It is a web app. After registion, Use the client_id and client_secrect to get the accesstoken. What are the client_id and client_secrect in your case? 403 in your case most probably indicates a invalid accesstoken, when dedcoding the token at http://jwt.io, what is the scp(scope)? Normally you'd get access as below according to the premission checked when registering the app.
Techinically it is possible to get the access token without GUI interaction in a silent way, just call the POST API with grant_type=password. Then use the refreshtoken to get token afterwards. Note that it might violate the license compliance if other people use the this token to access the embedded reports. People who access the reports in Power BI service shall have their own accounts/tokens.
However for the first time, AFAIK, you'll always have the GUI consent page and accept it.
HI , I am facing the same issue .
I am using to python script to use powerbi rest api.
1) First I regestered an app as a web app and noted its app id (to be used as client id)
2) I created a secret key for it
3) Gave it the required permissions
4) using the ADAL module , I was able to get the access token
5)But when I use the token in further get requests , I get the "403 : Forbidden" error , usually meaning that unauthorised access
Please help!!!
def sample_query():
print("--------------inside sample query-----------------")
headersData = { 'Authorization': 'Bearer'+tokenString ,
'Content-Type': 'application/json',
'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.106 Safari/537.36" }
#urllib.request.urlopen
request = urllib.request.Request('https://api.powerbi.com/v1.0/myorg/groups',headers=headersData)
print("________________________________")
print(request.get_full_url())
print("________________________________")
response_body = urllib.request.urlopen(request)
print(response_body)here is the query code after I get the auth tokken
- adamwallace38 years ago
Advocate II
This works for me.
Reporting Class: Using single user access with app owns dataclass EmbedToken: def __init__(self, report_id, group_id, settings=None): self.username = 'USER' self.password = 'PASSWORD' self.client_id = 'CLIENT ID' self.report_id = report_id self.group_id = group_id if settings is None: self.settings = {'accessLevel': 'View', 'allowSaveAs': 'false'} else: self.settings = settings self.access_token = self.get_access_token() self.config = self.get_embed_token() def get_access_token(self): data = { 'grant_type': 'password', 'scope': 'openid', 'resource': r'https://analysis.windows.net/powerbi/api', 'client_id': self.client_id, 'username': self.username, 'password': self.password } response = requests.post('https://login.microsoftonline.com/common/oauth2/token', data=data) return response.json().get('access_token') def get_embed_token(self): dest = 'https://api.powerbi.com/v1.0/myorg/groups/' + self.group_id \ + '/reports/' + self.report_id + '/GenerateToken' embed_url = 'https://app.powerbi.com/reportEmbed?reportId=' \ + self.report_id + '&groupId=' + self.group_id headers = {'Authorization': 'Bearer ' + self.access_token} response = requests.post(dest, data=self.settings, headers=headers) self.token = response.json().get('token') return {'token': self.token, 'embed_url': embed_url, 'report_id': self.report_id} def get_report(self): headers = {'Authorization': 'Bearer ' + self.token} dest = 'https://app.powerbi.com/reportEmbed?reportId=' + self.report_id + \ '&groupId=' + self.group_id response = requests.get(dest, data=self.settings, headers=headers) return responseDjango View
def index(request): ... irrelevant Code... conf = EmbedToken(report.get('report_id'), report.get('group_id')) token = conf.get_embed_token() return render(request, 'unfi_breakout/unfi_breakout.html', {'selectedReport': token.get('report_id'), 'embedToken': token.get('token')})HTML
{% extends extension %} {% load staticfiles %} {% block main %} <div id="reportContainer" style="height: 100% "> <script src="{% static 'PowerBi/dist/powerbi.js' %}"></script> <script> var models = window['powerbi-client'].models; var embedConfiguration = { type: 'report', id: '{{ selectedReport }}', embedUrl: 'https://app.powerbi.com/reportEmbed', tokenType: models.TokenType.Embed, accessToken: '{{ embedToken }}', settings: { filterPaneEnabled: false } }; var element = document.getElementById('reportContainer'); var report = powerbi.embed(element, embedConfiguration); </script> </div> </div> {% endblock %}- Anonymous8 years agoNot applicable
Hello
I want to reproduce this part on C# to manage row level security with python code.
Any help ?GenerateTokenRequest generateTokenRequestParameters; // This is how you create embed token with effective identities if (!string.IsNullOrEmpty(username)) { var rls = new EffectiveIdentity(username, new List<string> { report.DatasetId }); if (!string.IsNullOrWhiteSpace(roles)) { var rolesList = new List<string>(); rolesList.AddRange(roles.Split(',')); rls.Roles = rolesList; } // Generate Embed Token with effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view", identities: new List<EffectiveIdentity> { rls }); } else { // Generate Embed Token for reports without effective identities. generateTokenRequestParameters = new GenerateTokenRequest(accessLevel: "view"); } - hprasanth6 years agoNew Member
In this code view.py EmbedToken(report.get() is not defined ??? what is the report attribute in class.please reply thank in advance