02-rest-api.mdx 13.4 KB
Newer Older
1 2
---
title: REST API
D
danielclow 已提交
3
description: This document describes the TDengine REST API.
4 5
---

D
danielclow 已提交
6
To support the development of various types of applications and platforms, TDengine provides an API that conforms to REST principles; namely REST API. To minimize the learning cost, unlike REST APIs for other database engines, TDengine allows insertion of SQL commands in the BODY of an HTTP POST request, to operate the database. 
7

D
danielclow 已提交
8 9
:::note
One difference from the native connector is that the REST interface is stateless and so the `USE db_name` command has no effect. All references to table names and super table names need to specify the database name in the prefix. TDengine supports specification of the db_name in RESTful URL. If the database name prefix is not specified in the SQL command, the `db_name` specified in the URL will be used.
10 11 12 13
:::

## Installation

14
The REST interface does not rely on any TDengine native library, so the client application does not need to install any TDengine libraries. The client application's development language only needs to support the HTTP protocol. The REST interface is provided by [taosAdapter](../taosadapter), to use REST interface you need to make sure `taosAdapter` is running properly.
15 16 17 18 19

## Verification

If the TDengine server is already installed, it can be verified as follows:

20
The following example is in an Ubuntu environment and uses the `curl` tool to verify that the REST interface is working. Note that the `curl` tool may need to be installed in your environment.
21

G
gccgdb1234 已提交
22
The following example lists all databases on the host h1.tdengine.com. To use it in your environment, replace `h1.tdengine.com` and `6041` (the default port) with the actual running TDengine service FQDN and port number.
23

D
danielclow 已提交
24 25 26
```bash
curl -L -H "Authorization: Basic cm9vdDp0YW9zZGF0YQ==" \
  -d "select name, ntables, status from information_schema.ins_databases;" \
G
gccgdb1234 已提交
27
  h1.tdengine.com:6041/rest/sql
28 29 30 31 32 33
```

The following return value results indicate that the verification passed.

```json
{
D
danielclow 已提交
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    "code": 0,
    "column_meta": [
        [
            "name",
            "VARCHAR",
            64
        ],
        [
            "ntables",
            "BIGINT",
            8
        ],
        [
            "status",
            "VARCHAR",
            10
        ]
    ],
    "data": [
        [
            "information_schema",
            16,
            "ready"
        ],
        [
            "performance_schema",
            9,
            "ready"
        ]
    ],
    "rows": 2
65 66 67 68 69
}
```

## HTTP request URL format

D
danielclow 已提交
70
```text
S
sunpeng 已提交
71
http://<fqdn>:<port>/rest/sql/[db_name][?tz=timezone[&req_id=req_id]]
72 73 74 75
```

Parameter Description:

D
danielclow 已提交
76 77 78
- fqnd: FQDN or IP address of any host in the cluster.
- port: httpPort configuration item in the configuration file, default is 6041.
- db_name: Optional parameter that specifies the default database name for the executed SQL command.
79
- tz: Optional parameter that specifies the timezone of the returned time, following the IANA Time Zone rules, e.g. `America/New_York`.
S
sunpeng 已提交
80
- req_id: Optional parameter that specifies the request id for tracing.
81

82 83 84 85 86 87
:::note

URL Encoding. Make sure that parameters are properly encoded. For example, when specifying a timezone you must properly encode special characters. ?tz=Etc/GMT+10 will not work because the <+> plus symbol is recognized as a space in the url. It's best practice to encode all special characters in a parameter. Instead use ?tz=Etc%2FGMT%2B10 for the parameter.

:::

88 89 90 91
For example, `http://h1.taos.com:6041/rest/sql/test` is a URL to `h1.taos.com:6041` and sets the default database name to `test`.

TDengine supports both Basic authentication and custom authentication mechanisms, and subsequent versions will provide a standard secure digital signature mechanism for authentication.

92
- authentication information is shown below:
93

D
danielclow 已提交
94
  ```text
95 96 97
  Authorization: Taosd <TOKEN>
  ```

98
- Basic authentication information is shown below:
99

