Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions sdk/python/openmeter/.flake8
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
[flake8]
max-line-length = 100
extend-exclude = .venv,build,dist

7 changes: 7 additions & 0 deletions sdk/python/openmeter/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
/.venv/
/.ruff_cache/
/build/
/dist/
*.egg-info/
__pycache__/
*.py[cod]
2 changes: 2 additions & 0 deletions sdk/python/openmeter/MANIFEST.in
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
recursive-include examples *.py

154 changes: 154 additions & 0 deletions sdk/python/openmeter/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
# OpenMeter Python SDK (v3 baseline)

An idiomatic, hand-written Python SDK for the OpenMeter v3 API. This baseline
covers the same endpoint groups as the Go SDK baseline in PR #4644: meters and
plan add-ons. It is intentionally not a complete OpenMeter client.

## Requirements

- Python 3.9 or newer
- Pydantic v2
- httpx (async client only, installed through the `async` extra)

The sync `Client` uses only the Python standard library (`urllib`) for HTTP.
The async `AsyncClient` uses `httpx.AsyncClient` for true async I/O — no
thread pool involved. Pydantic is the only required runtime dependency.

## Install

```bash
python -m pip install ./sdk/python/openmeter
```

Install the async client dependencies with:

```bash
python -m pip install "./sdk/python/openmeter[async]"
```

## Client setup

The base URL must include the deployment's v3 prefix:

| Deployment | Base URL |
| --- | --- |
| Local | `http://127.0.0.1:8888/api/v3` |
| OpenMeter Cloud | `https://openmeter.cloud/api/v3` |
| Kong Konnect | `https://<region>.api.konghq.com/v3` |

```python
from openmeter import Client

with Client(
"https://openmeter.cloud/api/v3",
token="om_...",
) as client:
page = client.meters.list()
print(page.data)
```

The async client has the same resource groups and method names:

```python
import asyncio

from openmeter import AsyncClient


async def main() -> None:
async with AsyncClient(
"https://openmeter.cloud/api/v3",
token="om_...",
) as client:
async for meter in client.meters.list_all():
print(meter.key)


asyncio.run(main())
```

Complete runnable snippets live in [`examples/`](examples/). Public classes and
methods include docstrings, so `help(openmeter.Client)` and editor tooltips also
serve as API documentation.

## Pydantic models

Request models validate v3 constraints before sending a request:

```python
from openmeter import CreateMeterRequest

request = CreateMeterRequest(
name="Tokens Total",
key="tokens_total",
aggregation="sum",
event_type="prompt",
value_property="$.tokens",
)
```

Unknown response fields are ignored to preserve additive API compatibility.
Response enum-like fields remain plain strings, allowing a newer server value to
round-trip through an older SDK. Request enum values are validated against the
current v3 contract.

## Implemented endpoints

| Resource method | HTTP endpoint |
| --- | --- |
| `meters.create` / `meters.list` / `meters.list_all` | `POST`, `GET /openmeter/meters` |
| `meters.get` / `meters.update` / `meters.delete` | `GET`, `PUT`, `DELETE /openmeter/meters/{meterId}` |
| `meters.query` / `meters.query_csv` / `meters.query_csv_stream` | `POST /openmeter/meters/{meterId}/query` |
| `plan_addons.create` / `plan_addons.list` / `plan_addons.list_all` | `POST`, `GET /openmeter/plans/{planId}/addons` |
| `plan_addons.get` / `plan_addons.update` / `plan_addons.delete` | `GET`, `PUT`, `DELETE /openmeter/plans/{planId}/addons/{planAddonId}` |

`list_all` is a lazy iterator on the sync client and an async iterator on the
async client. Buffered JSON and CSV bodies are capped at 10 MiB. Use
`query_csv_stream` for large CSV exports and close it with `with` or `async with`.
Plan-add-on operations and meter update/query operations are marked unstable in
the current v3 specification and can evolve before they become stable.

## Errors and transport

