Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 39 ยท Writing Data

Writing with Client Libraries

Write and read InfluxDB data from Python, JavaScript and Go with the official client libraries, the Point builder, write options and error handling.

You could build line protocol strings and POST them yourself, but you would then also own escaping, batching, retries, compression and authentication. Client libraries do all of that. InfluxData maintains official libraries for Python, JavaScript/TypeScript, Go, Java, C#, PHP, Ruby, Rust and more; the community covers the rest.

This lesson shows the shape of a client program in three languages and builds a small stand-in of the fluent Point builder, so the library calls feel familiar.

The Python, JavaScript and Go code below is read-only: it needs a server, a token and an installed package. Package names and method names changed between the 2.x clients and the 3.x clients, so check the documentation of the version you use. The runnable blocks are our own JavaScript imitation of the builder.

Which library for which version

Server Python JavaScript Go
InfluxDB 2.x influxdb-client @influxdata/influxdb-client influxdb-client-go
InfluxDB 3.x influxdb3-python (module influxdb_client_3) @influxdata/influxdb3-client influxdb3-go

3.x clients speak the 3.x write API and query through Apache Arrow Flight (SQL and InfluxQL), which returns results as columnar tables. 2.x clients use the 2.x write and Flux query APIs. Do not mix them: using a 2.x client with a 3.x-only feature (or the other way round) leads to confusing errors.

Python (3.x client)

Python
from influxdb_client_3 import InfluxDBClient3, Point

client = InfluxDBClient3(
    host="http://localhost:8181",
    token="YOUR_TOKEN",
    database="weather",
)

point = (
    Point("weather")
    .tag("city", "Lisbon")
    .field("temp", 18.4)
    .field("humidity", 62)
)
client.write(record=point)

table = client.query("SELECT time, city, temp FROM weather ORDER BY time DESC LIMIT 5")
print(table.to_pandas())
client.close()

Point is a builder: tag adds to the tag set, field to the field set; the library escapes and serialises. Reading returns a PyArrow table, which converts to pandas with one call. Remember close() (or a with block) so buffered writes are flushed.

Python (2.x client)

Python
from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS

with InfluxDBClient(url="http://localhost:8086", token="YOUR_TOKEN", org="my-org") as client:
    write_api = client.write_api(write_options=SYNCHRONOUS)
    write_api.write(bucket="weather", record=Point("weather").tag("city", "Lisbon").field("temp", 18.4))

    flux = 'from(bucket:"weather") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "weather")'
    for table in client.query_api().query(flux):
        for row in table.records:
            print(row.get_time(), row.get_field(), row.get_value())

SYNCHRONOUS waits for each write. The default is a batching write API that buffers in the background, which is faster but needs a proper close().

JavaScript

JavaScript
import { InfluxDB, Point } from '@influxdata/influxdb-client'

const client = new InfluxDB({ url: 'http://localhost:8086', token: process.env.INFLUX_TOKEN })
const writeApi = client.getWriteApi('my-org', 'weather', 's') // precision: seconds

const point = new Point('weather')
  .tag('city', 'Lisbon')
  .floatField('temp', 18.4)
  .intField('humidity', 62)
  .timestamp(new Date())

writeApi.writePoint(point)
await writeApi.close() // flushes the buffer

Typed methods such as floatField and intField exist because JavaScript has only one number type: the library cannot guess whether 62 should be an integer or a float, so you say it. This is exactly the field-type problem from the types lesson.

Go

Go
client := influxdb3.New(influxdb3.ClientConfig{
    Host:     "http://localhost:8181",
    Token:    os.Getenv("INFLUXDB3_TOKEN"),
    Database: "weather",
})
defer client.Close()

p := influxdb3.NewPointWithMeasurement("weather").
    SetTag("city", "Lisbon").
    SetField("temp", 18.4).
    SetTimestamp(time.Now())

if err := client.WritePoints(context.Background(), []*influxdb3.Point{p}); err != nil {
    log.Fatal(err)
}

Imitating the Point builder

This stand-in implements a small fluent builder with escaping and explicit field types. It is not an official library, but writing it makes the official APIs predictable.

JS A fluent Point builder (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A write-then-read round trip

The next stand-in mimics write_api.write followed by query, with an in-memory store and a time filter. It demonstrates the typical program structure: connect, write, read, close.

JS Write, query, close (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Good habits with clients

  • Create one client for the process and reuse it; do not open a new one per write.
  • Close it on shutdown so that buffers flush.
  • Read the token from an environment variable or a secret store, never from source code.
  • Set timestamps explicitly if you may retry.
  • Use typed field methods for numbers; log write errors (the batching API reports them through callbacks).
  • For bulk loads from files or DataFrames, use the library's DataFrame or CSV helpers instead of looping point by point.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why do JavaScript clients have floatField and intField methods?

    You must say whether 62 is an integer or a float to avoid field type conflicts.
  2. 2. What should you do before a program exits when using a batching write API?

    Points in the buffer are lost if the process ends without a flush.
  3. 3. How do 3.x clients return query results in Python?

    3.x queries use Arrow Flight and return columnar tables.
  4. 4. Where should the token come from?

    Hard-coded tokens leak through repositories and logs.

Summary

  • Official client libraries handle escaping, batching, retries, compression and authentication.
  • Choose the client that matches your server generation; 2.x and 3.x clients differ.
  • A fluent Point builder adds tags, typed fields and a timestamp; always close the client to flush.
  • Keep tokens in the environment, reuse one client per process and use typed fields.

Next: Collecting Metrics with Telegraf