D
danielclow 已提交
100
  ```text
101 102 103 104 105 106 107 108
  Authorization: Basic <TOKEN>
  ```

The HTTP request's BODY is a complete SQL command, and the data table in the SQL statement should be provided with a database prefix, e.g., `db_name.tb_name`. If the table name does not have a database prefix and the database name is not specified in the URL, the system will response an error because the HTTP module is a simple forwarder and has no awareness of the current DB.

Use `curl` to initiate an HTTP request with a custom authentication method, with the following syntax.

```bash
S
sunpeng 已提交
109
curl -L -H "Authorization: Basic <TOKEN>" -d "<SQL>" <ip>:<PORT>/rest/sql/[db_name][?tz=timezone[&req_id=req_id]]
110 111
```

D
danielclow 已提交
112
or
113 114

```bash
S
sunpeng 已提交
115
curl -L -u username:password -d "<SQL>" <ip>:<PORT>/rest/sql/[db_name][?tz=timezone[&req_id=req_id]]
116 117
```

D
danielclow 已提交
118
where `TOKEN` is the string after Base64 encoding of `{username}:{password}`, e.g. `root:taosdata` is encoded as `cm9vdDp0YW9zZGF0YQ==`..
119 120 121

## HTTP Return Format

D
danielclow 已提交
122 123
### HTTP Response Code

124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158
Starting from `TDengine 3.0.3.0`, `taosAdapter` provides a configuration parameter `httpCodeServerError` to set whether to return a non-200 http status code when the C interface returns an error

| **Description** | **httpCodeServerError false** | **httpCodeServerError true** |
|--------------------|---------------------------- ------|---------------------------------------|
| taos_errno() returns 0 | 200 | 200 |
| taos_errno() returns non-0 | 200 (except authentication error) | 500 (except authentication error and 400/502 error) |
| Parameter error | 400 (only handle HTTP request URL parameter error) | 400 (handle HTTP request URL parameter error and taosd return error) |
| Authentication error | 401 | 401 |
| Interface does not exist | 404 | 404 |
| Cluster unavailable error | 502 | 502 |
| Insufficient system resources | 503 | 503 |

The C error codes that return http code 400 are:

- TSDB_CODE_TSC_SQL_SYNTAX_ERROR ( 0x0216 )
- TSDB_CODE_TSC_LINE_SYNTAX_ERROR (0x021B)
- TSDB_CODE_PAR_SYNTAX_ERROR (0x2600)
- TSDB_CODE_TDB_TIMESTAMP_OUT_OF_RANGE (0x060B)
- TSDB_CODE_TSC_VALUE_OUT_OF_RANGE (0x0224)
- TSDB_CODE_PAR_INVALID_FILL_TIME_RANGE (0x263B)

The error code that returns http code 401 are:

- TSDB_CODE_MND_USER_ALREADY_EXIST (0x0350)
- TSDB_CODE_MND_USER_NOT_EXIST (0x0351)
- TSDB_CODE_MND_INVALID_USER_FORMAT (0x0352)
- TSDB_CODE_MND_INVALID_PASS_FORMAT (0x0353)
- TSDB_CODE_MND_NO_USER_FROM_CONN (0x0354)
- TSDB_CODE_MND_TOO_MANY_USERS (0x0355)
- TSDB_CODE_MND_INVALID_ALTER_OPER (0x0356)
- TSDB_CODE_MND_AUTH_FAILURE (0x0357)

The error code that returns http code 403 are:

- TSDB_CODE_RPC_SOMENODE_NOT_CONNECTED (0x0020)
D
danielclow 已提交
159 160 161

### HTTP body structure

sangshuduo's avatar
sangshuduo 已提交
162
#### Successful Insert Operation
D
danielclow 已提交
163 164

Example:
165 166 167

```json
{
D
danielclow 已提交
168 169 170 171 172 173 174 175 176 177 178 179 180 181
  "code": 0,
  "column_meta": [["affected_rows", "INT", 4]],
  "data": [[0]],
  "rows": 1
}
```

Description:

