API 快速开始
InfluxDB 提供丰富的 API 和 客户端库,可与您的应用程序集成。使用流行工具如 Curl 和 Postman 快速测试 API 请求。
本节指导您使用最常用的API方法。
有关整个API的详细文档,请参见InfluxDB v2 API参考。
如果您需要使用 InfluxDB Cloud 与 InfluxDB 1.x API 客户端和集成,请参阅 1.x 兼容 API。
引导你的应用程序
对于大多数API请求,您需要至少提供您的InfluxDB URL和授权令牌(API令牌)。
安装 InfluxDB OSS v2.x 或升级到 一个 InfluxDB Cloud 帐户。
认证
InfluxDB使用API tokens来授权API请求。
在探索API之前,使用InfluxDB UI为您的应用程序创建初始API令牌。
在每个请求中将您的API令牌包含在
Authorization: Token YOUR_API_TOKENHTTP头中。
#######################################
# Use a token in the Authorization header
# to authenticate with the InfluxDB 2.x API.
#######################################
curl --get "http://localhost:8086/api/v2" \
--header "Authorization: Token YOUR_API_TOKEN" \
--header 'Content-type: application/json' \
--data-urlencode "db=mydb" \
--data-urlencode "q=SELECT * FROM cpu_usage"
/**
* Use a token in the Authorization header
* to authenticate with the InfluxDB 2.x API.
*/
const https = require('https');
function queryWithToken() {
const options = {
host: 'localhost:8086',
path: "/api/v2",
headers: {
'Authorization': 'Token YOUR_API_TOKEN',
'Content-type': 'application/json'
},
};
const request = https.get(options, (response) => {
let rawData = '';
response.on('data', () => {
response.on('data', (chunk) => { rawData += chunk; });
})
response.on('end', () => {
console.log(rawData);
})
});
request.end();
}
Postman 是另一个流行的 API 探索工具。看看如何 使用 Postman 发送认证请求。
桶 API
在写入数据之前,您需要在InfluxDB中创建一个存储桶。创建一个存储桶,使用HTTP请求到InfluxDB API /buckets 端点。
INFLUX_TOKEN=YOUR_API_TOKEN
INFLUX_ORG_ID=YOUR_ORG_ID
curl --request POST \
"http://localhost:8086/api/v2/buckets" \
--header "Authorization: Token ${INFLUX_TOKEN}" \
--header "Content-type: application/json" \
--data '{
"orgID": "'"${INFLUX_ORG_ID}"'",
"name": "iot-center",
"retentionRules": [
{
"type": "expire",
"everySeconds": 86400,
"shardGroupDurationSeconds": 0
}
]
}'
编写API
通过HTTP请求将数据写入InfluxDB,使用InfluxDB API /api/v2/write 端点。
查询API
从InfluxDB查询,使用HTTP请求到/api/v2/query端点。