从数据库表生成 API
本教程将带你将一张数据库表完整地发布为 API——从初始化配置到测试增删改查全流程。以图书管理系统的 Books 表为例。
前提条件
- 已安装
dabCLI 工具,参考安装数据墙DBW。 - 有一个可访问的数据库,其中至少有一张表。
本教程使用 SQL Server 示例。PostgreSQL 和 MySQL 的流程完全相同,只需调整 --database-type 和连接字符串格式。
第一步:初始化配置
dab init \
--database-type "mssql" \
--connection-string "Server=localhost;Database=Library;User Id=sa;Password=YourPassword;TrustServerCertificate=true;Encrypt=true;" \
--host-mode "Development"第二步:添加表实体
将 dbo.Books 表注册为 Book 实体,授予匿名用户读权限和已认证用户全部权限:
dab add Book \
--source "dbo.Books" \
--permissions "anonymous:read,authenticated:*"生成的 dab-config.json:
{
"entities": {
"Book": {
"source": { "object": "dbo.Books", "type": "table" },
"permissions": [
{ "role": "anonymous", "actions": ["read"] },
{ "role": "authenticated", "actions": ["*"] }
]
}
}
}* 对表实体扩展为 create、read、update、delete 四项。
第三步:配置字段别名
如果数据库列名是技术命名风格,可以给 API 使用更干净的字段名:
dab update Book \
--fields.name "sku_book_title" \
--fields.alias "title"
dab update Book \
--fields.name "sku_book_year" \
--fields.alias "year"
dab update Book \
--fields.name "id" \
--fields.primary-key "true"API 消费者看到的是 title 和 year,底层列名变化不影响接口。
第四步:启动并测试
dab start查询全部
curl http://localhost:5000/api/Book按主键查询
curl http://localhost:5000/api/Book/id/1000筛选查询
# 2000 年以后出版的书
curl "http://localhost:5000/api/Book?\$filter=year%20ge%202000"
# 只返回书名和年份,按年份降序
curl "http://localhost:5000/api/Book?\$select=title,year&\$orderby=year%20desc"
# 每页 5 条
curl "http://localhost:5000/api/Book?\$first=5"创建记录
curl -X POST http://localhost:5000/api/Book \
-H "Content-Type: application/json" \
-d '{"id": 2000, "title": "云原生架构设计", "year": 2024, "pages": 350}'NOTE
由于配置中 authenticated:* 包含了 create 权限,而 anonymous 只有 read。创建操作需要通过认证用户身份。在开发模式下,可以通过 Simulator 认证或 X-MS-API-ROLE 头模拟角色。
更新和删除
# 更新书名
curl -X PATCH http://localhost:5000/api/Book/id/2000 \
-H "Content-Type: application/json" \
-d '{"title": "云原生架构设计(第二版)"}'
# 删除
curl -X DELETE http://localhost:5000/api/Book/id/2000GraphQL 查询
curl -X POST http://localhost:5000/graphql \
-H "Content-Type: application/json" \
-d '{"query": "{ books { items { id title year pages } } }"}'{
books(filter: { year: { gte: 2000 } }, orderBy: { year: DESC }, first: 5) {
items { id title year pages }
}
}第五步:添加更多表
重复第二步,将其他表也注册为实体:
dab add Author --source "dbo.Authors" --permissions "anonymous:read"
dab add Publisher --source "dbo.Publishers" --permissions "anonymous:read"所有实体在同一个 API 入口下对外暴露,REST 路径分别为 /api/Author 和 /api/Publisher。
实战经验
开发阶段保持 mode 为 Development
host.mode: development 提供 Swagger UI(/swagger)和更详细的错误信息,便于调试。上线前改为 production。
先用 * 通配符快速验证
开发阶段权限配置可以先用 "*" 快速跑通,等 API 行为确认无误后,再根据角色精细调整各操作的权限。
字段别名越早配置越好
一旦 API 消费者开始使用你的接口,字段名的修改成本就很高了。建议在第一个消费者接入之前就确定好 API 层的字段命名规范,用 fields[].alias 建立稳定的 API 契约。
善用 Swagger 测试
启动后直接访问 http://localhost:5000/swagger,在浏览器中浏览所有可用端点,在线测试——不需要写 curl 命令。
