First of all / I’m a novice on this field so please apologize me If my question is for you too simple…
I’m trying to get history of states for temperature (and boiler gas consumption if I find out how to get any data through this way).
If using /api/states - it works, but when trying /api/history/period/ I receive 404 error.
I probably construct the url in a wrong way / but without idea what is wrong.
Thank you in advance for any help.
import requests
from datetime import datetime, timedelta
from urllib.parse import urlencode
url = "http://homeassistant:8123/api/history/period/"
#I have tried also ipadress:8123/....
headers = {
"Authorization": "Bearer MYTOKEN",
"content-type": "application/json",
}
# Define parameters for the query - as entity_id I use the same as is stored in sql db.
entity_id = "sensor.boiler_energy_heating"
start_time = datetime.now() - timedelta(days=7)
end_time = datetime.now()
start_time_str = start_time.strftime("%Y-%m-%dT%H:%M:%S%Z")
end_time_str = end_time.strftime("%Y-%m-%dT%H:%M:%S%Z")
# Define payload for the query
query_params = {
"filter_entity_id": entity_id,
"end_time": end_time_str
}
# Encode query parameters
query_string = urlencode(query_params)
# Construct final URL
final_url = f"{url}?{query_string}"
# Send GET request to fetch historical data
response = requests.get(final_url, headers=headers)
# Check if request was successful
if response.status_code == 200:
# Parse JSON response
history_data = response.json()
print(history_data)
else:
print("Failed to fetch data. Status code:", response.status_code)