- code: (`int`) 0 indicates success.
- column_meta: (`[1][3]any`) Only returns `[["affected_rows", "INT", 4]]`.
- rows: (`int`) Only returns `1`.
- data: (`[][]any`) Returns the number of rows affected.

sangshuduo's avatar
sangshuduo 已提交
182
#### Successful Query Operation
D
danielclow 已提交
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206

Example:

```json
{
  "code": 0,
  "column_meta": [
    ["ts", "TIMESTAMP", 8],
    ["count", "BIGINT", 8],
    ["endpoint", "VARCHAR", 45],
    ["status_code", "INT", 4],
    ["client_ip", "VARCHAR", 40],
    ["request_method", "VARCHAR", 15],
    ["request_uri", "VARCHAR", 128]
  ],
  "data": [
    [
      "2022-06-29T05:50:55.401Z",
      2,
      "LAPTOP-NNKFTLTG:6041",
      200,
      "172.23.208.1",
      "POST",
      "/rest/sql"
207
    ],
D
danielclow 已提交
208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273
    [
      "2022-06-29T05:52:16.603Z",
      1,
      "LAPTOP-NNKFTLTG:6041",
      200,
      "172.23.208.1",
      "POST",
      "/rest/sql"
    ],
    [
      "2022-06-29T06:28:14.118Z",
      1,
      "LAPTOP-NNKFTLTG:6041",
      200,
      "172.23.208.1",
      "POST",
      "/rest/sql"
    ],
    [
      "2022-06-29T05:52:16.603Z",
      2,
      "LAPTOP-NNKFTLTG:6041",
      401,
      "172.23.208.1",
      "POST",
      "/rest/sql"
    ]
  ],
  "rows": 4
}
```

Description:

- code: `int` 0 indicates success.
- column_meta: (`[][3]any`) Column information. Each column is described with three values: column name (string), column type (string), and type length (int).
- rows: (`int`) The number of rows returned.
- data: (`[][]any`)

The following types may be returned:

- "NULL"
- "BOOL"
- "TINYINT"
- "SMALLINT"
- "INT"
- "BIGINT"
- "FLOAT"
- "DOUBLE"
- "VARCHAR"
- "TIMESTAMP"
- "NCHAR"
- "TINYINT UNSIGNED"
- "SMALLINT UNSIGNED"
- "INT UNSIGNED"
- "BIGINT UNSIGNED"
- "JSON"

#### Errors

Example:

```json
{
  "code": 9728,
  "desc": "syntax error near \"1\""
274 275 276 277 278
}
```

Description:

D
danielclow 已提交
279 280
- code: (`int`) Error code.
- desc: (`string`): Error code description.
281 282 283 284 285 286 287 288 289 290 291

## Custom Authorization Code

HTTP requests require an authorization code `<TOKEN>` for identification purposes. The administrator usually provides the authorization code, and it can be obtained simply by sending an ``HTTP GET`` request as follows:

```bash
curl http://<fqnd>:<port>/rest/login/<username>/<password>
```

Where `fqdn` is the FQDN or IP address of the TDengine database. `port` is the port number of the TDengine service. `username` is the database username. `password` is the database password. The return value is in `JSON` format, and the meaning of each field is as follows.

D
danielclow 已提交
292 293 294
- status: flag bit of the request result.
- code: return value code.
- desc: authorization code.
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310

Example of getting authorization code.

```bash
curl http://192.168.0.1:6041/rest/login/root/taosdata
```

Response body:

```json
{
  "code": 0,
  "desc": "/KfeAzX/f9na8qdtNZmtONryp201ma04bEl8LcvLUd7a8qdtNZmtONryp201ma04"
}
```

D
danielclow 已提交
311
## Usage examples
312 313 314 315