Non-2xx responses raise `APIError`, exposing `status_code`, `title`, `detail`,
`type`, `instance`, parsed invalid parameters, and the capped raw response body.
Transport failures raise `TransportError`; client-side model failures use
Pydantic's `ValidationError`.

The sync client accepts an optional `urllib.request.OpenerDirector` to customize
proxy, TLS, and authentication behavior without adding an HTTP dependency. The
async client accepts an optional preconfigured `httpx.AsyncClient` for the same
purpose. It follows standard proxy environment variables by default; pass
`trust_env=False` to ignore them. Pass `timeout=None` only when the caller
supplies another transport-level bound.

GET, PUT, DELETE, and read-only meter query requests are retried up to twice
with exponential backoff on connection failures or a 502/503/504 response.
Resource-creating POST requests are never retried, since a retry could duplicate
the resource or its notification/webhook side effects.

## Development

The package uses [uv](https://docs.astral.sh/uv/) for the contributor environment
and lockfile. From `sdk/python/openmeter`, install the development dependencies
with the supported Python floor:

```bash
uv sync --python 3.9
```

Run linting, formatting, type checking, tests, and the package build through the
locked environment:

```bash
uv run flake8 src tests examples
uv run ruff check .
uv run ruff format --check .
uv run pyright
uv run python -m unittest discover -s tests -v
uv build
```

Tests use `unittest` and a local standard-library HTTP server. Package consumers
do not need uv and can continue installing the SDK with pip or another Python
package manager.
21 changes: 21 additions & 0 deletions sdk/python/openmeter/examples/async.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""List meters with the asynchronous v3 client."""

import asyncio
import os

from openmeter import AsyncClient


async def main() -> None:
"""Run the asynchronous example using environment-based configuration."""

base_url = os.getenv("OPENMETER_BASE_URL", "http://127.0.0.1:8888/api/v3")
token = os.getenv("OPENMETER_TOKEN")

async with AsyncClient(base_url, token=token) as client:
async for meter in client.meters.list_all():
print(meter.key, meter.aggregation)


if __name__ == "__main__":
asyncio.run(main())
25 changes: 25 additions & 0 deletions sdk/python/openmeter/examples/sync.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
"""List and query meters with the synchronous v3 client."""

import os

from openmeter import Client, MeterQueryRequest


def main() -> None:
"""Run the synchronous example using environment-based configuration."""

base_url = os.getenv("OPENMETER_BASE_URL", "http://127.0.0.1:8888/api/v3")
token = os.getenv("OPENMETER_TOKEN")

with Client(base_url, token=token) as client:
for meter in client.meters.list_all():
print(meter.key, meter.aggregation)

meter_id = os.getenv("OPENMETER_METER_ID")
if meter_id:
result = client.meters.query(meter_id, MeterQueryRequest())
print(result.data)


if __name__ == "__main__":
main()
66 changes: 66 additions & 0 deletions sdk/python/openmeter/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
[build-system]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"

[project]
name = "openmeter"
version = "0.1.0"
description = "Idiomatic Python SDK for the OpenMeter v3 API"
readme = "README.md"
requires-python = ">=3.9"
license = "Apache-2.0"
authors = [
{ name = "OpenMeter", email = "info@openmeter.io" },
]
keywords = ["billing", "metering", "openmeter", "sdk", "usage"]
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Programming Language :: Python :: 3.14",
"Typing :: Typed",
]
dependencies = [
"pydantic>=2.10,<3",
]

[project.optional-dependencies]
async = [
"httpx>=0.28.1,<1",
]

[dependency-groups]
dev = [
"build>=1.2,<2",
"flake8>=7,<8",
"httpx>=0.28.1,<1",
"pyright>=1.1.400,<2",
"ruff>=0.14,<1",
]

[project.urls]
Documentation = "https://openmeter.io/docs"
Issues = "https://github.com/openmeterio/openmeter/issues"
Repository = "https://github.com/openmeterio/openmeter"

[tool.setuptools.packages.find]
where = ["src"]

Comment on lines +51 to +53

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | ⚡ Quick win

Ensure the py.typed marker gets bundled in the wheel.

Hey! I see we're building a typed SDK (love the Typing :: Typed classifier!), but we need to make sure the py.typed marker file actually makes it into the installed wheel. setuptools won't grab non-Python files automatically unless we explicitly specify them in package-data.

Let's add that so downstream type checkers know the package is fully typed!

📦 Proposed fix to include the marker file
 [tool.setuptools.packages.find]
 where = ["src"]
+
+[tool.setuptools.package-data]
+openmeter = ["py.typed"]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.packages.find]
where = ["src"]
[tool.setuptools.package-data]
openmeter = ["py.typed"]
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@sdk/python/openmeter/pyproject.toml` around lines 46 - 48, Update the
setuptools configuration near [tool.setuptools.packages.find] to explicitly
include the py.typed marker in the openmeter package data, ensuring it is
bundled into the wheel for downstream type checkers.

[tool.ruff]
target-version = "py39"
line-length = 100

[tool.ruff.lint]
select = ["E", "F", "I", "UP"]
# Optional/Union spellings keep annotations unambiguous for the Python 3.9 floor.
ignore = ["UP006", "UP007", "UP035", "UP045"]

[tool.pyright]
include = ["src", "examples"]
pythonVersion = "3.9"
typeCheckingMode = "standard"
112 changes: 112 additions & 0 deletions sdk/python/openmeter/src/openmeter/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
"""OpenMeter Python SDK for the v3 API baseline."""

from typing import TYPE_CHECKING, Any

from ._version import __version__
from .client import Client, Meters, PlanAddons
from .errors import (
APIError,
InvalidIDError,
OpenMeterError,
PaginationError,
ResponseTooLargeError,
TransportError,
)
from .models import (
AddonReference,
CreateMeterRequest,
CreatePlanAddonRequest,
InvalidParameter,
Meter,
MeterAggregation,
MeterFilter,
MeterListParams,
MeterPage,
MeterQueryFilters,
MeterQueryGranularity,
MeterQueryRequest,
MeterQueryResult,
MeterQueryRow,
PageMeta,
PageParams,
PaginatedMeta,
PlanAddon,
PlanAddonListParams,
PlanAddonPage,
ProblemDetails,
ProductCatalogValidationError,
QueryFilterString,
QueryFilterStringMapItem,
StringFilter,
UpdateMeterRequest,
UpsertPlanAddonRequest,
)

if TYPE_CHECKING:
from .aio import AsyncByteStream, AsyncClient

_ASYNC_EXPORTS = frozenset({"AsyncByteStream", "AsyncClient"})


def __getattr__(name: str) -> Any:
if name not in _ASYNC_EXPORTS:
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

try:
from .aio import AsyncByteStream, AsyncClient
except ModuleNotFoundError as error:
if error.name != "httpx":
raise
raise ImportError(
"async support requires the 'async' extra: pip install 'openmeter[async]'"
) from error

exports = {
"AsyncByteStream": AsyncByteStream,
"AsyncClient": AsyncClient,
}
globals().update(exports)
return exports[name]


__all__ = [
"APIError",
"AddonReference",
"AsyncByteStream",
"AsyncClient",
"Client",
"CreateMeterRequest",
"CreatePlanAddonRequest",
"InvalidIDError",
"InvalidParameter",
"Meter",
"MeterAggregation",
"MeterFilter",
"MeterListParams",
"MeterPage",
"MeterQueryFilters",
"MeterQueryGranularity",
"MeterQueryRequest",
"MeterQueryResult",
"MeterQueryRow",
"Meters",
"OpenMeterError",
"PageMeta",
"PageParams",
"PaginatedMeta",
"PaginationError",
"PlanAddon",
"PlanAddonListParams",
"PlanAddonPage",
"PlanAddons",
"ProblemDetails",
"ProductCatalogValidationError",
"QueryFilterString",
"QueryFilterStringMapItem",
"ResponseTooLargeError",
"StringFilter",
"TransportError",
"UpdateMeterRequest",
"UpsertPlanAddonRequest",
"__version__",
]
Loading
Loading