共用方式為


將應用程式連線至 GraphQL 的網狀架構 API

注意

適用於 GraphQL 的網狀架構 API Microsoft處於預覽狀態。

若要將應用程式連線到適用於 GraphQL 的 API,您需要三個重要資訊 :用戶端識別碼、租 使用者標識碼,以及 Fabric 中的 GraphQL 端點位址 。 在下列各節中,我們將示範如何建立和擷取您需要的所有詳細數據,以及如何使用範例應用程式存取 API。

必要條件

  • GraphQL 的 API 目前需要應用程式使用 Microsoft Entra 進行驗證。 您的應用程式必須適當地註冊並設定,才能對 Fabric 執行 API 呼叫。 如需詳細資訊,請參閱 在 Azure 中建立Microsoft Entra 應用程式。

  • 呼叫 API 的已驗證用戶必須是具有參與者角色的 API 和數據源專案所在的工作區成員。 如需詳細資訊,請參閱 為使用者提供工作區的存取權

  • 線上應用程式之前,您必須在 Fabric 中擁有 GraphQL 的 API。 如需詳細資訊,請參閱 在 Fabric 中建立 GraphQL 的 API 並新增數據

建立 Microsoft Entra 應用程式

在下列步驟中,我們會示範如何在 Entra 中設定 ReactJS 應用程式的支援。

  1. 登入 Azure 入口網站

  2. 搜尋並選取 Microsoft Entra ID

  3. 從 [ 管理] 列表中,選取 [ 應用程式註冊]。

  4. 選取新增註冊

  5. 填寫必要資訊:

    • 名稱 -輸入應用程式的名稱。

    • 支援的帳戶類型 - 選取您想要應用程式支援的帳戶。

    • (選擇性) 重新導向 URI - 視需要輸入 URI。

  6. 選取註冊。 您的Microsoft Entra 應用程式 應用程式 (用戶端) 識別碼目錄 (租使用者) 識別碼 值會顯示在 [摘要] 方塊中。 在稍後需要這些值時記錄這些值。

  7. 從 [管理] 列表中,選取 [API 許可權],然後選取 [新增許可權]。

  8. 新增 PowerBI 服務、選取 [委派的許可權],然後選取 Item.Execute.AllDatamart.ReadWrite.All 許可權。 請確定不需要管理員同意。

  9. 回到 [管理] 列表,選取 [驗證],選取 [新增平臺],然後選取 [單頁應用程式]。

  10. 針對本機開發目的,請在 [重新導向 URI] 底下新增 http://localhost:3000 ,並確認已針對授權碼流程啟用應用程式,並具有適用於程式代碼交換的證明金鑰 (PKCE) 。 選取 [設定] 按鈕以儲存變更。

  11. 回到 [授權],向下捲動至 [進階設定],然後在 [允許公用用戶端流程] 底下,針對 [啟用下列行動和桌面流程] 選取 []。

設定應用程式存取的範例 GraphQL API

在此範例中,我們會建立 GraphQL API,將範例 Lakehouse 數據公開給用戶端。

  1. 在網狀架構入口網站中,從導覽列底部的工作負載切換器選取 [資料工程師]。 如果您位於 Fabric 首頁,您也可以選取 資料工程師 卡片。

    網狀架構工作負載切換器的螢幕快照。

  2. 在 資料工程師 體驗中,選取 [使用範例],然後在 [Lakehouse] 底下,選取 [公用假日] 以自動建立具有公用假日數據的新 Lakehouse

    選取範例 Data Lakehouse 選項的螢幕快照。

  3. 遵循建立 GraphQL API 的步驟,建立新的 GraphQL API,然後選取您建立的 Lakehouse。 新增公用假日數據表,讓用戶端存取此數據。

    將範例 Lakehouse 新增為 GraphQL 數據源的螢幕快照。

  4. 使用下列範例查詢,在 API 編輯器測試 GraphQL API。 這是我們在 React 用戶端應用程式中使用的相同查詢:

     query {
       publicholidays (filter: {countryRegionCode: {eq:"US"}, date: {gte: "2024-01-01T00:00:00.000Z", lte: "2024-12-31T00:00:00.000Z"}}) {
         items {
           countryOrRegion
           holidayName
           date
         }
       }
     }
    
  5. 選取 API 專案工具列上的 [複製端點 ]。

    API 專案的工具列選項螢幕快照。

  6. 在 [ 複製連結] 畫面中,選取 [ 複製]。

    [複製連結] 對話框畫面的螢幕快照,其中顯示要選取 [複製] 的位置。

  7. 作為稍早記錄之 Entra 應用程式的用戶端識別碼租使用者識別碼,請複製端點 URI,以供稍後使用。

