Skip to main content

Official Python SDK for source-timestamped OilPriceAPI energy data

Project description

OilPriceAPI Python SDK

Official Python client for source-timestamped OilPriceAPI energy data. It provides typed synchronous and asynchronous clients, bounded retries, explicit errors, optional pandas helpers, and executable example manifests.

PyPI version Python Tests License: MIT

Mutable offer, catalog, freshness, entitlement, and data-rights wording is governed by the reviewed product-facts.json contract. Latest available values include source timestamps; cadence, history depth, and access vary by source, market hours, dataset, and account entitlement.

Install

python -m pip install oilpriceapi

Optional extras are installed only when the application uses them:

python -m pip install "oilpriceapi[pandas]"
python -m pip install "oilpriceapi[stream]"

An installed helper does not imply that every dataset or workflow is enabled for an account. Confirm access in the current API response and documentation.

Authenticate

Create an API key in the OilPriceAPI dashboard and provide it through the environment. Do not put a key in source code, a notebook cell, a URL, logs, screenshots, or issue text.

export OILPRICEAPI_KEY="your-key-from-the-dashboard"

The API authentication header is Authorization: Token YOUR_API_KEY.

First Request With Source Context

The canonical first request is GET /v1/prices/latest?by_code=BRENT_CRUDE_USD. This example fails closed if the response omits the context needed to interpret the value:

import math
import os

from oilpriceapi import OilPriceAPI

with OilPriceAPI(api_key=os.environ["OILPRICEAPI_KEY"], max_retries=1) as client:
    payload = client.request(
        "GET",
        "/v1/prices/latest",
        params={"by_code": "BRENT_CRUDE_USD"},
        timeout=30,
    )

record = payload.get("data")
if not isinstance(record, dict):
    raise RuntimeError("EMPTY_RESPONSE: no price record returned")

price = record.get("price")
if isinstance(price, bool) or not isinstance(price, (int, float)) or not math.isfinite(price):
    raise RuntimeError("MALFORMED_RESPONSE: price is not a finite number")

source = record.get("source")
metadata = record.get("metadata")
if not source and isinstance(metadata, dict):
    source = metadata.get("source")

timestamp_field = next(
    (
        field
        for field in ("as_of", "source_timestamp", "created_at", "updated_at")
        if isinstance(record.get(field), str) and record[field].strip()
    ),
    None,
)

required_text = {
    "code": record.get("code"),
    "currency": record.get("currency"),
    "unit": record.get("unit"),
    "source": source,
}
if timestamp_field is None or any(
    not isinstance(value, str) or not value.strip()
    for value in required_text.values()
):
    raise RuntimeError("MALFORMED_RESPONSE: source context is incomplete")

print(
    {
        **required_text,
        "price": float(price),
        "api_timestamp_field": timestamp_field,
        "api_timestamp": record[timestamp_field],
        "freshness": record.get("data_status") or record.get("freshness"),
    }
)

The reviewed standalone form is examples/snippets/latest_price.py. CI executes it against production-shaped fixtures and publishes its code and checksum in the release snippet manifest.

Typed Client

For applications that only need the normalized core fields:

import os

from oilpriceapi import OilPriceAPI

with OilPriceAPI(api_key=os.environ["OILPRICEAPI_KEY"]) as client:
    price = client.prices.get("BRENT_CRUDE_USD")

print(
    price.commodity,
    price.value,
    price.currency,
    price.unit,
    price.timestamp.isoformat(),
)

Use the raw first-request pattern when downstream logic requires the exact source and timestamp-field semantics from the API response.

Recovery

The package exposes typed errors for the customer-recoverable boundaries:

from oilpriceapi import (
    AuthenticationError,
    OilPriceAPIError,
    RateLimitError,
    TimeoutError,
)

try:
    price = client.prices.get("BRENT_CRUDE_USD")
except AuthenticationError:
    print("Replace the missing, expired, or revoked API key.")
except RateLimitError as error:
    print("Wait for the API-provided reset window.", error.seconds_until_reset)
except TimeoutError:
    print("Retry once, then check https://status.oilpriceapi.com.")
except OilPriceAPIError as error:
    if error.status_code in (402, 403):
        print("Review dataset access for this account.")
    else:
        raise

Executable recovery examples cover 401, 403, 429, and timeout responses under examples/snippets/. Empty or malformed successful responses should stop analysis rather than inventing a price, unit, currency, source, or timestamp.

Capabilities

The client includes resources for latest and historical values plus additional dataset and workflow families. Availability is determined by the live API and account entitlement, not by the presence of a helper method in the package.

Standard plans provide API access, normalization, monitoring, and delivery; they do not transfer ownership of underlying source data or unrestricted raw data redistribution rights.

Reproducible Examples

Website and documentation snippets are maintained in examples/snippets/. Every release attaches a versioned manifest containing the package version, minimum runtime, source commit, expected response shape, exact code, and SHA-256 for each example.

python scripts/generate_snippet_manifest.py \
  --source-commit "$(git rev-parse HEAD)" \
  --output artifacts/snippets/oilpriceapi-python-snippets-v1.json

Development

The performance guide documents timeout, connection-pooling, batching, retry, and troubleshooting behavior without making a universal latency promise.

python -m pip install -e '.[dev]'
python scripts/validate_storefront_claims.py
pytest tests/ --ignore=tests/integration --ignore=tests/contract -m 'not slow'
python -m build

Live tests require an explicitly supplied non-customer test credential. Unit and snippet tests use local fixtures and do not print or persist credentials.

Support

Licensed under the MIT License.

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

oilpriceapi-1.11.0.tar.gz (94.9 kB view details)

Uploaded Source

Built Distribution

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

oilpriceapi-1.11.0-py3-none-any.whl (102.6 kB view details)

Uploaded Python 3

File details

Details for the file oilpriceapi-1.11.0.tar.gz.

File metadata

  • Download URL: oilpriceapi-1.11.0.tar.gz
  • Upload date:
  • Size: 94.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for oilpriceapi-1.11.0.tar.gz
Algorithm Hash digest
SHA256 c1406ea3719227d3fdffd7438b770686c1c0fe9a08a4fb2126082aa23a82c86b
MD5 148e4e36ee67049649984ef0ca14b974
BLAKE2b-256 047adf0b988a25e24e468256a10c1492e8aba904b4b90aa5e07d0f89c3465ada

See more details on using hashes here.

Provenance

The following attestation bundles were made for oilpriceapi-1.11.0.tar.gz:

Publisher: publish.yml on OilpriceAPI/python-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file oilpriceapi-1.11.0-py3-none-any.whl.

File metadata

  • Download URL: oilpriceapi-1.11.0-py3-none-any.whl
  • Upload date:
  • Size: 102.6 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.14

File hashes

Hashes for oilpriceapi-1.11.0-py3-none-any.whl
Algorithm Hash digest
SHA256 21fa75c9e071e7dd3bf26072102bd0130d9546657633e7670f22c0ce50db019a
MD5 bd1521a4b1966d89a4ca5190e68102be
BLAKE2b-256 c567dd6d53257fa8ded103a82d89b8d1f1e73f4a9ae2178f6f587462820bbb98

See more details on using hashes here.

Provenance

The following attestation bundles were made for oilpriceapi-1.11.0-py3-none-any.whl:

Publisher: publish.yml on OilpriceAPI/python-sdk

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

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