Skip to content

Client

oilpriceapi.client.OilPriceAPI

Main synchronous client for OilPriceAPI.

Thread Safety: The underlying httpx.Client is thread-safe and can be used from multiple threads. However, you should not modify client attributes (like headers) after initialization when using from multiple threads.

Resource Management: Always use context managers (with statement) or explicitly call close() to ensure proper cleanup of network resources. Do not rely on del for cleanup as it is non-deterministic.

Parameters:

Name Type Description Default
api_key Optional[str]

API key for authentication. If not provided, uses OILPRICEAPI_KEY env var.

None
base_url Optional[str]

Base URL for API. Defaults to production.

None
timeout Optional[float]

Request timeout in seconds. Defaults to 30.

None
max_retries Optional[int]

Total request ATTEMPTS, not retries after the first. Defaults to 3. Must be at least 1; pass 1 for a single attempt with no retries. Anything less, or a non-int, raises ConfigurationError rather than being silently replaced by the default.

None
retry_on Optional[List[int]]

Status codes to retry on. Defaults to [429, 500, 502, 503, 504]. An explicit empty list is honoured and disables status-code retries.

None

Retry safety: a non-idempotent method (POST, PATCH) is sent exactly ONCE. A timeout, a transport error or a 5xx is an ambiguous outcome — the server may have committed the write before the response was lost — so replaying it could create a duplicate. Idempotent methods (GET, HEAD, OPTIONS, TRACE, PUT, DELETE) still retry as before, and a 429 still retries any method because it is an outright refusal. Pass idempotent=True to request() to opt a specific write back into retrying.

Example

with OilPriceAPI() as client: ... price = client.prices.get("BRENT_CRUDE_USD") ... print(f"Brent: ${price.value:.2f}")

Or explicitly manage lifecycle

client = OilPriceAPI() try: ... price = client.prices.get("BRENT_CRUDE_USD") ... finally: ... client.close()

request(method, path, params=None, json_data=None, timeout=None, idempotent=None, **kwargs)

Make HTTP request to API.

Warning: This method uses blocking time.sleep() for retries. For async/await applications, use AsyncOilPriceAPI instead.

Parameters:

Name Type Description Default
method str

HTTP method (GET, POST, etc.)

required
path str

API endpoint path

required
params Optional[Dict[str, Any]]

Query parameters

None
json_data Optional[Dict[str, Any]]

JSON body data

None
timeout Optional[float]

Request timeout in seconds. If None, uses client's default timeout.

None
idempotent Optional[bool]

Assert that repeating this request is safe. Without it, POST and PATCH are sent exactly once and never replayed after an ambiguous outcome (#104).

None
**kwargs

Additional httpx request arguments

{}

Returns:

Type Description
Dict[str, Any]

Parsed JSON response dict

Raises:

Type Description
OilPriceAPIError

On API errors

AuthenticationError

On 401 status

RateLimitError

On 429 status

DataNotFoundError

On 404 status

ServerError

On 5xx status

TimeoutError

On request timeout

request_with_headers(method, path, params=None, json_data=None, timeout=None, idempotent=None, **kwargs)

Make HTTP request and return (json_body, headers) tuple.

Identical to request() but also returns response headers so callers can inspect pagination headers like X-Has-Next, X-Page, X-Per-Page.

Returns:

Type Description
Tuple[Dict[str, Any], Headers]

Tuple of (parsed JSON dict, httpx.Headers)

get_data_connector_prices(fuel_type=None, port=None, region=None, since=None)

Get prices from connected data sources (BYOS - Bring Your Own Subscription).

Requires Data Connector feature enabled on your organization.

Parameters:

Name Type Description Default
fuel_type Optional[str]

Filter by fuel type (VLSFO, MGO, IFO380)

None
port Optional[str]

Filter by port name

None
region Optional[str]

Filter by region (AMERICAS, EMEA, APAC)

None
since Optional[str]

ISO 8601 timestamp to fetch prices after

None

Returns:

Type Description
List[DataConnectorPrice]

List of DataConnectorPrice objects

Example

prices = client.get_data_connector_prices(fuel_type='VLSFO') for p in prices: ... print(f"{p.port}: ${p.price}/{p.unit}")

market_brief(codes, narrative=False)

Get a multi-commodity structured (+ optional narrative) market brief.

Composes existing price/forecast data for the given commodity codes into a single structured summary (#3245 Phase 1a). Counts as one request.

Parameters:

Name Type Description Default
codes List[str]

Commodity codes to include (e.g. ["BRENT_CRUDE_USD", "WTI"]).

required
narrative bool

When True, request a natural-language narrative as well.

False

Returns:

Type Description
MarketBrief

A MarketBrief model.

Example

brief = client.market_brief(["BRENT_CRUDE_USD"], narrative=True) print(brief.commodities[0].price)

close()

Close the HTTP client and stop telemetry.

__enter__()

Context manager entry.

__exit__(exc_type, exc_val, exc_tb)

Context manager exit.

__del__()

Cleanup on deletion.

Note: Relying on del for cleanup is non-deterministic. Prefer using context managers (with statement) or explicitly calling close().