共用方式為


將應用程式連線至適用於 GraphQL 的 Fabric API

若要將應用程式連線到 GraphQL 的 API,您需要三個重要詳細資料: 用戶端識別碼租用戶識別碼,以及 Fabric 中的 GraphQL 端點位址 。 以下各節說明如何建立和擷取所需的詳細資訊,以及如何使用範例 React 應用程式存取您的 API。

其他語言

本教學課程說明如何將 React 範例應用程式連線到適用於 GraphQL 的 Fabric API。 您可以在 Microsoft Fabric 範例 GitHub 存放庫中找到 C#、Python 和其他語言範例。

必要條件

  • 連線應用程式之前,請確定您在 Fabric 中有 GraphQL 的 API。 如需詳細資訊,請參閱在 Fabric 中建立適用於 GraphQL 的 API 並新增資料

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

  • 呼叫 API 的已驗證憑證(使用者主體、服務主體或受管識別)需要具有 GraphQL API 的執行權限(在新增直接存取權限時選擇 "執行查詢和變動" 選項)。 如果使用單一登入 (SSO) 作為 API 中的連線選項,請確定認證在所選資料來源中具有讀取或寫入許可權。 如需詳細資訊,請參閱 連線至資料源並建置架構

建立 Microsoft Entra 應用程式

下列步驟說明如何在 Microsoft Entra 中設定 ReactJS 應用程式的支援。

  1. 使用 快速入門中所述的步驟註冊應用程式:使用 Microsoft 身分識別平台註冊應用程式,

  2. Microsoft Entra 應用程式 (用戶端) 識別碼目錄 (租用戶識別碼) 值會出現在 [摘要] 方塊中。 記錄這些值,因為稍後需要這些值。

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

  4. 新增 PowerBI 服務、選取 [委派的許可權],然後選取 [GraphQLApi.Execute.All ] 許可權。 確認不需要系統管理員同意。

  5. 返回 管理 清單,選取 驗證 新增>平台>單頁應用程式

  6. 針對本機開發目的,請在 [重新導向 URIhttp://localhost:3000新增 ,並確認應用程式已針對授權碼流程啟用,且具有適用於程式代碼交換的證明金鑰 (PKCE) 。 選取 [設定] 按鈕來儲存變更。 如果應用程式遇到與跨來源要求相關的錯誤,請在上一個步驟中使用相同的重新導向 URI 新增 行動和桌面應用程式 平台。

  7. 回到 [驗證],向下捲動至 [進階設定],然後在 [允許公用用戶端流程] 下,選取 [[是][啟用下列行動和桌面流程]

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

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

  1. 從 [網狀架構入口網站] 首頁,從工作負載清單中選取 [資料工程師]。

  2. 在 [資料工程] 體驗中,選取 [使用範例],然後在 Lakehouse 底下,選取 [國定假日] ,以自動建立包含國定假日資料的新 Lakehouse。

    選取範例資料 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. 使用先前記錄的 Microsoft Entra 應用程式中的 用戶端識別碼租用戶識別碼 ,並複製端點 URI,因為稍後需要它。

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

備註

如果您想要略過下列手動步驟,您可以使用完整的應用程式複製 GitHub 存放庫 。 請遵循步驟 3,將 GraphQL 端點和從 Microsoft Entra 擷取的特定詳細數據新增至檔案 authConfig.js,透過 npm install 安裝相依性,並跳至步驟 9 以繼續測試應用程式執行。

  1. 使用現有的 React 應用程式作為起點。 請遵循教學課程中的步驟建立 React 單頁應用程式,並準備進行驗證 ,以建立已設定 Microsoft 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: 
     * [OpenID Connect scopes](/azure/active-directory/develop/v2-permissions-and-consent#openid-connect-scopes)
     */
    export const loginRequest = {
        scopes: ["https://analysis.windows.net/powerbi/api/GraphQLApi.Execute.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/GraphQLApi.Execute.All

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

    • clientId - 應用程式的識別碼,也稱為用戶端。 將 Enter_the_Application_Id_Here 更換為先前從已註冊 Microsoft Entra 應用程式概觀頁面記錄的 Application(用戶端)識別碼 值。

    • authority - 這由兩部分組成:

      • 執行個體是雲端提供者的端點。 在國家雲端中檢查不同的可用端點。

      • 租用戶識別碼是註冊應用程式的租用戶識別碼。 將 Enter_the_Tenant_Info_Here 替換為先前從已註冊應用程式的概觀頁面記錄下來的 目錄(租戶)識別碼 值。

    • graphQLEndpoint - 適用於 GraphQL 端點的 Fabric API。 使用稍早記錄的 GraphQL API 端點取代 Enter_the_GraphQL_Endpoint_Here

  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>CountryOrRegion</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. 登入之後,選取 [查詢 Fabric API for GraphQL 資料] 按鈕。

    登入後 React 範例應用程式的螢幕擷取畫面。

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

    收到 GraphQL 要求後的 React 範例應用程式螢幕擷取畫面。