Documentation

Use InfluxDB client libraries to write data

Use InfluxDB 3 client libraries that integrate with your code to construct data as time series points, and then write them as line protocol to an InfluxDB 3 Enterprise database.

Set up your project

Set up your InfluxDB 3 Enterprise project and credentials to write data using the InfluxDB 3 client library for your programming language of choice.

  1. Install InfluxDB 3 Enterprise
  2. Set up InfluxDB 3 Enterprise
  3. Create a project directory and store your InfluxDB 3 Enterprise credentials as environment variables or in a project configuration file, such as a .env (“dotenv”) file.

After setting up InfluxDB 3 Enterprise and your project, you should have the following:

  • InfluxDB 3 Enterprise credentials:

  • A directory for your project.

  • Credentials stored as environment variables or in a project configuration file–for example, a .env (“dotenv”) file.

Initialize a project directory

Create a project directory and initialize it for your programming language.

  1. Install Go 1.13 or later.

  2. Create a directory for your Go module and change to the directory–for example:

    mkdir iot-starter-go && cd $_
    
    • Copy
    • Fill window
  3. Initialize a Go module–for example:

    go mod init iot-starter
    
    • Copy
    • Fill window
  1. Install Node.js.

  2. Create a directory for your JavaScript project and change to the directory–for example:

    mkdir -p iot-starter-js && cd $_
    
    • Copy
    • Fill window
  3. Initialize a project–for example, using npm:

    npm init
    
    • Copy
    • Fill window
  1. Install Python

  2. Inside of your project directory, create a directory for your Python module and change to the module directory–for example:

    mkdir -p iot-starter-py && cd $_
    
    • Copy
    • Fill window
  3. Optional, but recommended: Use venv or conda to activate a virtual environment for installing and executing code–for example, enter the following command using venv to create and activate a virtual environment for the project:

    python3 -m venv envs/iot-starter && source ./envs/iot-starter/bin/activate
    
    • Copy
    • Fill window

Install the client library

Install the InfluxDB 3 client library for your programming language of choice.

Add the InfluxDB 3 C# client library to your project using the dotnet CLI or by adding the package to your project file–for example:

dotnet add package InfluxDB3.Client
  • Copy
  • Fill window

Add the InfluxDB 3 Go client library to your project using the go get command–for example:

go mod init path/to/project/dir && cd $_
go get github.com/InfluxCommunity/influxdb3-go/v2/influxdb3
  • Copy
  • Fill window

Add the InfluxDB 3 Java client library to your project dependencies using the Maven Gradle build tools.

For example, to add the library to a Maven project, add the following dependency to your pom.xml file:

<dependency>
  <groupId>com.influxdb</groupId>
  <artifactId>influxdb3-java</artifactId>
  <version>1.1.0</version>
</dependency>
  • Copy
  • Fill window

To add the library to a Gradle project, add the following dependency to your build.gradle file:

dependencies {
  implementation 'com.influxdb:influxdb3-java:1.1.0'
}
  • Copy
  • Fill window

For a Node.js project, use @influxdata/influxdb3-client, which provides main (CommonJS), module (ESM), and browser (UMD) exports. Add the InfluxDB 3 JavaScript client library using your preferred package manager–for example, using npm:

npm install --save @influxdata/influxdb3-client
  • Copy
  • Fill window

Install the InfluxDB 3 Python client library using pip. To use Pandas features, such as to_pandas(), provided by the Python client library, you must also install the pandas package.

pip install influxdb3-python pandas
  • Copy
  • Fill window

Construct line protocol

With a basic understanding of line protocol, you can construct line protocol data and write it to InfluxDB 3 Enterprise.

Use client library write methods to provide data as raw line protocol or as Point objects that the client library converts to line protocol. If your program creates the data you write to InfluxDB, the Point interface to take advantage of type safety in your program.

Client libraries provide one or more Point constructor methods. Some libraries support language-native data structures, such as Go’s struct, for creating points.

