Skip to main content
Version: 2.4.x

Connect to CnosDB

CnosDB supports several programming languages, some examples are provided below.

The HTTP API query command is as follows, which you can refer to when implementing HTTP API requests in code.

Syntax

curl -X POST "http://<cnosdb_url>:<cnosdb_port>/api/v1/sql?db=<database_name>&pretty=true" \
-u "<username>:<password>" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "<your SQL statement>"

Example

curl -X POST "http://127.0.0.1:8902/api/v1/sql?db=public&pretty=true" \
-u "root:" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "CREATE TABLE air (
visibility DOUBLE,
temperature DOUBLE,
pressure DOUBLE,
TAGS(station)
);"

Use programming languages

The sample code uses reqwest to build Http requests.

Http request needs to specify the database to be operated on, written in the url query as db=database_name.

let url = Url::parse("http://127.0.0.1:8902/api/v1/sql?db=public&pretty=true").unwrap();
let sql = r#"
CREATE TABLE air (
visibility DOUBLE,
temperature DOUBLE,
pressure DOUBLE,
TAGS(station)
);"#.to_string();

Set the SQL requested for execution into the body of the http.

Encode the username and password in BASIC code to the Authorization Header.

let user_name = "cnosdb";
let password = "";
let http_client = reqwest::Client::new();
let request = http_client
.request(Method::POST, url)
//用户名和密码
.basic_auth::<&str, &str>(user_name, Some(password))
.body(sql)
.build()
.unwrap();

The status code of the response will indicate whether the SQL is executed successfully, 200 representing success.

The error messages or the result of the correct execution will be in the text() of the response.

let response = http_client.execute(request).await.unwrap();
let success = response.status().is_success();
let result = response.text().await.unwrap();