設定 React 應用程式以存取公用假日 API

  1. 我們使用現有的 React 應用程式作為起點。 遵循建立 React 單頁應用程式教學課程 中的所有步驟,並準備進行驗證 ,以使用已設定的 Entra 驗證來建立 React 專案,包括新增至專案結構所需的其他檔案和資料夾。 我們只需要變更三個檔案,以針對 GraphQL 使用案例調整應用程式。

  2. src 資料夾中,開啟 authConfig.js 檔案,並以下列代碼段取代檔案的內容:

     /*
      * Copyright (c) Microsoft Corporation. All rights reserved.
      * Licensed under the MIT License.
      */
    
     import { LogLevel } from "@azure/msal-browser";
    
     /**
      * Configuration object to be passed to MSAL instance on creation. 
      * For a full list of MSAL.js configuration parameters, visit:
      * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/configuration.md 
      */
    
     export const graphqlConfig = {
         graphqlEndpoint: "`Enter_the_GraphQL_Endpoint_Here"
     };
    
     export const msalConfig = {
         auth: {
             clientId: "Enter_the_Application_Id_Here",
             authority: "https://login.microsoftonline.com/Enter_the_Tenant_Info_Here",
             redirectUri: "http://localhost:3000",
         },
         cache: {
             cacheLocation: "sessionStorage", // This configures where your cache will be stored
             storeAuthStateInCookie: false, // Set this to "true" if you are having issues on IE11 or Edge
         },
         system: {	
             loggerOptions: {	
                 loggerCallback: (level, message, containsPii) => {	
                     if (containsPii) {		
                         return;		
                     }		
                     switch (level) {
                         case LogLevel.Error:
                             console.error(message);
                             return;
                         case LogLevel.Info:
                             console.info(message);
                             return;
                         case LogLevel.Verbose:
                             console.debug(message);
                             return;
                         case LogLevel.Warning:
                             console.warn(message);
                             return;
                         default:
                             return;
                     }	
                 }	
             }	
         }
     };
    
     /**
      * Scopes you add here will be prompted for user consent during sign-in. 
      * By default, MSAL.js will add OIDC scopes (openid, profile, email) to any login request.
      * For more information about OIDC scopes, visit: 
      * https://docs.microsoft.com/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes
      */
     export const loginRequest = {
         scopes: ["https://analysis.windows.net/powerbi/api/Item.Execute.All","https://analysis.windows.net/powerbi/api/Datamart.ReadWrite.All"]
     };
    
     /**
      * Add here the scopes to request when obtaining an access token for MS Graph API. For more information, see:
      * https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-browser/docs/resources-and-scopes.md
      */
     export const graphConfig = {
         graphMeEndpoint: "https://graph.microsoft.com/v1.0/me",
     };
    

    如您在上述程式代碼中所見,請務必使用正確的範圍來存取應用程式。 在我們的案例 https://analysis.windows.net/powerbi/api/Item.Execute.All 中, 與 https://analysis.windows.net/powerbi/api/Datamart.ReadWrite.All

    重要

    在適用於 GraphQL 預覽 Microsoft 的網狀架構 API 期間,範圍可能會變更。

  3. 將下列值取代為來自 Microsoft Entra 系統管理中心的值。

    • clientId - 應用程式的識別碼,也稱為用戶端。 將取代 Enter_the_Application_Id_Here先前從已註冊的 Entra 應用程式概觀頁面記錄的應用程式 (client) 識別碼 值。
    • authority - 這是由兩個部分組成:
      • 執行個體是雲端提供者的端點。 在國家雲端中檢查不同的可用端點。
      • 租用戶識別碼是註冊應用程式的租用戶識別碼。 將 Enter_the_Tenant_Info_Here 取代為先前從註冊應用程式的概觀頁面記錄的目錄 (租用戶) 識別碼值。
    • graphQLEndpoint - GraphQL 端點的網狀架構 API。 將取代 Enter_the_GraphQL_Endpoint_Here 為稍早記錄的 GraphQL API 端點。
  4. 儲存檔案。

  5. 在相同的 src 資料夾中,開啟 App.js 檔案,並以下列代碼段取代檔案的內容:

     import React, { useState } from 'react';
     import { PageLayout } from './components/PageLayout';
     import { loginRequest, graphqlConfig } from './authConfig';
     import { ProfileData } from './components/ProfileData';
     import { AuthenticatedTemplate, UnauthenticatedTemplate, useMsal } from '@azure/msal-react';
     import './App.css';
     import Button from 'react-bootstrap/Button';
     import Spinner from 'react-bootstrap/Spinner';
    
     /**
     * Renders information about the signed-in user or a button to retrieve data about the user
     */
     const ProfileContent = () => {
       const { instance, accounts } = useMsal();
       const [graphqlData, setGraphqlData] = useState(null);
       const [display, setDisplay] = useState(false);
    
       function RequestGraphQL() {
           // Silently acquires an access token which is then attached to a request for GraphQL data
           instance
               .acquireTokenSilent({
                   ...loginRequest,
                   account: accounts[0],
               })
               .then((response) => {
                   callGraphQL(response.accessToken).then((response) => setGraphqlData(response));
               });
       }
    
     async function callGraphQL(accessToken) {
       setDisplay(true);
       const query = `query {
         publicholidays (filter: {countryRegionCode: {eq:"US"}, date: {gte: "2024-01-01T00:00:00.000Z", lte: "2024-12-31T00:00:00.000Z"}}) {
           items {
             countryOrRegion
             holidayName
             date
           }
         }
       }`;
       fetch(graphqlConfig.graphqlEndpoint, {
               method: 'POST',
               headers: {
                   'Content-Type': 'application/json',
                   'Authorization': `Bearer ${accessToken}`,
               },
               body: JSON.stringify({ 
                   query: query
               })
           })
           .then((res) => res.json())
           .then((result) => setGraphqlData(result));
     }
    
       return (
           <>
               <h5 className="card-title">Welcome {accounts[0].name}</h5>
               <br/>
               {graphqlData ? (
                   <ProfileData graphqlData={graphqlData} />
               ) : (
                   <Button variant="primary" onClick={RequestGraphQL}>
                       Query Fabric API for GraphQL Data 
                       {display ? (
                             <Spinner
                                 as="span"
                                 animation="border"
                                 size="sm"
                                 role="status"
                                 aria-hidden="true"
                             />
                         ) : null}
                   </Button>
               )}
           </>
       );
     };
    
     /**
     * If a user is authenticated the ProfileContent component above is rendered. Otherwise a message indicating a user is not authenticated is rendered.
     */
     const MainContent = () => {
       return (
           <div className="App">
               <AuthenticatedTemplate>
                   <ProfileContent />
               </AuthenticatedTemplate>
    
               <UnauthenticatedTemplate>
                   <h5>
                       <center>
                           Please sign-in to see your profile information.
                       </center>
                   </h5>
               </UnauthenticatedTemplate>
           </div>
       );
     };
    
     export default function App() {
       return (
           <PageLayout>
               <center>
                   <MainContent />
               </center>
           </PageLayout>
       );
     }
    
  6. 儲存檔案。

  7. 最後,在 src/components 資料夾下,開啟 ProfileData.jsx 檔案,並將檔案的內容取代為下列代碼段:

     import React from "react";
     import ListGroup from 'react-bootstrap/ListGroup'; 
     import Table from 'react-bootstrap/Table';
     /**
      * Renders information about the user obtained from MS Graph 
      * @param props
      */
     export const ProfileData = (props) => {
       const holidays = props.graphqlData.data.publicholidays.items;
       return (
         <Table striped bordered hover responsive>
         <thead>
           <tr>
             <th>Country</th>
             <th>Holiday</th>
             <th>Date</th>
           </tr>
         </thead>
         <tbody>
           {holidays.map((item,i) => (
           <tr key={i}>
             <td>{item.countryOrRegion}</td>
             <td>{item.holidayName}</td>
             <td>{item.date}</td>
           </tr>
           ))}
           </tbody>
         </Table>
     )};
    
  8. 儲存所有檔案變更。

  9. 在您選擇的終端應用程式中,移至 React 專案的根資料夾,然後執行 命令 npm start 在本機測試應用程式。

  10. 從瀏覽器中載入 http://localhost:3000應用程式之後,請遵循教學課程最後一個部分中 的步驟,從應用程式 呼叫 API 進行驗證。

  11. 登入之後,按兩下 [查詢 GraphQL 數據的查詢網狀架構 API] 按鈕

    登入后 React 範例應用程式的螢幕快照。

  12. Fabric 中 GraphQL API 的成功驗證要求會將 GraphQL 查詢中的數據傳回至 React 用戶端應用程式中的 Lakehouse:

    收到 GraphQL 要求之後 React 範例應用程式的螢幕快照。

其他語言

在 Microsoft Fabric 範例 GitHub 存放庫中尋找 C#、Python 和其他語言範例,以聯機到 GraphQL API