• influxdb-client-dart
    • Documentation
    • Features
    • Supported Platforms
    • Installation
      • Import
    • Usage
      • Creating a client
        • Client Options
        • InfluxDB 1.8 API compatibility
      • Writes
        • WriteOptions
      • Queries
        • Query to FluxRecord
        • Query to String
        • Parameterized queries
      • Delete points
      • Management API
      • Proxy configuration
    • Contributing
    • License

    Dart - 图1influxdb-client-dart

    CircleCI codecov Platforms Pub Version License GitHub issues GitHub pull requests Slack Status

    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.

    Dart - 图10Documentation

    This section contains links to the client library documentation.

    Dart - 图11Features

    InfluxDB 2.x client supports:

    • Querying data using the Flux language
      • Streaming result to Stream<FluxRecord>
    • 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

    Dart - 图12Supported Platforms

    Library works in web, server, and Flutter.

    Dart - 图13Installation

    Dart developer can add it as a dependency in their pubspec.yaml:

    1. dependencies:
    2. influxdb_client: ^2.2.0

    Dart - 图14Import

    1. import 'package:influxdb_client/api.dart';

    Dart - 图15Usage

    Important: You should call close() at the end of your application to release allocated resources.

    Dart - 图16Creating a client

    Specify url and token via parameters:

    1. var client = InfluxDBClient(
    2. url: 'http://localhost:8086',
    3. token: 'my-token',
    4. org: 'my-org',
    5. bucket: 'my-bucket',
    6. debug: true);

    Dart - 图17Client Options

    OptionDescriptionTypeDefault
    urlInfluxDB urlStringnone
    bucketDefault destination bucket for writesStringnone
    orgDefault organization bucket for writesStringnone
    debugEnable verbose logging of underlying http clientboolfalse

    Dart - 图18InfluxDB 1.8 API compatibility

    1. var client = InfluxDBClient.connectV1(
    2. url: 'http://localhost:8086',
    3. database: 'mydb',
    4. retentionPolicy: 'autogen',
    5. username: 'my-username',
    6. password: 'my-password',
    7. );

    Dart - 图19Writes

    The WriteApi supports asynchronous writes into InfluxDB 2.x.

    The data could be written as:

    1. String that is formatted as a InfluxDB’s Line Protocol
    2. Data Point structure
    3. Array of above items

    The following example demonstrates how to write data with different type of records. For further information see docs and examples.

    1. import 'package:influxdb_client/api.dart';
    2. main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. bucket: 'my-bucket',
    8. debugEnabled: true);
    9. var writeApi = WriteService(client);
    10. var point = Point('h2o')
    11. .addTag('location', 'Prague')
    12. .addField('level', 1.12345)
    13. .time(DateTime.now().toUtc());
    14. await writeApi.write(point).then((value) {
    15. print('Write completed 1');
    16. }).catchError((exception) {
    17. // error block
    18. print("Handle write error here!");
    19. print(exception);
    20. });
    21. }

    Dart - 图20WriteOptions

    Settings for WriteService like batching, default tags, retry strategy, precision, can customized in `WriteOptions’.

    Example how to modify default WriteOptions:

    1. var client = InfluxDBClient(
    2. url: 'http://localhost:8086',
    3. token: 'my-token',
    4. org: 'my-org',
    5. bucket: 'my-bucket',
    6. debug: true);
    7. var writeApi = client.getWriteService(WriteOptions().merge(
    8. precision: WritePrecision.s,
    9. batchSize: 100,
    10. flushInterval: 5000,
    11. gzip: true));

    Dart - 图21Queries

    The result retrieved by QueryService could be formatted as a:

    Dart - 图22Query to FluxRecord

    1. import 'package:influxdb_client/api.dart';
    2. void main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. bucket: 'my-bucket',
    8. );
    9. var queryService = client.getQueryService();
    10. var recordStream = await queryService.query('''
    11. from(bucket: "my-bucket")
    12. |> range(start: 0)
    13. |> filter(fn: (r) => r["_measurement"] == "cpu")
    14. |> filter(fn: (r) => r["cpu"] == "cpu-total")
    15. |> aggregateWindow(every: 1m, fn: mean, createEmpty: false)
    16. |> yield(name: "mean")
    17. ''');
    18. var count = 0;
    19. await recordStream.forEach((record) {
    20. print(
    21. 'record: ${count++} ${record['_time']}: ${record['host']} ${record['cpu']} ${record['_value']}');
    22. });
    23. client.close();
    24. }

    Dart - 图23Query to String

    1. import 'package:influxdb_client/api.dart';
    2. main() async {
    3. var client = InfluxDBClient(url: 'http://localhost:8086',
    4. token: 'my-token', org: 'my-org', bucket: 'my-bucket');
    5. var queryService = client.getQueryService(client);
    6. var rawCSV = await queryService.queryRaw('''
    7. from(bucket: "my-bucket")
    8. |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
    9. |> filter(fn: (r) => r["_measurement"] == "h2o")
    10. |> aggregateWindow(every: v.windowPeriod, fn: mean, createEmpty: false)
    11. |> yield(name: "mean")''');
    12. print(rawCSV);
    13. }

    Dart - 图24Parameterized queries

    InfluxDB Cloud supports Parameterized Queries 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.

    1. import 'package:influxdb_client/api.dart';
    2. void main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. bucket: 'my-bucket',
    8. );
    9. var queryService = client.getQueryService();
    10. var queryService = client.getQueryService();
    11. var queryString = '''
    12. from(bucket: params.bucketParam)
    13. |> range(start: duration(v: params.startParam))
    14. |> filter(fn: (r) => r["_measurement"] == "weather"
    15. and r["location"] == "Prague")''';
    16. var queryParams = {'bucketParam':'my-bucket', 'startParam':'-10d'};
    17. var query = Query(query: queryString, params: queryParams);
    18. // Using string for query and Map for params
    19. var recordMap = await queryService.query(queryString, params: queryParams);
    20. // Using Query class
    21. var recordClass = await queryService.query(query);
    22. client.close();
    23. }

    Dart - 图25Delete points

    The DeleteService supports deletes points from an InfluxDB bucket.

    InfluxDB uses an InfluxQL-like predicate syntax to determine what data points to delete.

    1. import 'package:influxdb_client/api.dart';
    2. void main() async {
    3. var client = InfluxDBClient(
    4. url: 'http://localhost:8086',
    5. token: 'my-token',
    6. org: 'my-org',
    7. bucket: 'my-bucket',
    8. debugEnabled: true);
    9. await client
    10. .getDeleteService()
    11. .delete(
    12. predicate: '_measurement="temperature"',
    13. start: '1970-01-01T00:00:00.000000001Z',
    14. stop: DateTime.now().toUtc().toIso8601String(),
    15. bucket: 'my-bucket',
    16. org: 'my-org')
    17. .catchError((e) => print(e));
    18. var queryService = client.getQueryService();
    19. var fluxQuery = '''
    20. from(bucket: "my-bucket")
    21. |> range(start: -1d)
    22. |> filter(fn: (r) => r["_measurement"] == "temperature")
    23. ''';
    24. // should be empty
    25. var records = await queryService.query(fluxQuery);
    26. assert(await records.isEmpty);
    27. client.close();
    28. }

    Dart - 图26Management API

    The client supports following management API:

    API docs
    AuthorizationsAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Authorizations
    BucketsAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Buckets
    DBRPsAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/DBRPs
    DeleteAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Delete
    HealthAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Health
    LabelsAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Labels
    OrganizationsAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Organizations
    PingAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Ping
    ReadyAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Ready
    SecretsAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Secrets
    SetupAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Setup
    TasksAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Tasks
    UsersAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Users
    VariablesAPIhttps://docs.influxdata.com/influxdb/latest/api/#tag/Variables

    The following example demonstrates how to use a InfluxDB 2.x Management API to create new bucket. For further information see docs and examples.

    1. import 'package:influxdb_client/api.dart';
    2. void main() async {
    3. // Initialize Client and API
    4. var client = InfluxDBClient(
    5. url: 'http://localhost:8086', token: 'my-token', org: 'my-org');
    6. //check server availability
    7. await client.getPingApi().getPing();
    8. var orgs = await client.getOrganizationsApi().getOrgs();
    9. var myOrgId = orgs.orgs.first.id;
    10. var bucketsApi = client.getBucketsApi();
    11. var bucketName = 'bucket-my-org';
    12. // find and delete bucket 'bucket-my-org'
    13. var buckets = await bucketsApi.getBuckets(name: bucketName);
    14. if (buckets.buckets.isNotEmpty) {
    15. var bucketID = buckets.buckets.first.id;
    16. await bucketsApi.deleteBucketsID(bucketID);
    17. print('Bucket $bucketID was deleted.');
    18. }
    19. // Bucket configuration
    20. var request = PostBucketRequest(
    21. orgID: myOrgId,
    22. name: bucketName,
    23. retentionRules: [
    24. RetentionRule(type: RetentionRuleTypeEnum.expire, everySeconds: 3600)
    25. ]);
    26. var bucket = await bucketsApi.postBuckets(request);
    27. // Create Authorization with permission to read/write created bucket
    28. var bucketResource =
    29. Resource(type: ResourceTypeEnum.buckets, id: bucket.id, orgID: myOrgId);
    30. // Authorization configuration
    31. var auth = AuthorizationPostRequest(
    32. description: 'Authorization to read/write bucket:${bucket.name}',
    33. orgID: myOrgId,
    34. permissions: [
    35. Permission(action: PermissionActionEnum.read, resource: bucketResource),
    36. Permission(action: PermissionActionEnum.write, resource: bucketResource)
    37. ]);
    38. // Create Authorization
    39. var authorizationsApi = client.getAuthorizationsApi();
    40. var authorization = await authorizationsApi.postAuthorizations(auth);
    41. // Print token
    42. var token = authorization.token;
    43. print('The bucket: \'${bucket.name}\' is successfully created.');
    44. print('The following token can be used to read/write: ${token}');
    45. client.close();
    46. }

    Dart - 图27Proxy configuration

    By default the HttpClient uses the proxy configuration available from the environment, see findProxyFromEnvironment.

    1. export http_proxy="PROXY http://localhost:8080"

    Initialize a proxy from code:

    1. HttpClient httpClient = HttpClient();
    2. httpClient.findProxy = (url) => "PROXY localhost:8080";
    3. var client = IOClient(httpClient);
    4. var influxdb = InfluxDBClient(
    5. url: 'http://localhost:8086',
    6. token: 'my-token',
    7. org: 'my-org',
    8. bucket: 'my-bucket',
    9. client: client,
    10. followRedirects: true,
    11. maxRedirects: 5,
    12. debug: true);

    To turn off the use of proxies set the findProxy property to null.

    Client automatically follows 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.

    Dart - 图28Contributing

    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:

    1. ./scripts/influxdb-restart.sh
    2. dart test

    Check code coverage:

    1. ./scripts/influxdb-restart.sh
    2. dart test --enable-code-coverage

    Dart - 图29License

    The client is available as open source under the terms of the MIT License.