Skip to main content

Async Python client library for the Octopus Energy REST API

Project description

Octopy Energy API

PyPI version Python versions License: MIT Code style: ruff

An async Python client library for the Octopus Energy REST API

Features

  • Async API Client - Full async/await support with httpx
  • Comprehensive Data Models - Fully typed Pydantic models for all API responses
  • Secure - Built-in API key authentication
  • Type-Safe - Complete type hints for better IDE support
  • Automatic Pagination - Seamlessly fetch all pages of data
  • Automatic Retry - Exponential backoff on transient errors for all API requests

Installation

pip install octopy-energy-api

Requirements

  • An Octopus Energy account and API key (if using the Account and Consumption endpoints)

Configuration

Copy the example environment file and add your credentials:

cp .env.example .env

Then edit .env with your Octopus Energy credentials:

OCTOPUS_API_KEY=sk_live_xxxxxxxxxxxxxxxxxxxxx
OCTOPUS_ACCOUNT_NUMBER=A-XXXXXXXX

Or set environment variables directly:

export OCTOPUS_API_KEY=sk_live_xxxxxxxxxxxxxxxxxxxxx
export OCTOPUS_ACCOUNT_NUMBER=A-XXXXXXXX

Environment Variables

Variable Required Default Description
OCTOPUS_API_KEY Yes - Your Octopus Energy API key
OCTOPUS_ACCOUNT_NUMBER Yes - Your account number (A-XXXXXXXX format)
OCTOPUS_API_BASE_URL No https://api.octopus.energy/v1 API base URL

Quick Start

import asyncio
from octopy import Octopy
from octopy.config import get_settings

async def main():
    # Load settings from environment variables or .env file
    settings = get_settings()

    # Use the client as an async context manager
    async with Octopy(settings) as client:
        # Get account information
        account = await client.get_account()
        print(f"Account Number: {account.number}")

        # Get consumption data
        property = account.properties[0]
        meter_point = property.electricity_meter_points[0]
        meter = meter_point.meters[0]

        consumption = await client.get_consumption(
            meter_point=meter_point.mpan,
            serial_number=meter.serial_number,
            fuel="electricity"
        )

        for interval in consumption.results[:5]:
            print(f"{interval.interval_start}: {interval.consumption} kWh")

if __name__ == "__main__":
    asyncio.run(main())

API Coverage

Account Management

  • get_account() - Get account details with properties and meter points
  • get_grid_supply_point(postcode) - Get GSP region from postcode

Consumption Data

  • get_consumption() - Fetch electricity or gas consumption with filtering and grouping

Products & Tariffs

  • get_products() - List available products with filters
  • get_product(product_code) - Get detailed product information

Pricing

  • get_unit_rates() - Get electricity/gas unit rates with date filtering
  • get_standing_charges() - Get daily standing charges for tariffs

All paginated endpoints support automatic pagination with auto_paginate=True (default).

Known Limitations

API Constraints

  • Rate Limiting: The Octopus Energy API may have rate limits. The client includes automatic retry logic for transient errors (408, 429, 500, 502, 503, 504) and network-level failures (timeouts, connection errors) with exponential backoff
  • Page Size: Maximum page size is 25,000 results per request
  • Date Ranges: Historical data availability varies by meter type and installation date

Gas Meter Differences

  • SMETS1 meters: Return consumption in kWh (kilowatt-hours)
  • SMETS2 meters: Return consumption in cubic meters (m³)

Authentication

  • API keys must be in format sk_live_* or sk_test_*
  • Account numbers must be in format A-XXXXXXXX
  • Some endpoints (products, pricing) work without authentication, while account and consumption endpoints require valid credentials

Debugging

Enable debug logging to see detailed API request/response information:

import logging
logging.basicConfig(level=logging.DEBUG)

Performance Tips

Response Caching

Since energy pricing data doesn't change frequently, caching API responses can significantly reduce API calls and improve performance. See examples/cached_pricing.py for a complete implementation using cachetools.

Recommended caching durations:

  • Pricing data (unit rates, standing charges): 1-24 hours
  • Product lists: Several hours
  • Consumption data: Don't cache or use very short TTL (real-time data)
  • Account information: Hours to days

Usage Examples

See the examples/ directory for complete working examples:

Data Models

All API responses are returned as fully typed Pydantic models:

  • Account - Account information with properties
  • Property - Property with address and meter points
  • ElectricityMeterPoint / GasMeterPoint - Meter point details
  • Meter - Physical meter with serial number
  • Agreement - Tariff agreement with validity dates
  • ConsumptionInterval - Energy consumption for a time period
  • Product / ProductDetail - Energy product information
  • UnitRate - Unit rate pricing
  • StandingCharge - Daily standing charge
  • Region - Grid Supply Point (GSP) region enum

Development

Setup

Clone the repository and install dependencies:

git clone https://github.com/imspury/octopy-energy-api.git
cd octopy-energy-api
pip install -e ".[dev]"

Testing

This project uses pytest for testing with comprehensive test coverage.

Run Tests

# Run all tests
pytest

# Run with coverage report
pytest --cov=src/octopy --cov-report=term-missing

# Run with verbose output
pytest -v

# Run specific test file
pytest tests/test_client.py

# Run specific test
pytest tests/test_client.py::test_get_account

Test Structure

The test suite includes:

  • Unit tests for all client methods and API endpoints
  • HTTP mocking with respx for isolated testing (no real API calls)
  • Async test support with pytest-asyncio
  • Comprehensive coverage of:
  • Account management endpoints
  • Consumption data with pagination and filtering
  • Product and pricing endpoints
  • Exception handling and error cases
  • Configuration management
  • Data model validation

Code Quality

# Run linting
ruff check src/ tests/ examples/

# Auto-fix linting issues
ruff check --fix src/ tests/ examples/

# Format code
ruff format src/ tests/ examples/

# Type checking
mypy src/octopy tests

License

This project is licensed under the MIT License - see LICENSE for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

octopy_energy_api-0.3.0.tar.gz (30.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

octopy_energy_api-0.3.0-py3-none-any.whl (15.2 kB view details)

Uploaded Python 3

File details

Details for the file octopy_energy_api-0.3.0.tar.gz.

File metadata

  • Download URL: octopy_energy_api-0.3.0.tar.gz
  • Upload date:
  • Size: 30.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.13.2

File hashes

Hashes for octopy_energy_api-0.3.0.tar.gz
Algorithm Hash digest
SHA256 c8b726a8050e83e863293bde76383da98cbfb3edbf6f1e0e77811e6ccd62501a
MD5 b6069db0075c885aa1e274c5c953c437
BLAKE2b-256 6f193e02166bbe0438d7be4eefbcc4dcb6a827cfae6e550db0502a5d45bda747

See more details on using hashes here.

File details

Details for the file octopy_energy_api-0.3.0-py3-none-any.whl.

File metadata

File hashes

Hashes for octopy_energy_api-0.3.0-py3-none-any.whl
Algorithm Hash digest
SHA256 93110f2afe04a0a2525a04dfe5cb258789e57c1ddcad285072aba5dc801b888e
MD5 ef7db1062a699a1a2fee21658ab56edc
BLAKE2b-256 e80b0e004f0b02afdb11d9e1be83d238eb1cce9440f34daef4993acd2ddf8e24

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page