InfluxDB Python Client

1.50.0 · active · verified Thu Apr 09

The official Python client library for InfluxDB 2.0+, providing comprehensive API access for writing, querying (Flux), and managing InfluxDB resources. It is actively maintained with frequent minor releases, typically on a monthly to bi-monthly cadence.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the InfluxDBClient, write a single data point using the synchronous write API, and then query data using a basic Flux query. Remember to replace placeholder environment variables with your actual InfluxDB 2.x connection details (URL, Token, Organization, Bucket).

import os
from influxdb_client import InfluxDBClient, Point, WriteOptions
from influxdb_client.client.write_api import SYNCHRONOUS

# Configuration from environment variables for security and flexibility
INFLUXDB_URL = os.environ.get('INFLUXDB_URL', 'http://localhost:8086')
INFLUXDB_TOKEN = os.environ.get('INFLUXDB_TOKEN', 'YOUR_INFLUXDB_TOKEN')
INFLUXDB_ORG = os.environ.get('INFLUXDB_ORG', 'YOUR_INFLUXDB_ORG')
INFLUXDB_BUCKET = os.environ.get('INFLUXDB_BUCKET', 'YOUR_INFLUXDB_BUCKET')

if 'YOUR_INFLUXDB_TOKEN' in INFLUXDB_TOKEN or 'YOUR_INFLUXDB_ORG' in INFLUXDB_ORG or 'YOUR_INFLUXDB_BUCKET' in INFLUXDB_BUCKET:
    print("WARNING: Please set INFLUXDB_URL, INFLUXDB_TOKEN, INFLUXDB_ORG, and INFLUXDB_BUCKET environment variables or update the quickstart code.")

print(f"Connecting to InfluxDB at {INFLUXDB_URL} for org '{INFLUXDB_ORG}'")

with InfluxDBClient(url=INFLUXDB_URL, token=INFLUXDB_TOKEN, org=INFLUXDB_ORG) as client:
    # 1. Write data point
    write_api = client.write_api(write_options=WriteOptions(batch_size=1, flush_interval=1_000, write_type=SYNCHRONOUS))
    point = Point("my_measurement") \
        .tag("location", "us-west") \
        .field("temperature", 25.0) \
        .field("humidity", 60.5)

    try:
        write_api.write(bucket=INFLUXDB_BUCKET, record=point)
        print(f"Successfully wrote point: {point.to_line_protocol()}")
    except Exception as e:
        print(f"Error writing point: {e}")

    # 2. Query data using Flux
    query_api = client.query_api()
    query = f'from(bucket: "{INFLUXDB_BUCKET}") |> range(start: -1h) |> filter(fn: (r) => r._measurement == "my_measurement")'

    print(f"Executing Flux query:\n{query}")
    try:
        tables = query_api.query(query, org=INFLUXDB_ORG)
        for table in tables:
            for record in table.records:
                print(f"  Queried: {record.get_measurement()}, {record.get_field()}="{record.get_value()}" at {record.get_time()}")
    except Exception as e:
        print(f"Error querying data: {e}")

print("Client closed.")

view raw JSON →