通过


快速入门:将数据 API 生成器与 SQL 配合使用

在本快速入门中,你将使用数据 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 脚本,然后使用自己的连接字符串跳转到 配置 Data 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 中的连接字符串替换为你自己的:

  • Sqlserver: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. 打开浏览器并导航到 Todo 实体的 REST 终结点。

    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 文件在浏览器中显示您的待办事项。 使用 REST 或 GraphQL 终结点创建一个名为 todo.html 的文件。

<!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

后续步骤