influxdb-client-dart
This repository contains the reference Dart client for the InfluxDB 2.x. It works on all platforms including web, server, and Flutter. Please submit issues and pull requests, help out, or just give encouragement.
This section contains links to the client library documentation.
Features
InfluxDB 2.x client supports:
- Querying data using the Flux language
- Streaming result to
- Writing data
- batched in chunks on background
- automatic retries on write failures
- Management API
- provides all other InfluxDB 2.x APIs for managing
- health check
- sources, buckets
- tasks
- authorizations
- …
- provides all other InfluxDB 2.x APIs for managing
Library works in web, server, and Flutter.
Installation
Dart developer can add it as a dependency in their pubspec.yaml:
import 'package:influxdb_client/api.dart';
Creating a client
Specify url and token via parameters:
var client = InfluxDBClient(
url: 'http://localhost:8086',
token: 'my-token',
org: 'my-org',
bucket: 'my-bucket',
debug: true);
Client Options
InfluxDB 1.8 API compatibility
var client = InfluxDBClient(
url: 'http://localhost:8086',
username: '...',
password: '...',
org: 'my-org',
bucket: 'my-bucket',
debug: true);
The WriteApi supports asynchronous writes into InfluxDB 2.x.
The data could be written as:
String
that is formatted as a InfluxDB’s Line Protocol- structure
- Array of above items
The following example demonstrates how to write data with different type of records. For further information see docs and examples.
import 'package:influxdb_client/api.dart';
main() async {
var client = InfluxDBClient(
url: 'http://localhost:8086',
token: 'my-token',
org: 'my-org',
debugEnabled: true);
var writeApi = WriteService(client);
var point = Point('h2o')
.addTag('location', 'Prague')
.addField('level', 1.12345)
.time(DateTime.now().toUtc());
await writeApi.write(point).then((value) {
print('Write completed 1');
}).catchError((exception) {
// error block
print("Handle write error here!");
print(exception);
});
}
WriteOptions
Example how to modify default WriteOptions
:
- sources -
Queries
The result retrieved by QueryService could be formatted as a:
Query to FluxRecord
import 'package:influxdb_client/api.dart';
void main() async {
var client = InfluxDBClient(
url: 'http://localhost:8086',
token: 'my-token',
org: 'my-org',
bucket: 'my-bucket',
);
var queryService = client.getQueryService();
var recordStream = await queryService.query('''
from(bucket: "my-bucket")
|> range(start: 0)
|> filter(fn: (r) => r["_measurement"] == "cpu")
|> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
|> yield(name: "mean")
''');
var count = 0;
await recordStream.forEach((record) {
print(
'record: ${count++} ${record['_time']}: ${record['host']} ${record['cpu']} ${record['_value']}');
});
client.close();
}
Query to String
import 'package:influxdb_client/api.dart';
main() async {
var client = InfluxDBClient(url: 'http://localhost:8086',
token: 'my-token', org: 'my-org', bucket: 'my-bucket');
var queryService = client.getQueryService(client);
var rawCSV = await queryService.queryRaw('''
from(bucket: "my-bucket")
|> range(start: v.timeRangeStart, stop: v.timeRangeStop)
|> filter(fn: (r) => r["_measurement"] == "h2o")
|> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
|> yield(name: "mean")''');
print(rawCSV);
}
Parameterized queries
InfluxDB Cloud supports that let you dynamically change values in a query using the InfluxDB API. Parameterized queries make Flux queries more reusable and can also be used to help prevent injection attacks.
InfluxDB Cloud inserts the params object into the Flux query as a Flux record named params
. Use dot or bracket notation to access parameters in the params
record in your Flux query. Parameterized Flux queries support only int
, float
, and string
data types. To convert the supported data types into other Flux basic data types, use Flux type conversion functions.
Parameterized query example:
⚠️ Parameterized Queries are supported only in InfluxDB Cloud, currently there is no support in InfluxDB OSS.
import 'package:influxdb_client/api.dart';
void main() async {
var client = InfluxDBClient(
url: 'http://localhost:8086',
token: 'my-token',
org: 'my-org',
);
var queryService = client.getQueryService();
var queryService = client.getQueryService();
var queryString = '''
from(bucket: params.bucketParam)
|> range(start: duration(v: params.startParam))
|> filter(fn: (r) => r["_measurement"] == "weather"
and r["location"] == "Prague")''';
var queryParams = {'bucketParam':'my-bucket', 'startParam':'-10d'};
var query = Query(query: queryString, params: queryParams);
// Using string for query and Map for params
var recordMap = await queryService.query(queryString, params: queryParams);
// Using Query class
client.close();
}
The supports deletes points from an InfluxDB bucket.
InfluxDB uses an InfluxQL-like syntax to determine what data points to delete.
import 'package:influxdb_client/api.dart';
void main() async {
var client = InfluxDBClient(
url: 'http://localhost:8086',
token: 'my-token',
org: 'my-org',
bucket: 'my-bucket',
debugEnabled: true);
await client
.getDeleteService()
.delete(
predicate: '_measurement="temperature"',
start: '1970-01-01T00:00:00.000000001Z',
stop: DateTime.now().toUtc().toIso8601String(),
bucket: 'my-bucket',
org: 'my-org')
.catchError((e) => print(e));
var queryService = client.getQueryService();
var fluxQuery = '''
from(bucket: "my-bucket")
|> range(start: -1d)
|> filter(fn: (r) => r["_measurement"] == "temperature")
''';
// should be empty
var records = await queryService.query(fluxQuery);
assert(await records.isEmpty);
client.close();
}
Management API
The client supports following management API:
The client supports following management API:
By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment.
export http_proxy="PROXY http://localhost:8080"
Initialize a proxy from code:
HttpClient httpClient = HttpClient();
httpClient.findProxy = (url) => "PROXY localhost:8080";
var client = IOClient(httpClient);
var influxdb = InfluxDBClient(
url: 'http://localhost:8086',
token: 'my-token',
org: 'my-org',
bucket: 'my-bucket',
client: client,
followRedirects: true,
maxRedirects: 5,
debug: true);
To turn off the use of proxies set the findProxy
property to null.
Client HTTP redirects for all GET and HEAD requests with status codes 301, 302, 303, 307, 308. The default redirect policy is to follow up to 5 consecutive requests.
write
and query
APIs also support an automatic redirect of POST requests. You can disable followRedirects
and change default maxRedirects
on InfluxDBClient
instance.
Contributing
If you would like to contribute code you can do through GitHub by forking the repository and sending a pull request into the master
branch.
Build Requirements:
- dart 2.X
Build source and test targets:
./scripts/influxdb-restart.sh
dart test
Check code coverage:
The client is available as open source under the terms of the MIT License.