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.
Install & Compatibility
Where this runs
tested against v1.50.0 · pip install
no network on importno background threads
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
muslpy 3.10–3.960 runs
installs and imports cleanly · install 0.0s · import 0.815s · 30.9MB
glibcpy 3.10–3.960 runs
installs and imports cleanly · install 2.6s · import 0.711s · 31MB
30MB installed
● package 30MB
Code
Verified usage
Verified import paths — ran on the pinned version, not inferred.
InfluxDBClient
✓ from influxdb_client import InfluxDBClient
Point
✓ from influxdb_client import Point
WriteOptions
✓ from influxdb_client import WriteOptions
SYNCHRONOUS
✓ from influxdb_client.client.write_api import SYNCHRONOUS
✗ from influxdb_client import SYNCHRONOUS
SYNCHRONOUS is part of the write_api module, not top-level.
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.")
Debug
Known issues
breakingThis client is specifically designed for InfluxDB 2.0+ (Flux API) and is NOT compatible with InfluxDB 1.x HTTP API endpoints. Trying to connect to an InfluxDB 1.x instance will result in authentication or API endpoint errors.fixEnsure you are connecting to an InfluxDB 2.x instance or use the `influxdb` client library for InfluxDB 1.x.
affects: All versions
gotchaThe default write API is asynchronous (batching and buffering). For immediate writes, ensure you specify `write_type=SYNCHRONOUS` in `WriteOptions`. Not doing so can lead to data not appearing immediately in queries or being lost if the application crashes before the buffer is flushed.fixWhen creating the write API, use `client.write_api(write_options=WriteOptions(write_type=SYNCHRONOUS))` for guaranteed immediate writes. For high-throughput scenarios, carefully configure batch size and flush interval.
affects: All versions
gotchaOlder versions (pre-1.42.0) had issues with serializing Pandas DataFrames containing `NaN` (Not a Number) values, leading to errors or incorrect data storage.fixUpgrade to `influxdb-client` version 1.42.0 or newer to ensure correct handling of `NaN` values in DataFrames. Alternatively, pre-process DataFrames to handle or remove `NaN` values before writing.
affects: <1.42.0
gotchaThe client requires Python 3.7 or newer. Using older Python versions will result in `SyntaxError` or `ImportError` due to modern language features and type hinting.fixEnsure your environment uses Python 3.7 or a more recent version (e.g., Python 3.8, 3.9, 3.10, 3.11, 3.12).
affects: All versions
deprecatedSeveral internal `urllib` calls and `datetime` timezone helper functions were replaced or refactored in recent versions to avoid deprecated Python functions. While this mainly affects internal workings, it's good practice to update.fixUpgrade to `influxdb-client` version 1.45.0 or newer to benefit from these fixes and avoid potential warnings or compatibility issues with newer Python versions.
affects: <1.45.0 for datetime, <1.43.0 for urllib
gotchaExample or test scripts may contain a `SyntaxError` related to incorrect f-string formatting, particularly when attempting to embed quoted string literals directly within an f-string that uses the same quote type. For instance, using `f"... {variable}="{value}" ..."` will cause a `SyntaxError`.fixReview example code for proper f-string syntax. Ensure inner quoted strings are properly escaped (e.g., `\"`) or use different quote types for the f-string itself (e.g., `f'...'` for the outer string if inner parts need `"`).
affects: All versions (where such examples exist)
Errors
Common errors & fixes
ModuleNotFoundError: No module named 'influxdb_client'
This error often occurs when the `influxdb-client` library is not installed, or when there's a confusion between the `influxdb` (for InfluxDB 1.x) and `influxdb-client` (for InfluxDB 2.x) packages, or if using an incorrect Python environment.
fixEnsure you have the correct client installed for InfluxDB 2.x and that your Python environment is active. Use `pip install influxdb-client` or `pip install 'influxdb-client[ciso]'` for faster date parsing.
Reason: Unauthorized HTTP response headers: HTTPHeaderDict({'Content-Type': 'application/json; charset=utf-8', 'X-Influxdb-Build': 'OSS', 'X-Influxdb-Version': 'v2.7.0', 'X-Platform-Error-Code': 'unauthorized', 'Date': 'Wed, 17 May 2023 15:03:50 GMT', 'Content-Length': '55'}) HTTP response body: {"code":"unauthorized","message":"unauthorized access"}
This 'Unauthorized access' error (HTTP 401) indicates that the token, organization ID, or URL provided to the `InfluxDBClient` is incorrect or lacks the necessary permissions to perform the requested operation.
fixVerify that your InfluxDB URL, authentication token, and organization ID are correct and have the appropriate read/write permissions for the target bucket. Ensure environment variables are correctly loaded if you're using `os.environ.get()` to retrieve credentials.
AttributeError: 'InfluxDBClient' object has no attribute 'api_client'
This `AttributeError` typically occurs when the `token` or `org` parameters are `None` during the initialization of `InfluxDBClient`, leading to a partially initialized client object that lacks expected attributes. It can also be caused by trying to use a method that does not exist in the version of the client library being used or when mixing InfluxDB 1.x client code with InfluxDB 2.x client initialization.
fixEnsure that `url`, `token`, and `org` are always provided with valid string values during `InfluxDBClient` initialization. Double-check that all required configuration parameters are correctly supplied and not `None`.
Read timed out. (read timeout=0)
This error occurs when the client's HTTP request to the InfluxDB server exceeds the configured timeout duration, often due to large queries, slow network conditions, or an overly aggressive (low) timeout setting.
fixIncrease the `timeout` parameter during `InfluxDBClient` initialization. The timeout is specified in milliseconds. For example, `InfluxDBClient(url=..., token=..., org=..., timeout=20000)` sets a 20-second timeout.
Audit
Dependencies
pandasoptionalRequired for DataFrame integration (e.g., writing/reading Pandas DataFrames to/from InfluxDB).