Retrieving my electricity usage with the Octopus Energy API using Python 🐙

I’ve recently changed my energy supplier to Octopus……the main reason being their super-cheap overnight electricity rates, which will save me lots of money charging my EV car 💷.

I noticed that they had a developer API, ever the tinkerer I thought I’d take a closer look. Their documentation is really extensive, however their examples all used Curl and I wanted to have a play with Python (using the Requests module). I ran into a couple of issues so thought I’d document this to help others (although most likely my future self when I forgot all of this 😂)

Issue 1 – authenticating to the API using a key

The API uses HTTP basic auth (which uses a key that is available on the API access page), after much searching I found the equivalent for the -u parameter in Curl to enable me to successfully authenticate using the key. The trick was import HTTPBasicAuth using the following command:

from requests.auth import HTTPBasicAuth

Then when making the request to the API using the following syntax, which passes the API key (key variable) and the username, with a blank password (denoted by “”).

request = requests.get(url,auth=HTTPBasicAuth(key,""))

Issue 2 – formatting the date for period_from correctly

The API allows you to pass it a period_from parameter, this is useful to get your energy consumption from a specific date. In my specific use-case, I wanted to see my consumption from the previous 7 days. I achieved this using the following:

date7daysago = (datetime.datetime.now() - datetime.timedelta(days=7)).isoformat()

Pulling all of this together, I created the script below which connects to the developer API and retrieves my electricity consumption for the previous 7 days (grouped by day) and outputs this to the console – if you’d like to use this you’ll need to update the key, MPAN and serial variables – all of which are listed on this page (if you are a customer of course!)

import requests
from requests.auth import HTTPBasicAuth
import datetime
date7daysago = (datetime.datetime.now() - datetime.timedelta(days=7)).isoformat() # calculate the date 7 days ago
key = "KEY"
MPAN = "MPAN"
serial = "SERIAL"
baseurl = "https://api.octopus.energy/v1/"
url = baseurl + "electricity-meter-points/" + MPAN + "/meters/" + serial + "/consumption" + "?period_from=" + date7daysago + "&group_by=" + "day"
request = requests.get(url,auth=HTTPBasicAuth(key,""))
request.json()

Here is the output of the script – you may notice that it doesn’t include 7 days worth of data, that is because I haven’t been a customer for that long.

To make it a little easier to read I added the following to the script, which prints out the date and consumption:

consumption = request.json()
for result in consumption["results"]:
    print(str(result["interval_start"].split("T")[0]) + " : " + str(result["consumption"]))

Based on my previous escapades with developer API’s for consumer services I’m sure that I’ll be writing an Alexa skill for this next 🤖.

Comments

3 responses to “Retrieving my electricity usage with the Octopus Energy API using Python 🐙”

  1. woodygems Avatar

    Brendan, this is a really cool post – particularly for people (like me) who are new to Python and/or struggle with the Octopus API’s.

    Here are some extra tips:

    1. The Octopus API only gives consumption data for that collected via SMETS1/2 meters. If you manually input readings, nada.

    2. Curl in Windows Terminal, gives a “parameter name ‘u’ is ambiguous” for the “-u”. The fix, is “Remove-item alias:curl”.

    3. For those who find the Visual Studio IDE a bit overwhelming, PyCharm Community Edition is free – and I find easier to use. Remember to hit “Python Packages” (bottom left) to import the Requests library.

    Loving your work,
    Woody.

    Like

    1. Brendan Griffin Avatar

      Thanks for the tips Woody!

      I’m currently working on creating a Power Automate Flow/Logic App to replicate what I’m doing with the script, will be easier to schedule and send an e-mail. Also thought about being super geeky and analysing the data in Power BI

      I’ll have to check out PyCharm 👍

      Liked by 1 person

  2. Calculating the daily cost of my electricity with the Octopus Energy API using Python 🐙 – Brendan's Tech Ramblings Avatar

    […] recently shared a script that I’d written that uses the Octopus Energy API to retrieve my electricity usage (in kWh) […]

    Like

Leave a comment