The following is a simplified example using Python’s requests library to fetch historical sensor data from ChirpStack’s API. Where can I obtain the ChirpStack API endpoint and Authentication token?
import requests
ChirpStack API endpoint for fetching historical sensor data
if response.status_code == 200:
# Parse the JSON response
historical_data = response.json()
# Process the data as needed
print(historical_data)
else:
print(‘Failed to fetch historical data:’, response.text)
The API endpoint is the same URL as your Chirpstack web interface, including port. The API token can be gotten through the web interface under: Network Server → API keys.
I’m not familiar with the python requests library, but why wouldn’t you use the requests and format outlined in the API protocol. Here’s my code for creating a channel and retrieving metrics (although I’ve found retrieving metrics from the API not very helpful unless you increase the duration metrics are kept before Chirpstack deletes them):
def createChannel(server):
try:
# Connect with TLS
channel = grpc.secure_channel(server, grpc.ssl_channel_credentials())
# Device-queue API client.
client = api.DeviceServiceStub(channel)
except grpc.RpcError as e:
print('error:',type(e))
print("Connected to " + server)
return channel, client
def getMetrics(client,token,dev_eui,start,end):
print("Retrieving metrics from device with EUI: " + dev_eui)
# Define the API key meta-data.
auth_token = [("authorization", "Bearer %s" % token)]
try:
# Construct request.
req = api.GetDeviceMetricsRequest()
req.dev_eui = dev_eui
req.start.FromDatetime(start)
req.end.FromDatetime(end)
resp = client.GetMetrics(req, metadata=auth_token)
print(resp.metrics)
return resp
EDIT:
Two things to note in these functions:
I have a Traefik reverse-proxy in front of my Chirpstack web UI / API to control TLS, therefore I use grpc.secure_channel to connect to my API, if you have not set up TLS you should use grpc.insecure_channel as outlined in the API example.
In this example I create the channel with a DeviceServiceStub, this will only work on API calls about devices. Depending on what section of the API protocol documentation the API call falls under, you must use the appropriate service stub.
I’ve only ever worked in Chirpstack V4 so I’m unfamiliar with the V3 UI, but I am assuming any of those API keys would work. Although it’s important to know that the ID’s of the keys there are not the keys themselves, the keys can only be seen once when creating them and must be saved and stored somewhere else, although you could probably retrieve them through the postgres database.
You need to click the [+ create] button to create a new key. What you see in the table are only the IDs and names of already created keys. The actual key can only be obtained once.