Power BI is one of the most powerful platforms to analyze, visualize, and share your data insight with people. In this post, I want to walk you through how I integrated Microsoft Power BI into my ReactJS application. I know Microsoft has their demo but I summarize major steps and speed up your tasks in this post.
Here are some key concepts in Power BI we should be familiar with:
Power BI is a platform of enterprise so we couldn't use it by personal account. Make sure your organization is connected to the Microsoft ecosystem. Next, within the organization, actually there're 2 level of permissions:
Microsoft manages integrations by apps. We have to define ourselves as app and register permission based on our need.
To integrate Power BI to your ReactJS Application, we install to install official package from Microsoft.
1npm i powerbi-client-react powerbi-client --save 2
And of course based on the package tutorial https://github.com/microsoft/powerbi-client-react it's simply copy-paste:
1import { PowerBIEmbed } from 'powerbi-client-react'; 2 3<PowerBIEmbed 4 embedConfig = {{ 5 type: 'report', 6 id: '<Report Id>', 7 embedUrl: '<Embed Url>', 8 accessToken: '<Access Token>', 9 tokenType: models.TokenType.Embed, 10 settings: { 11 // ... settings 12 } 13 }} 14 eventHandlers = {} 15 cssClassName = { "reportClass" } 16 getEmbeddedComponent = { (embeddedReport) => { 17 this.report = embeddedReport as Report; 18 }} 19/> 20 21
As you noticed, we need to get the <ReportId>
and <EmbedUrl>
and <AccessToken>
. Let retrieve them.
<ReportId>
should be the easiest one, it's the string after https://app.powerbi.com/groups/me/reports/\[xxx].
This step depends on the configuration of the Microsoft App. I don't have permission to set any permission to the app so I will select the delegated approach. but I recommend in-app permission approach.
1microsoft_app = ConfidentialClientApplication(
2 client_id=CLIENT_ID,
3 client_credential=CLIENT_SECRET,
4 authority=AUTHORITY,
5)
6
7@app.get("/sign-in")
8async def signIn():
9 # Should use microsoft_app.acquire_token_silent(scopes=SCOPES, account=None) instead. I don't have permission to use it.
10 result = microsoft_app.get_authorization_request_url(scopes=SCOPES)
11 return RedirectResponse(result)
12
The method acquire_token_silent method will return directly access_token. but in this case by using get_authorization_request_url I need to define callback URI. after the user authenticates with Microsoft, the URI triggered and add additional code to the URI, we need to have addtional step for it assuming /receive_token is my callback URI:
1@app.get("/receive_token")
2def receive_token(code: str):
3 result = microsoft_app.acquire_token_by_authorization_code(
4 code, scopes=SCOPES, redirect_uri=REDIRECT_URI
5 )
6 if "error" in result:
7 return {"error": result["error_description"]}
8 else:
9 return result["access_token"]
10
From the initialized instance from microsoft and accessToken. we can retrieve embedToken
and embedURL
which is the token that authorizes for client to render a report with its dataset. so we can simply combine and return them in one api call.
1def report_embed_token(access_token):
2 response = requests.post(f"https://api.powerbi.com/v1.0/myorg/reports/{REPORT_ID}/GenerateToken", json={
3 "datasets": [{"id": "your-dataset-id"}],
4 "reports": [{"id": REPORT_ID}]
5 }, headers={
6 "Authorization": f"Bearer {access_token}",
7 "Content-Type": "application/json"
8 })
9 if response.status_code == 200:
10 report = response.json()
11 return report.get("token")
12 else:
13 return None
14
15
16def report_embed_url(access_token):
17 response = requests.get(f"https://api.powerbi.com/v1.0/myorg/reports/{REPORT_ID}", headers={
18 "Authorization": f"Bearer {access_token}",
19 "Content-Type": "application/json"
20 })
21 if response.status_code == 200:
22 report = response.json()
23 return report.get("embedUrl")
24 else:
25 return None
26
27@app.get("/embed")
28async def embed(credentials: HTTPAuthorizationCredentials = Depends(security)):
29 token = credentials.credentials
30
31 if not token:
32 raise HTTPException(status_code=401, detail="Invalid token")
33 else:
34 embed_token = report_embed_token(token)
35 embed_url = report_embed_url(token)
36 return { "embed_token": embed_token, "embed_url": embed_url }
37
Based on that we can successfully render microsoft power BI in our Reactjs application. Maintain a consistent professional tone throughout. Hopefully, the post can give you some keywords and directions to integrate Microsoft Power Bi into ReactJS, also you can check code here https://github.com/tuanhuydev/power-bi-integration. And of course, I'm tuanhuydev, a web app engineer in case you need any help. See you and thanks for your reading.