- query all records from table d1001 of database demo

  ```bash
Z
Zhengmao Zhu 已提交
316
  curl -L -H "Authorization: Basic cm9vdDp0YW9zZGF0YQ==" -d "select * from demo.d1001" 192.168.0.1:6041/rest/sql
317 318 319 320 321 322
  ```

  Response body:

  ```json
  {
D
danielclow 已提交
323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360
      "code": 0,
      "column_meta": [
          [
              "ts",
              "TIMESTAMP",
              8
          ],
          [
              "current",
              "FLOAT",
              4
          ],
          [
              "voltage",
              "INT",
              4
          ],
          [
              "phase",
              "FLOAT",
              4
          ]
      ],
      "data": [
          [
              "2022-07-30T06:44:40.32Z",
              10.3,
              219,
              0.31
          ],
          [
              "2022-07-30T06:44:41.32Z",
              12.6,
              218,
              0.33
          ]
      ],
      "rows": 2
361 362 363 364 365 366
  }
  ```

- Create database demo:

  ```bash
Z
Zhengmao Zhu 已提交
367
  curl -L -H "Authorization: Basic cm9vdDp0YW9zZGF0YQ==" -d "create database demo" 192.168.0.1:6041/rest/sql
368 369 370 371 372 373
  ```

  Response body:

  ```json
  {
D
danielclow 已提交
374 375 376 377 378 379 380 381 382 383 384 385 386 387
      "code": 0,
      "column_meta": [
          [
              "affected_rows",
              "INT",
              4
          ]
      ],
      "data": [
          [
              0
          ]
      ],
      "rows": 1
388 389 390
  }
  ```

sangshuduo's avatar
sangshuduo 已提交
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
## REST API between TDengine 2.x and 3.0

### URI

| URI                  | TDengine 2.x         | TDengine 3.0                                         |
| :--------------------| :------------------: | :--------------------------------------------------: |
| /rest/sql            | Supported            | Supported (with different response code and body)    |
| /rest/sqlt           | Supported            | No more supported                                    |
| /rest/sqlutc         | Supported            | No more supported                                    |

### HTTP code

| HTTP code            | TDengine 2.x         | TDengine 3.0 | note                                  |
| :--------------------| :------------------: | :----------: | :-----------------------------------: |
| 200                  | Supported            | Supported    | Success or taosc return error         |
| 400                  | Not supported        | Supported    | Parameter error                       |
| 401                  | Not supported        | Supported    | Authentication failure                |
| 404                  | Supported            | Supported    | URI not exist                         |
| 500                  | Not supported        | Supported    | Internal error                        |
| 503                  | Supported            | Supported    | Insufficient system resources         |

### Response body

414 415 416 417 418 419
#### REST response body return from TDengine 2.x

```JSON
{
  "status": "succ",
  "head": [
sangshuduo's avatar
sangshuduo 已提交
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436
    "name",
    "created_time",
    "ntables",
    "vgroups",
    "replica",
    "quorum",
    "days",
    "keep1,keep2,keep(D)",
    "cache(MB)",
    "blocks",
    "minrows",
    "maxrows",
    "wallevel",
    "fsync",
    "comp",
    "precision",
    "status"
437
  ],
438
  "data": [
sangshuduo's avatar
sangshuduo 已提交
439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
    [
      "log",
      "2020-09-02 17:23:00.039",
      4,
      1,
      1,
      1,
      10,
      "30,30,30",
      1,
      3,
      100,
      4096,
      1,
      3000,
      2,
      "us",
      "ready"
    ]
458 459 460
  ],
  "rows": 1
}
461 462 463
```
```
  "data": [
sangshuduo's avatar
sangshuduo 已提交
464 465 466 467 468 469 470 471 472 473
        [
            "information_schema",
            16,
            "ready"
        ],
        [
            "performance_schema",
            9,
            "ready"
        ]
474 475
    ],
```
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513

#### REST response body return from TDengine 3.0

```JSON
{
    "code": 0,
    "column_meta": [
        [
            "name",
            "VARCHAR",
            64
        ],
        [
            "ntables",
            "BIGINT",
            8
        ],
        [
            "status",
            "VARCHAR",
            10
        ]
    ],
    "data": [
        [
            "information_schema",
            16,
            "ready"
        ],
        [
            "performance_schema",
            9,
            "ready"
        ]
    ],
    "rows": 2
}
```
sangshuduo's avatar
sangshuduo 已提交
514

D
danielclow 已提交
515
## Reference
516

D
danielclow 已提交
517
[taosAdapter](/reference/taosadapter/)