Examples in this guide show how to construct Point objects that follow the example home schema, and then write the points as line protocol data to an InfluxDB 3 Enterprise database.

Example home schema

Consider a use case where you collect data from sensors in your home. Each sensor collects temperature, humidity, and carbon monoxide readings.

To collect this data, use the following schema:

  • table: home
    • tags
      • room: Living Room or Kitchen
    • fields
      • temp: temperature in °C (float)
      • hum: percent humidity (float)
      • co: carbon monoxide in parts per million (integer)
    • timestamp: Unix timestamp in second precision
  1. Create a file for your module–for example: main.go.

  2. In main.go, enter the following sample code:

    package main
    
    import (
     "context"
     "os"
     "fmt"
     "time"
     "github.com/InfluxCommunity/influxdb3-go/v2/influxdb3"
     "github.com/influxdata/line-protocol/v2/lineprotocol"
    )
    
    func Write() error {
      url := os.Getenv("INFLUX_HOST")
      token := os.Getenv("INFLUX_TOKEN")
      database := os.Getenv("INFLUX_DATABASE")
    
      // To instantiate a client, call New() with InfluxDB credentials.
      client, err := influxdb3.New(influxdb3.ClientConfig{
       Host: url,
       Token: token,
       Database: database,
      })
    
      /** Use a deferred function to ensure the client is closed when the
        * function returns.
       **/
      defer func (client *influxdb3.Client)  {
       err = client.Close()
       if err != nil {
         panic(err)
       }
      }(client)
    
      /** Use the NewPoint method to construct a point.
        * NewPoint(measurement, tags map, fields map, time)
       **/
      point := influxdb3.NewPoint("home",
         map[string]string{
           "room": "Living Room",
         },
         map[string]any{
           "temp": 24.5,
           "hum":  40.5,
           "co":   15i},
         time.Now(),
       )
    
      /** Use the NewPointWithMeasurement method to construct a point with
        * method chaining.
       **/
      point2 := influxdb3.NewPointWithMeasurement("home").
       SetTag("room", "Living Room").
       SetField("temp", 23.5).
       SetField("hum", 38.0).
       SetField("co",  16i).
       SetTimestamp(time.Now())
    
      fmt.Println("Writing points")
      points := []*influxdb3.Point{point, point2}
    
      /** Write points to InfluxDB.
        * You can specify WriteOptions, such as Gzip threshold,
        * default tags, and timestamp precision. Default precision is lineprotocol.Nanosecond
       **/
      err = client.WritePoints(context.Background(), points,
        influxdb3.WithPrecision(lineprotocol.Second))
      return nil
    }
    
    func main() {
      Write()
    }
    
    • Copy
    • Fill window
  3. To run the module and write the data to your InfluxDB 3 Enterprise database, enter the following command in your terminal:

    go run main.go
    
    • Copy
    • Fill window
  1. Create a file for your module–for example: write-points.js.

  2. In write-points.js, enter the following sample code:

    // write-points.js
    import { InfluxDBClient, Point } from '@influxdata/influxdb3-client';
    
    /**
     * Set InfluxDB credentials.
     */
    const host = process.env.INFLUX_HOST ?? '';
    const database = process.env.INFLUX_DATABASE;
    const token = process.env.INFLUX_TOKEN;
    
    /**
     * Write line protocol to InfluxDB using the JavaScript client library.
     */
    export async function writePoints() {
      /**
       * Instantiate an InfluxDBClient.
       * Provide the host URL and the database token.
       */
      const client = new InfluxDBClient({ host, token });
    
      /** Use the fluent interface with chained methods to construct Points. */
      const point = Point.measurement('home')
        .setTag('room', 'Living Room')
        .setFloatField('temp', 22.2)
        .setFloatField('hum', 35.5)
        .setIntegerField('co', 7)
        .setTimestamp(new Date().getTime() / 1000);
    
      const point2 = Point.measurement('home')
        .setTag('room', 'Kitchen')
        .setFloatField('temp', 21.0)
        .setFloatField('hum', 35.9)
        .setIntegerField('co', 0)
        .setTimestamp(new Date().getTime() / 1000);
    
      /** Write points to InfluxDB.
       * The write method accepts an array of points, the target database, and
       * an optional configuration object.
       * You can specify WriteOptions, such as Gzip threshold, default tags,
       * and timestamp precision. Default precision is lineprotocol.Nanosecond
       **/
    
      try {
        await client.write([point, point2], database, '', { precision: 's' });
        console.log('Data has been written successfully!');
      } catch (error) {
        console.error(`Error writing data to InfluxDB: ${error.body}`);
      }
    
      client.close();
    }
    
    writePoints();
    
    • Copy
    • Fill window
  3. To run the module and write the data to your {{< product-name >}} database, enter the following command in your terminal:

    node writePoints.js
    
    • Copy
    • Fill window
  1. Create a file for your module–for example: write-points.py.

  2. In write-points.py, enter the following sample code to write data in batching mode:

    import os
    from influxdb_client_3 import (
      InfluxDBClient3, InfluxDBError, Point, WritePrecision,
      WriteOptions, write_client_options)
    
    host = os.getenv('INFLUX_HOST')
    token = os.getenv('INFLUX_TOKEN')
    database = os.getenv('INFLUX_DATABASE')
    
    # Create an array of points with tags and fields.
    points = [Point("home")
                .tag("room", "Kitchen")
                .field("temp", 25.3)
                .field('hum', 20.2)
                .field('co', 9)]
    
    # With batching mode, define callbacks to execute after a successful or
    # failed write request.
    # Callback methods receive the configuration and data sent in the request.
    def success(self, data: str):
        print(f"Successfully wrote batch: data: {data}")
    
    def error(self, data: str, exception: InfluxDBError):
        print(f"Failed writing batch: config: {self}, data: {data} due: {exception}")
    
    def retry(self, data: str, exception: InfluxDBError):
        print(f"Failed retry writing batch: config: {self}, data: {data} retry: {exception}")
    
    # Configure options for batch writing.
    write_options = WriteOptions(batch_size=500,
                                        flush_interval=10_000,
                                        jitter_interval=2_000,
                                        retry_interval=5_000,
                                        max_retries=5,
                                        max_retry_delay=30_000,
                                        exponential_base=2)
    
    # Create an options dict that sets callbacks and WriteOptions.
    wco = write_client_options(success_callback=success,
                              error_callback=error,
                              retry_callback=retry,
                              write_options=write_options)
    
    # Instantiate a synchronous instance of the client with your
    # InfluxDB credentials and write options, such as Gzip threshold, default tags,
    # and timestamp precision. Default precision is nanosecond ('ns').
    with InfluxDBClient3(host=host,
                            token=token,
                            database=database,
                            write_client_options=wco) as client:
    
          client.write(points, write_precision='s')
    
    • Copy
    • Fill window
  3. To run the module and write the data to your InfluxDB 3 Enterprise database, enter the following command in your terminal:

    python write-points.py
    
    • Copy
    • Fill window

The sample code does the following:

  1. Instantiates a client configured with the InfluxDB URL and API token.
  2. Constructs hometable Point objects.
  3. Sends data as line protocol format to InfluxDB and waits for the response.
  4. If the write succeeds, logs the success message to stdout; otherwise, logs the failure message and error details.
  5. Closes the client to release resources.

Was this page helpful?

Thank you for your feedback!


The future of Flux

Flux is going into maintenance mode. You can continue using it as you currently are without any changes to your code.

Read more

Now Generally Available

InfluxDB 3 Core and Enterprise

Start fast. Scale faster.

Get the Updates

InfluxDB 3 Core is an open source, high-speed, recent-data engine that collects and processes data in real-time and persists it to local disk or object storage. InfluxDB 3 Enterprise builds on Core’s foundation, adding high availability, read replicas, enhanced security, and data compaction for faster queries and optimized storage. A free tier of InfluxDB 3 Enterprise is available for non-commercial at-home or hobbyist use.

For more information, check out: