Async Python client for National Grid built on aiohttp
Project description
py-nationalgrid
Async Python client for National Grid's GraphQL and REST APIs.
Installation
pip install py-nationalgrid
Quick Start
import asyncio
from py_nationalgrid import NationalGridClient, NationalGridConfig
async def main() -> None:
config = NationalGridConfig(
username="user@example.com",
password="your-password",
)
async with NationalGridClient(config=config) as client:
accounts = await client.get_linked_accounts()
for account in accounts:
print(account["billingAccountId"])
if __name__ == "__main__":
asyncio.run(main())
API Methods
| Method | Returns | Description |
|---|---|---|
get_linked_accounts() |
list[AccountLink] |
Get linked billing account IDs |
get_billing_account() |
BillingAccount |
Get account details (region, meters, address) |
get_energy_usage_costs() |
list[EnergyUsageCost] |
Get energy costs for a billing period |
get_energy_usages() |
list[EnergyUsage] |
Get historical usage data |
get_ami_energy_usages() |
list[AmiEnergyUsage] |
Primary AMI method. Tries the daily NrtDailyUsage endpoint first (no chunking required). Falls back to get_ami_energy_usages_15min() automatically on GraphQL errors or 504. See below. |
get_ami_energy_usages_15min() |
list[AmiEnergyUsage] |
AMI 15-minute interval data. Call directly only when you specifically need 15-minute granularity. Auto-chunks large ranges, falls back to daily on API errors, and handles the ~45-day hot storage limit gracefully. |
get_interval_reads() |
list[IntervalRead] |
Real-time meter interval reads. Returns [] for meters with no interval data (e.g. GAS). |
All methods return typed results using TypedDict models.
AMI Energy Usage
Primary method: get_ami_energy_usages()
This is the recommended entry point for AMI data. It sends a single full-range request to the NrtDailyUsage (daily) endpoint — no chunking required. If that request returns GraphQL errors or a 504 Gateway Timeout, it automatically falls back to get_ami_energy_usages_15min() (with chunking) and returns whatever that produces.
from datetime import date, timedelta
date_to = date.today()
date_from = date_to - timedelta(days=60)
usages = await client.get_ami_energy_usages(
meter_number=meter["meterNumber"],
premise_number=billing_account["premiseNumber"],
service_point_number=meter["servicePointNumber"],
meter_point_number=meter["meterPointNumber"],
date_from=date_from,
date_to=date_to,
fuel_type=meter.get("fuelType"), # forwarded to the fallback path if triggered
)
Explicit 15-minute method: get_ami_energy_usages_15min()
Use this directly only when you specifically need 15-minute interval granularity. It handles several API constraints automatically.
Chunking
The National Grid API imposes a hard limit of approximately 10,000 records per response, and the Azure Application Gateway enforces a backend timeout that cuts off requests spanning more than roughly 45 days of data regardless of record count.
To work around this, the method automatically splits any date range that exceeds 45 days into 45-day chunks and concatenates the results. Both ELECTRIC and GAS meters use 45-day chunks:
- ELECTRIC: 96 records/day × 45 days = 4,320 records per chunk (well inside the 10k cap)
- GAS: 24 records/day × 45 days = 1,080 records per chunk
Chunks are requested newest-first to ensure the most recent data is always fetched successfully before older chunks are attempted. Each chunk is logged at DEBUG level — enable debug logging to trace progress for large date ranges.
Hot Storage Window (~45 days)
National Grid's API only serves data from "hot" (immediately accessible) storage for approximately the last 45 days from today. Data older than that sits in cold/archive storage. Any query that touches cold storage — even a single-day range — will trigger a 504 Gateway Timeout from the Azure Application Gateway.
This is a server-side constraint. There is no client-side configuration that can change it.
Because chunks are fetched newest-first, a 504 on an older chunk does not discard the recent data already collected. The method logs a warning and returns whatever records were successfully retrieved:
WARNING amiEnergyUsages15Min: 504 on chunk 2/4 (2025-01-01 to 2025-02-14) —
data is likely beyond the ~45-day accessible window. Returning 135 record(s)
collected so far.
Callers should not assume the returned list covers the full requested date range. If you request 180 days, you will receive roughly the last 45 days of records without an exception being raised.
Fallback to Daily Endpoint
Some meters do not support the 15-minute (amiEnergyUsages15Min) GraphQL operation and return a GraphQL error response instead of data. When this happens on the first chunk, the method transparently falls back to a single full-range request against the standard daily endpoint (amiEnergyUsages). The fallback is automatic and invisible to the caller.
Example
from datetime import date, timedelta
date_to = date.today()
date_from = date_to - timedelta(days=60) # spans more than 45 days → auto-chunked
usages = await client.get_ami_energy_usages_15min(
meter_number=meter["meterNumber"],
premise_number=billing_account["premiseNumber"],
service_point_number=meter["servicePointNumber"],
meter_point_number=meter["meterPointNumber"],
date_from=date_from,
date_to=date_to,
fuel_type=meter.get("fuelType"), # "ELECTRIC" or "GAS"; controls chunk size
)
# usages covers only the accessible ~45-day window even though 60 days were requested
Examples
uv run python examples/list-accounts.py --username user@example.com --password secret
uv run python examples/account-info.py --username user@example.com --password secret
uv run python examples/energy-usage.py --username user@example.com --password secret
uv run python examples/interval-reads.py --username user@example.com --password secret
uv run python examples/ami-usage.py --username user@example.com --password secret
uv run python examples/ami-usage.py --username user@example.com --password secret --fuel-type ELECTRIC
uv run python examples/ami-usage.py --username user@example.com --password secret --fuel-type GAS --days 30
uv run python examples/ami-usage.py --username user@example.com --password secret --15min
Development
Requires Python 3.10+ and uv.
uv sync # install dependencies
uv run pytest # run tests
uv run ruff check . # lint
uv run ruff format . # format
uv run mypy src # type-check
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
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file py_nationalgrid-0.5.1.tar.gz.
File metadata
- Download URL: py_nationalgrid-0.5.1.tar.gz
- Upload date:
- Size: 58.4 kB
- Tags: Source
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
b7dc8182d09cff359ae44b4204a783d41cf59c4e05ece0326733ce626d6900ce
|
|
| MD5 |
6eaa1eef12390cf6438e2f99cd52b3b0
|
|
| BLAKE2b-256 |
b798b19ac27a1b82279db1287c286ef13b76d8399629984a31d984a7892d442b
|
Provenance
The following attestation bundles were made for py_nationalgrid-0.5.1.tar.gz:
Publisher:
release.yml on virtitnerd/py-nationalgrid
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
py_nationalgrid-0.5.1.tar.gz -
Subject digest:
b7dc8182d09cff359ae44b4204a783d41cf59c4e05ece0326733ce626d6900ce - Sigstore transparency entry: 1392467328
- Sigstore integration time:
-
Permalink:
virtitnerd/py-nationalgrid@595baec5127c64a21ff01a88cb44b9d49b0f5bd9 -
Branch / Tag:
refs/tags/v0.5.1 - Owner: https://github.com/virtitnerd
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@595baec5127c64a21ff01a88cb44b9d49b0f5bd9 -
Trigger Event:
release
-
Statement type:
File details
Details for the file py_nationalgrid-0.5.1-py3-none-any.whl.
File metadata
- Download URL: py_nationalgrid-0.5.1-py3-none-any.whl
- Upload date:
- Size: 35.2 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? Yes
- Uploaded via: twine/6.1.0 CPython/3.13.12
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
405022069b1f96bc1b85a0b430fc536cd07ba15b71f23b42f0920beb4eded551
|
|
| MD5 |
29e77a0a8fdf2a23c33c301775c00521
|
|
| BLAKE2b-256 |
8befb00dfd25563b255cc1ab94bd7a97161fc2b6e670faa6dee04ac04de21066
|
Provenance
The following attestation bundles were made for py_nationalgrid-0.5.1-py3-none-any.whl:
Publisher:
release.yml on virtitnerd/py-nationalgrid
-
Statement:
-
Statement type:
https://in-toto.io/Statement/v1 -
Predicate type:
https://docs.pypi.org/attestations/publish/v1 -
Subject name:
py_nationalgrid-0.5.1-py3-none-any.whl -
Subject digest:
405022069b1f96bc1b85a0b430fc536cd07ba15b71f23b42f0920beb4eded551 - Sigstore transparency entry: 1392467341
- Sigstore integration time:
-
Permalink:
virtitnerd/py-nationalgrid@595baec5127c64a21ff01a88cb44b9d49b0f5bd9 -
Branch / Tag:
refs/tags/v0.5.1 - Owner: https://github.com/virtitnerd
-
Access:
public
-
Token Issuer:
https://token.actions.githubusercontent.com -
Runner Environment:
github-hosted -
Publication workflow:
release.yml@595baec5127c64a21ff01a88cb44b9d49b0f5bd9 -
Trigger Event:
release
-
Statement type: