> ## Documentation Index
> Fetch the complete documentation index at: https://villagesql.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# 如何把 MySQL 表作为 REST API 暴露

> 如何使用 VillageSQL 的 vsql_rest 扩展通过 HTTP 提供 MySQL 表——过滤器、列选择、分页、按表设置方法，以及您必须先更改的默认值。

> [card] [VillageSQL is a drop-in replacement for MySQL with extensions.](https://villagesql.com/docs/en/8.4/stable/install-server.md)
>
> All examples on this page work on VillageSQL. Install Now →

> [!NOTE]
>
> 本指南使用预览功能。请使用 `--vsql_allow_preview_extensions=ON` 启动服务器，否则 `INSTALL EXTENSION` 会被拒绝。

在几张表前面放一个只读的 JSON 端点，通常意味着编写一个小服务、部署它、给它一个数据库账户，并维持它的运行。VillageSQL 的 `vsql_rest` 扩展改为从服务器进程内部提供这些表，因此没有第二个进程，也没有新的部署。

默认值是为开发者机器设计的，而不是为网络设计的。在把端口开放给任何东西之前，请先阅读下面的"暴露端口之前"。

## 启用

```sql theme={null}
INSTALL EXTENSION vsql_rest;
```

先创建数据库及其表。监听器在启动时读取数据库布局，并缓存 `vsql_rest.schema_ttl` 秒（默认 60），所以之后创建的表在缓存过期之前都会回答 `table not found`。

```sql theme={null}
CREATE DATABASE shop;
USE shop;

CREATE TABLE products (
    id       INT PRIMARY KEY,
    name     VARCHAR(40),
    category VARCHAR(20),
    price    DECIMAL(8,2),
    in_stock INT
);

INSERT INTO products VALUES
    (1, 'Budget Widget',   'widget', 29.99, 120),
    (2, 'Standard Widget', 'widget', 79.99,  40),
    (3, 'Premium Widget',  'widget', 149.99,  4),
    (4, 'Cable, 2m',       'cable',   9.99, 500),
    (5, 'Cable, 5m',       'cable',  14.99,   0);
```

然后指定数据库，指定您愿意提供的表，并启动监听器：

```sql theme={null}
SET GLOBAL vsql_rest.schema = 'shop';
SET GLOBAL vsql_rest.allowed_tables = 'products';
SET GLOBAL vsql_rest.vsql_rest_enabled = ON;
```

## 读取

一张表就是一个路径，查询字符串负责过滤。每个过滤器的形式是 `column=operator.value`：

```bash theme={null}
curl 'http://127.0.0.1:3000/products?category=eq.widget&order=price.desc&limit=2'
```

```json theme={null}
[{"id":3,"name":"Premium Widget","category":"widget","price":"149.99","in_stock":4},{"id":2,"name":"Standard Widget","category":"widget","price":"79.99","in_stock":40}]
```

只请求您需要的列：

```bash theme={null}
curl 'http://127.0.0.1:3000/products?select=name,price&in_stock=eq.0'
```

```json theme={null}
[{"name":"Cable, 5m","price":"14.99"}]
```

用 `or=(...)` 组合条件：

```bash theme={null}
curl 'http://127.0.0.1:3000/products?or=(category.eq.cable,price.gt.100)&select=id,name'
```

```json theme={null}
[{"id":3,"name":"Premium Widget"},{"id":4,"name":"Cable, 2m"},{"id":5,"name":"Cable, 5m"}]
```

用 `limit` 和 `offset` 翻页：

```bash theme={null}
curl 'http://127.0.0.1:3000/products?order=id.asc&limit=2&offset=2'
```

```json theme={null}
[{"id":3,"name":"Premium Widget","category":"widget","price":"149.99","in_stock":4},{"id":4,"name":"Cable, 2m","category":"cable","price":"9.99","in_stock":500}]
```

运算符有 `eq`、`neq`、`lt`、`lte`、`gt`、`gte`、`like`、`cs_like`、`in` 和 `is`。`in` 接受一个列表，例如 `?id=in.(1,3)`；`is` 接受 null，例如 `?price=is.null` 或 `?price=is.not.null`。没有 `limit` 的请求最多返回 `vsql_rest.max_rows` 行，初始值为 1000。

## 允许列表

对 API 而言，不在 `allowed_tables` 中的表就不存在：

```bash theme={null}
curl 'http://127.0.0.1:3000/orders'
```

```json theme={null}
{"message":"table not found: orders","details":null,"hint":null,"code":"VSQL0001"}
```

响应是 404，而且无论该表是不存在还是只是被隐藏，响应内容都一样。

> [!WARNING]
>
> 把 `allowed_tables` 留空并不意味着没有表。它意味着**所有**表。请在启用监听器之前，把它设置为您打算发布的表。

## 按表限制方法

`table_methods` 指定每张表接受哪些 HTTP 方法，形式为 `table:METHOD,METHOD`，表之间用 `|` 分隔：

```sql theme={null}
SET GLOBAL vsql_rest.table_methods = 'products:GET';
```

默认情况下每张表接受所有方法，所以请在监听器启动之前设置它。表未授予的方法会被拒绝：

```json theme={null}
{"message":"method not allowed: POST","details":null,"hint":null,"code":"VSQL0001"}
```

授予写入权限用的是同一个设置：

```sql theme={null}
SET GLOBAL vsql_rest.table_methods = 'products:GET,POST';
```

```bash theme={null}
curl -X POST -H 'Content-Type: application/json' \
     -d '{"id":6,"name":"Cable, 10m","category":"cable","price":19.99,"in_stock":10}' \
     'http://127.0.0.1:3000/products'
```

成功的插入回答 201，正文为空。重复键返回 409：

```json theme={null}
{"message":"Duplicate entry '6' for key 'products.PRIMARY'","details":null,"hint":null,"code":"VSQL0001"}
```

## 观察运行情况

五个状态计数器报告监听器的情况，包括它实际绑定的端口：

```sql theme={null}
SHOW STATUS LIKE 'vsql_rest%';
```

```
+-----------------------------+-------+
| Variable_name               | Value |
+-----------------------------+-------+
| vsql_rest.connections_total | 0     |
| vsql_rest.http_port         | 3000  |
| vsql_rest.https_port        | 0     |
| vsql_rest.requests_active   | 0     |
| vsql_rest.requests_total    | 16    |
+-----------------------------+-------+
```

没有任何东西在监听时，`http_port` 读数为 0，这是判断监听器是否已启动的最快方法。把 `vsql_rest.port` 设为 0 会让操作系统选择一个端口，而这个计数器就是您读取它选了哪个端口的地方。

## 暴露端口之前

默认设置敞开着大门，而每一项单独看都合理。

`require_auth` 初始为 `OFF`，所以没有请求携带或需要令牌。空的 `allowed_tables` 发布整个模式。空的 `table_methods` 允许所有方法，包括 `DELETE`，而对处于这种状态的监听器发起 `DELETE` 会成功：

```bash theme={null}
curl -X DELETE 'http://127.0.0.1:3000/products?id=eq.6'
```

它回答 204，该行就没了。

合在一起，一个在没有其他配置的情况下打开的监听器，会让任何能访问该端口的人读取、插入、更新和删除模式中的每一张表。在笔记本电脑上这很方便。在其他任何地方，请在启用之前更改四项设置：

```sql theme={null}
SET GLOBAL vsql_rest.allowed_tables = 'products';
SET GLOBAL vsql_rest.table_methods  = 'products:GET';
SET GLOBAL vsql_rest.require_auth   = ON;
SET GLOBAL vsql_rest.jwt_secret     = '...';
```

然后通过设置 `ssl_cert` 和 `ssl_key` 以 HTTPS 提供服务。没有绑定地址设置，监听器从启动那一刻起就绑定所有网络接口，所以请在防火墙上封锁该端口，只让反向代理访问它。

## 故障排除

| 症状 | 修复 |
| - | - |
| 安装时出现 `ERROR 3219 ... requires preview capabilities` | 使用 `--vsql_allow_preview_extensions=ON` 启动服务器 |
| 连接被拒绝 | 监听器已关闭。检查 `vsql_rest.vsql_rest_enabled`，然后在 `SHOW STATUS` 中读取 `vsql_rest.http_port` |
| 存在的表却返回 `table not found` | 它不在 `allowed_tables` 中，或者 `vsql_rest.schema` 指定了不同的数据库 |
| 写入返回 405 | `table_methods` 没有为该表授予该方法 |
| 重新安装扩展后设置消失 | `UNINSTALL EXTENSION` 会删除持久化的设置。请重新应用它们 |

## 另请参阅

* [vsql\_rest](https://villagesql.com/docs/zh/extensions/vsql-rest.md)——该扩展的参考页面，包含它添加的每一项设置
* [从 SQL 发起 HTTP 请求](https://villagesql.com/docs/zh/guides/http-requests-in-mysql.md)——同一台服务器向外调用而不是应答
* [用外部 API 数据丰富行](https://villagesql.com/docs/zh/guides/rest-api-enrichment.md)——把查询与别人的 API 连接起来
* [MySQL 安全加固](https://villagesql.com/docs/zh/guides/security-hardening.md)——在端口可达之前还应关闭什么


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.