Setting up query API endpoints

```
["query_cache", "system"]
["query_log", "system"]
["query_views_log", "system"]
```

### Request with array in the query variables that inserts data into a table[​](#request-with-array-in-the-query-variables-that-inserts-data-into-a-table "Direct link to Request with array in the query variables that inserts data into a table")

**Table SQL:**

```
CREATE TABLE default.t_arr
(
    `arr` Array(Array(Array(UInt32)))
)
ENGINE = MergeTree
ORDER BY tuple()
```

**Query API Endpoint SQL:**

```
INSERT INTO default.t_arr VALUES ({arr: Array(Array(Array(UInt32)))});
```

- cURL- JavaScript

```
curl -X POST 'https://console-api.clickhouse.cloud/.api/query-endpoints/<endpoint id>/run' \
--user '<openApiKeyId:openApiKeySecret>' \
-H 'Content-Type: application/json' \
-H 'x-clickhouse-endpoint-version: 2' \
-d '{
  "queryVariables": {
    "arr": [[[12, 13, 0, 1], [12]]]
  }
}'
```

```
fetch(
  "https://console-api.clickhouse.cloud/.api/query-endpoints/<endpoint id>/run",
  {
    method: "POST",
    headers: {
      Authorization: "Basic <base64_encoded_credentials>",
      "Content-Type": "application/json",
      "x-clickhouse-endpoint-version": "2",
    },
    body: JSON.stringify({
      queryVariables: {
        arr: [[[12, 13, 0, 1], [12]]],
      },
    }),
  }
)
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));
```

```
OK
```

### Request with ClickHouse settings `max_threads` set to 8[​](#request-with-clickhouse-settings-max_threads-set-to-8 "Direct link to request-with-clickhouse-settings-max_threads-set-to-8")

**Query API Endpoint SQL:**

```
SELECT * FROM system.tables;
```

- GET (cURL)- POST (cURL)- JavaScript

```
curl 'https://console-api.clickhouse.cloud/.api/query-endpoints/<endpoint id>/run?max_threads=8' \
--user '<openApiKeyId:openApiKeySecret>' \
-H 'x-clickhouse-endpoint-version: 2'
```

```
curl -X POST 'https://console-api.clickhouse.cloud/.api/query-endpoints/<endpoint id>/run?max_threads=8,' \
--user '<openApiKeyId:openApiKeySecret>' \
-H 'Content-Type: application/json' \
-H 'x-clickhouse-endpoint-version: 2' \
```

```
fetch(
  "https://console-api.clickhouse.cloud/.api/query-endpoints/<endpoint id>/run?max_threads=8",
  {
    method: "POST",
    headers: {
      Authorization: "Basic <base64_encoded_credentials>",
      "Content-Type": "application/json",
      "x-clickhouse-endpoint-version": "2",
    },
  }
)
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error("Error:", error));
```

### Request and parse the response as a stream`[​](#request-and-parse-the-response-as-a-stream "Direct link to Request and parse the response as a stream`")

**Query API Endpoint SQL:**

```
SELECT name, database FROM system.tables;
```

- TypeScript

```
async function fetchAndLogChunks(
  url: string,
  openApiKeyId: string,
  openApiKeySecret: string
) {
  const auth = Buffer.from(`${openApiKeyId}:${openApiKeySecret}`).toString(
    "base64"
  );

  const headers = {
    Authorization: `Basic ${auth}`,
    "x-clickhouse-endpoint-version": "2",
  };

  const response = await fetch(url, {
    headers,
    method: "POST",
    body: JSON.stringify({ format: "JSONEachRow" }),
  });

  if (!response.ok) {
    console.error(`HTTP error! Status: ${response.status}`);
    return;
  }

  const reader = response.body as unknown as Readable;
  reader.on("data", (chunk) => {
    console.log(chunk.toString());
  });

  reader.on("end", () => {
    console.log("Stream ended.");
  });

  reader.on("error", (err) => {
    console.error("Stream error:", err);
  });
}

const endpointUrl =
  "https://console-api.clickhouse.cloud/.api/query-endpoints/<endpoint id>/run?format=JSONEachRow";
const openApiKeyId = "<myOpenApiKeyId>";
const openApiKeySecret = "<myOpenApiKeySecret>";
// Usage example
fetchAndLogChunks(endpointUrl, openApiKeyId, openApiKeySecret).catch((err) =>
  console.error(err)
);
```

```
> npx tsx index.ts
> {"name":"COLUMNS","database":"INFORMATION_SCHEMA"}
> {"name":"KEY_COLUMN_USAGE","database":"INFORMATION_SCHEMA"}
...
> Stream ended.
```

### Insert a stream from a file into a table[​](#insert-a-stream-from-a-file-into-a-table "Direct link to Insert a stream from a file into a table")

Create a file `./samples/my_first_table_2024-07-11.csv` with the following content:

```
"user_id","json","name"
"1","{""name"":""John"",""age"":30}","John"
"2","{""name"":""Jane"",""age"":25}","Jane"
```

**Create Table SQL:**

```
create table default.my_first_table
(
    user_id String,
    json String,
    name String,
) ENGINE = MergeTree()
ORDER BY user_id;
```

**Query API Endpoint SQL:**

```
INSERT INTO default.my_first_table
```

```
cat ./samples/my_first_table_2024-07-11.csv | curl --user '<openApiKeyId:openApiKeySecret>' \
                                                   -X POST \
                                                   -H 'Content-Type: application/octet-stream' \
                                                   -H 'x-clickhouse-endpoint-version: 2' \
                                                   "https://console-api.clickhouse.cloud/.api/query-endpoints/<endpoint id>/run?format=CSV" \
                                                   --data-binary @-
```

- [Pre-requisites](#quick-start-guide)
  - [Create a saved query](#creating-a-saved-query)- [Configuring the query API endpoint](#configuring-the-query-api-endpoint)- [Query API parameters](#query-api-parameters)- [Testing and monitoring](#testing-and-monitoring)- [Implementation details](#implementation-details)
    - [HTTP methods](#http-methods)- [Authentication](#authentication)- [Request configuration](#request-configuration)- [Request body](#request-body)- [Responses](#responses)- [Upgrading endpoint versions](#upgrading-endpoint-versions)- [Examples](#examples)
      - [Basic request](#basic-request)- [Request with query variables and version 2 on JSONCompactEachRow format](#request-with-query-variables-and-version-2-on-jsoncompacteachrow-format)- [Request with array in the query variables that inserts data into a table](#request-with-array-in-the-query-variables-that-inserts-data-into-a-table)- [Request with ClickHouse settings `max_threads` set to 8](#request-with-clickhouse-settings-max_threads-set-to-8)- [Request and parse the response as a stream`](#request-and-parse-the-response-as-a-stream)- [Insert a stream from a file into a table](#insert-a-stream-from-a-file-into-a-table)

Was this page helpful?