Creating Python API to query and download data from InfluxDB v2

Hi there,

I am trying to query and download the data from InfluxDB v2 from a python based API.
I converting the CuRL command to python requests using the following code:

import requests

headers = {
‘Authorization’: ‘Token pcSpeRibWx0XxxxxxxxxxxxxxxxxxxxxxxxxxxxQTuQ==’,
‘Content-Type’: ‘application/json’,
‘Accept’: ‘/’,
‘Connection’: ‘keep-alive’,

data = {
‘from(bucket:“test2”) | > range(start: -12h) | > filter(fn: (r) = > r._measurement == “example-measurement”) | > aggregateWindow(every: 1 h, fn: mean)’

response ='http:/‘xxxx’, headers=headers, data=data)
However, it gives the following error:
TypeError: a bytes-like object is required, not ‘str’

Any kind of help/feedback on this would be appreciated. Thanks

Don’t reinvent the wheel, there is already a client library for this:

1 Like

Thanks, that is helpful

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. We can convert bytes to string using bytes class decode() instance method, So you need to decode the bytes object to produce a string. In Python 3 , the default encoding is “utf-8” , so you can use directly:

b"python byte to string".decode("utf-8")

Python makes a clear distinction between bytes and strings . Bytes objects contain raw data — a sequence of octets — whereas strings are Unicode sequences . Conversion between these two types is explicit: you encode a string to get bytes, specifying an encoding (which defaults to UTF-8); and you decode bytes to get a string. Clients of these functions should be aware that such conversions may fail, and should consider how failures are handled.