REST API
The QuestDB REST API is based on standard HTTP features and is understood by off-the-shelf HTTP clients. It provides a simple way to interact with QuestDB and is compatible with most programming languages. API functions are fully keyed on the URL and they use query parameters as their arguments.
The Web Console is the official Web client relying on the REST API. Find out more in the section using the Web Console.
Available methods
Examples
QuestDB exposes a REST API for compatibility with a wide range of libraries and
tools. The REST API is accessible on port 9000
and has the following
insert-capable entrypoints:
Entrypoint | HTTP Method | Description | API Docs |
---|---|---|---|
/imp | POST | Import CSV data | Reference |
/exec?query=.. | GET | Run SQL Query returning JSON result set | Reference |
For details such as content type, query parameters and more, refer to the REST API docs.
/imp
: Uploading Tabular Data
Let's assume you want to upload the following data via the /imp
entrypoint:
- CSV
- Table
col1,col2,col3
a,10.5,True
b,100,False
c,,True
col1 | col2 | col3 |
---|---|---|
a | 10.5 | true |
b | 100 | false |
c | NULL | true |
You can do so via the command line using cURL
or programmatically via HTTP
APIs in your scripts and applications.
By default, the response is designed to be human-readable. Use the fmt=json
query argument to obtain a response in JSON. You can also specify the schema
explicitly. See the second example in Python for these features.
- cURL
- Python
- NodeJS
- Go
This example imports a CSV file with automatic schema detection.
curl -F data=@data.csv http://localhost:9000/imp?name=table_name
This example overwrites an existing table and specifies a timestamp format and a designated timestamp column. For more information on the optional parameters to specify timestamp formats, partitioning and renaming tables, see the REST API documentation.
curl \
-F schema='[{"name":"ts", "type": "TIMESTAMP", "pattern": "yyyy-MM-dd - HH:mm:ss"}]' \
-F data=@weather.csv 'http://localhost:9000/imp?overwrite=true×tamp=ts'
This first example shows uploading the data.csv
file with automatic schema
detection.
import sys
import requests
csv = {'data': ('my_table', open('./data.csv', 'r'))}
host = 'http://localhost:9000'
try:
response = requests.post(host + '/imp', files=csv)
print(response.text)
except requests.exceptions.RequestException as e:
print(f'Error: {e}', file=sys.stderr)
The second example creates a CSV buffer from Python objects and uploads them with a custom schema. Note UTF-8 encoding.
The fmt=json
parameter allows us to obtain a parsable response, rather than a
tabular response designed for human consumption.
import io
import csv
import requests
import pprint
import json
def to_csv_str(table):
output = io.StringIO()
csv.writer(output, dialect='excel').writerows(table)
return output.getvalue().encode('utf-8')
def main():
table_name = 'example_table2'
table = [
['col1', 'col2', 'col3'],
['a', 10.5, True],
['b', 100, False],
['c', None, True]]
table_csv = to_csv_str(table)
print(table_csv)
schema = json.dumps([
{'name': 'col1', 'type': 'SYMBOL'},
{'name': 'col2', 'type': 'DOUBLE'},
{'name': 'col3', 'type': 'BOOLEAN'}])
response = requests.post(
'http://localhost:9000/imp',
params={'fmt': 'json'},
files={
'schema': schema,
'data': (table_name, table_csv)}).json()
# You can parse the `status` field and `error` fields
# of individual columns. See Reference/API/REST docs for details.
pprint.pprint(response)
if __name__ == '__main__':
main()
const fetch = require("node-fetch")
const FormData = require("form-data")
const fs = require("fs")
const HOST = "http://127.0.0.1:9000"
async function run() {
const form = new FormData()
form.append("data", fs.readFileSync(__dirname + "/data.csv"), {
filename: "data.csv",
contentType: "application/octet-stream",
})
try {
const r = await fetch(`${HOST}/imp`, {
method: "POST",
body: form,
headers: form.getHeaders(),
})
console.log(r)
} catch (e) {
console.error(e)
}
}
run()
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"mime/multipart"
"net/http"
"net/url"
"os"
)
func main() {
u, err := url.Parse("http://localhost:9000")
checkErr(err)
u.Path += "imp"
url := fmt.Sprintf("%v", u)
fileName := "/path/to/data.csv"
file, err := os.Open(fileName)
checkErr(err)
defer file.Close()
buf := new(bytes.Buffer)
writer := multipart.NewWriter(buf)
uploadFile, _ := writer.CreateFormFile("data", "data.csv")
_, err = io.Copy(uploadFile, file)
checkErr(err)
writer.Close()
req, err := http.NewRequest(http.MethodPut, url, buf)
checkErr(err)
req.Header.Add("Content-Type", writer.FormDataContentType())
client := &http.Client{}
res, err := client.Do(req)
checkErr(err)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
checkErr(err)
log.Println(string(body))
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
/exec
: SQL INSERT
Query
The /exec
entrypoint takes a SQL query and returns results as JSON.
We can use this for quick SQL inserts too, but note that there's no support for parameterized queries that are necessary to avoid SQL injection issues. Prefer InfluxDB Line Protocol if you need high-performance inserts.
- cURL
- Python
- NodeJS
- Go
# Create Table
curl -G \
--data-urlencode "query=CREATE TABLE IF NOT EXISTS trades(name STRING, value INT)" \
http://localhost:9000/exec
# Insert a row
curl -G \
--data-urlencode "query=INSERT INTO trades VALUES('abc', 123456)" \
http://localhost:9000/exec
import sys
import requests
import json
host = 'http://localhost:9000'
def run_query(sql_query):
query_params = {'query': sql_query, 'fmt' : 'json'}
try:
response = requests.get(host + '/exec', params=query_params)
json_response = json.loads(response.text)
print(json_response)
except requests.exceptions.RequestException as e:
print(f'Error: {e}', file=sys.stderr)
# create table
run_query("CREATE TABLE IF NOT EXISTS trades (name STRING, value INT)")
# insert row
run_query("INSERT INTO trades VALUES('abc', 123456)")
The node-fetch
package can be installed using npm i node-fetch
.
const fetch = require("node-fetch")
const HOST = "http://127.0.0.1:9000"
async function createTable() {
try {
const query = "CREATE TABLE IF NOT EXISTS trades (name STRING, value INT)"
const response = await fetch(
`${HOST}/exec?query=${encodeURIComponent(query)}`,
)
const json = await response.json()
console.log(json)
} catch (error) {
console.log(error)
}
}
async function insertData() {
try {
const query = "INSERT INTO trades VALUES('abc', 123456)"
const response = await fetch(
`${HOST}/exec?query=${encodeURIComponent(query)}`,
)
const json = await response.json()
console.log(json)
} catch (error) {
console.log(error)
}
}
createTable().then(insertData)
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
)
func main() {
u, err := url.Parse("http://localhost:9000")
checkErr(err)
u.Path += "exec"
params := url.Values{}
params.Add("query", `
CREATE TABLE IF NOT EXISTS
trades (name STRING, value INT);
INSERT INTO
trades
VALUES(
"abc",
123456
);
`)
u.RawQuery = params.Encode()
url := fmt.Sprintf("%v", u)
res, err := http.Get(url)
checkErr(err)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
checkErr(err)
log.Println(string(body))
}
func checkErr(err error) {
if err != nil {
panic(err)
}
}
/imp - Import data
/imp
streams tabular text data directly into a table. It supports CSV, TAB and
pipe (|
) delimited inputs with optional headers. There are no restrictions on
data size. Data types and structures are detected automatically, without
additional configuration. In some cases, additional configuration can be
provided to improve the automatic detection as described in
user-defined schema.
The structure detection algorithm analyses the chunk in the beginning of the file and relies on relative uniformity of data. When the first chunk is non-representative of the rest of the data, automatic imports can yield errors.
If the data follows a uniform pattern, the number of lines which are analyzed
for schema detection can be reduced to improve performance during uploads using
the http.text.analysis.max.lines
key. Usage of this setting is described in
the HTTP server configuration
documentation.
URL parameters
/imp
is expecting an HTTP POST request using the multipart/form-data
Content-Type with following optional URL parameters which must be URL encoded:
Parameter | Required | Default | Description |
---|---|---|---|
atomicity | No | skipCol | abort , skipRow or skipCol . Behaviour when an error is detected in the data. abort : the entire file will be skipped. skipRow : the row is skipped. skipCol : the column is skipped. |
delimiter | No | URL encoded delimiter character. When set, import will try to detect the delimiter automatically. Since automatic delimiter detection requires at least two lines (rows) to be present in the file, this parameter may be used to allow single line file import. | |
fmt | No | tabular | Can be set to json to get the response formatted as such. |
forceHeader | No | false | true or false . When false , QuestDB will try to infer if the first line of the file is the header line. When set to true , QuestDB will expect that line to be the header line. |
name | No | Name of the file | Name of the table to create, see below. |
overwrite | No | false | true or false . When set to true, any existing data or structure will be overwritten. |
partitionBy | No | NONE | See partitions. |
o3MaxLag | No | Sets upper limit on the created table to be used for the in-memory out-of-order buffer. Can be also set globally via the cairo.o3.max.lag configuration property. | |
maxUncommittedRows | No | Maximum number of uncommitted rows to be set for the created table. When the number of pending rows reaches this parameter on a table, a commit will be issued. Can be also set globally via the cairo.max.uncommitted.rows configuration property. | |
skipLev | No | false | true or false . Skip “Line Extra Values”, when set to true, the parser will ignore those extra values rather than ignoring entire line. An extra value is something in addition to what is defined by the header. |
timestamp | No | Name of the column that will be used as a designated timestamp. | |
create | No | true | true or false . When set to false , QuestDB will not automatically create a table 'name ' if one does not exist, and will return an error instead. |
curl -F data=@weather.csv \
'http://localhost:9000/imp?overwrite=true&name=new_table×tamp=ts&partitionBy=MONTH'
Further example queries with context on the source CSV file contents relative and the generated tables are provided in the examples section below.
Names
Table and column names are subject to restrictions, the following list of characters are automatically removed:
[whitespace]
.
?
,
:
\
/
\\
\0
)
(
_
+
-
*
~
%
When the header row is missing, column names are generated automatically.