快速入門:使用 SQL 與資料 API 建立工具

在這個快速入門中,你將使用 Data API 建構器(DAB)為本地 SQL 資料庫建立 REST 和 GraphQL 端點。 選擇你的資料庫引擎開始吧。

先決條件

安裝資料 API 產生器 CLI

請從 NuGet 安裝 Microsoft.DataApiBuilder 套件以作為 .NET 工具。

  1. 使用 dotnet tool install 並添加 Microsoft.DataApiBuilder 參數來安裝最新版本的 --global

    dotnet tool install --global Microsoft.DataApiBuilder
    

    備註

    如果已安裝套件,請使用 dotnet tool update來更新套件。

    dotnet tool update --global Microsoft.DataApiBuilder
    
  2. 使用 dotnet tool list 並透過 --global 參數確認工具已安裝。

    dotnet tool list --global
    

拉取資料庫映像檔

小提示

已經有資料庫了嗎? 跳到 建立並做種子資料庫,執行引擎的 SQL 腳本,然後跳到用你自己的連接字串 配置資料 API 建構 器。

下載適用於您資料庫引擎的 Docker 映像檔。 這步驟視你的連線速度而定,可能需要幾分鐘。

docker pull mcr.microsoft.com/mssql/server:2025-latest

啟動資料庫

在 Docker 裡執行一個本地資料庫實例。

docker run --name dab-mssql --env "ACCEPT_EULA=Y" --env "MSSQL_SA_PASSWORD=P@ssw0rd1" --publish 1433:1433 --detach mcr.microsoft.com/mssql/server:2025-latest

小提示

如果埠1433已經正在使用(例如,被本地 SQL Server 安裝佔用),請將--publish更換為其他主機埠,例如1434:1433,並在後續步驟中將Server=localhost,1433更新為Server=localhost,1434

在執行下一個指令前,先確認資料庫引擎是否準備好。

docker exec dab-mssql /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "P@ssw0rd1" -C -Q "SELECT 1"

如果回傳錯誤,請等幾秒再試一次。

建立並填充資料庫

建立 todos 資料庫和表格,然後加入範例資料。 如果你用的是 Docker,不需要 SQL 用戶端——docker exec 指令直接在容器內執行。 如果你用的是自己的資料庫,可以在你偏好的工具裡執行 SQL 腳本。

  1. 建立資料庫。

    docker exec dab-mssql /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "P@ssw0rd1" -C -Q "CREATE DATABASE todos;"
    
  2. 建立表格並加入範例資料。

    docker exec dab-mssql /opt/mssql-tools18/bin/sqlcmd -S localhost -U sa -P "P@ssw0rd1" -C -d todos -Q "CREATE TABLE dbo.todos (id int PRIMARY KEY, title nvarchar(100) NOT NULL, completed bit NOT NULL DEFAULT 0); INSERT INTO dbo.todos VALUES (1, 'Walk the dog', 0), (2, 'Feed the fish', 0), (3, 'Comb the cat', 1);"
    

小提示

使用自己的 SQL Server? 直接執行這個腳本:

CREATE DATABASE todos;
GO
USE todos;
GO
CREATE TABLE dbo.todos (id int PRIMARY KEY, title nvarchar(100) NOT NULL, completed bit NOT NULL DEFAULT 0);
INSERT INTO dbo.todos VALUES (1, 'Walk the dog', 0), (2, 'Feed the fish', 0), (3, 'Comb the cat', 1);

設定資料 API 建構器

建立 DAB 設定檔並新增 Todo 實體。

小提示

用你自己的資料庫?dab init 中的連接字串替換為您自己的:

  • SQL Server:Server=<host>,<port>;Database=todos;User Id=<user>;Password=<password>;TrustServerCertificate=true;Encrypt=true;
  • PostgreSQL:Host=<host>;Port=5432;Database=todos;User ID=<user>;Password=<password>;
  • MySQL:Server=<host>;Port=3306;Database=todos;User=<user>;Password=<password>;
  1. 初始化設定。

    dab init --database-type "mssql" --host-mode "Development" --connection-string "Server=localhost,1433;Database=todos;User Id=sa;Password=P@ssw0rd1;TrustServerCertificate=true;Encrypt=true;"
    
  2. 新增 Todo 實體。

    dab add Todo --source "dbo.todos" --permissions "anonymous:*"
    

您的 dab-config.json 檔案現在應該會看起來像以下範例:

{
  "$schema": "https://github.com/Azure/data-api-builder/releases/download/vmajor.minor.patch/dab.draft.schema.json",
  "data-source": {
    "database-type": "mssql",
    "connection-string": "Server=localhost,1433;Database=todos;User Id=sa;Password=P@ssw0rd1;TrustServerCertificate=true;Encrypt=true;"
  },
  "runtime": {
    "rest": {
      "enabled": true
    },
    "graphql": {
      "enabled": true
    },
    "host": {
      "mode": "development",
      "cors": {
        "origins": ["*"]
      }
    }
  },
  "entities": {
    "Todo": {
      "source": "dbo.todos",
      "permissions": [
        {
          "role": "anonymous",
          "actions": [
            "*"
          ]
        }
      ]
    }
  }
}

小提示

你可以跳過 dab initdab add 指令,直接用本文所示的內容創建 dab-config.json 檔案。

啟動 API

使用 dab start 來執行工具,併為您的實體建立 API 端點。

dab start

輸出應該包含執行中的 API 位址。

      Successfully completed runtime initialization.
info: Microsoft.Hosting.Lifetime[14]
      Now listening on: <http://localhost:5000>

小提示

在此範例中,應用程式在埠 localhost執行。 執行中的應用程式可能有不同的位址和埠。

測試 API

  1. 打開瀏覽器,然後移動到 REST 端點的 Todo 實體。

    http://localhost:5000/api/Todo
    
  2. JSON 回應應該包含這三個待辦事項。

    {
      "value": [
        { "id": 1, "title": "Walk the dog", "completed": false },
        { "id": 2, "title": "Feed the fish", "completed": false },
        { "id": 3, "title": "Comb the cat", "completed": true }
      ]
    }
    
  3. 請前往 Swagger 文件頁面 /swagger

    http://localhost:5000/swagger
    

建置 Web 應用程式

使用瀏覽器透過純 HTML 文件顯示你的待辦事項。 建立檔案名稱 todo.html ,可使用 REST 或 GraphQL 接口。

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Todo App</title>
  <style>
    body { font-family: sans-serif; max-width: 400px; margin: 2rem auto; }
    li.done { text-decoration: line-through; color: gray; }
    #error { color: red; }
  </style>
</head>
<body>
  <h1>Todos</h1>
  <ul id="list"></ul>
  <p id="error"></p>
  <script>
    fetch('http://localhost:5000/api/Todo')
      .then(r => r.json())
      .then(data => {
        const ul = document.getElementById('list');
        data.value.forEach(todo => {
          const li = document.createElement('li');
          li.textContent = todo.title;
          if (todo.completed) li.className = 'done';
          ul.appendChild(li);
        });
      })
      .catch(() => {
        document.getElementById('error').textContent =
          'Could not reach the API. Make sure DAB is running on http://localhost:5000.';
      });
  </script>
</body>
</html>

在瀏覽器中開啟 todo.html 。 該頁面會擷取所有待辦事項並以清單形式呈現,完成項目以劃線方式顯示。

這很重要

你設定中的 cors 設定允許這個從本地檔案系統開啟的 HTML 檔案呼叫 API。 如果沒有它,瀏覽器就會封鎖請求。

清除

完成時停止並移除 Docker 容器。

docker stop dab-mssql && docker rm dab-mssql

下一個步驟