Fuel surcharge API in Python: DOE diesel, LTL and parcel
By OilPriceAPI · API and live diesel source checked November 5, 2026
A weekly DOE/EIA diesel observation and a carrier's published surcharge table answer different questions. The first is an index input; the second is a carrier rate with its own effective date. Your contract determines how to apply either one.
Run the Python example
Set OILPRICEAPI_KEY, save this as fuel_surcharge.py, and run python3 fuel_surcharge.py. The script requests DIESEL_RETAIL_USD, the LTL carrier table, and UPS parcel service levels. It checks the diesel source time and reports published carrier percentages with their effective dates.
import json
import math
import os
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError
from urllib.request import Request, urlopen
base = "https://api.oilpriceapi.com/v1"
key = os.environ.get("OILPRICEAPI_KEY")
if not key:
raise SystemExit("Set OILPRICEAPI_KEY before running this example")
def valid_effective_date(value):
if not isinstance(value, str):
return False
try:
return datetime.strptime(value, "%Y-%m-%d").date().isoformat() == value
except ValueError:
return False
def get(path):
request = Request(base + path, headers={"Authorization": "Token " + key})
try:
with urlopen(request, timeout=10) as response:
payload = json.load(response)
except HTTPError as error:
if error.code in (401, 403):
raise SystemExit("Check API key and dataset access for this account")
if error.code in (402, 429):
raise SystemExit("Quota or rate limit reached; check account limits")
if error.code == 404:
raise SystemExit("Carrier or source data unavailable; check covered carriers")
raise SystemExit(f"API request failed with HTTP {error.code}") from error
except URLError:
raise SystemExit("API unavailable; retry later, not with a zero rate")
if not isinstance(payload, dict) or payload.get("status") != "success":
raise SystemExit("API returned no usable result")
return payload.get("data")
diesel = get("/prices/latest?by_code=DIESEL_RETAIL_USD")
if not isinstance(diesel, dict) or diesel.get("code") != "DIESEL_RETAIL_USD":
raise SystemExit("Diesel index missing or mismatched")
price = diesel.get("price")
as_of = diesel.get("as_of")
if (isinstance(price, bool) or not isinstance(price, (int, float))
or not math.isfinite(price) or price < 0
or diesel.get("currency") != "USD" or diesel.get("unit") != "gallon"
or not isinstance(as_of, str) or not as_of):
raise SystemExit("Diesel price, unit or source time is unusable")
try:
observed_at = datetime.fromisoformat(as_of.replace("Z", "+00:00"))
except ValueError:
raise SystemExit("Diesel source time is malformed")
age_seconds = (datetime.now(timezone.utc) - observed_at).total_seconds() if observed_at.tzinfo else None
if age_seconds is None or age_seconds < 0 or age_seconds > 10 * 86400:
raise SystemExit("Diesel observation is old or lacks a timezone; check EIA")
if diesel.get("stale") or diesel.get("data_status") == "stale" or diesel.get("dataStatus") == "stale":
raise SystemExit("Diesel observation is stale; check the EIA release")
print("US diesel index:", price, "USD/gallon as of", as_of)
# Illustrative contract inputs; replace them with your signed tariff.
baseline_usd_per_gallon = 2.50
miles_per_gallon = 6.0
loaded_miles = 500.0
per_mile = max(0.0, (price - baseline_usd_per_gallon) / miles_per_gallon)
print("Example contract surcharge:", round(per_mile * loaded_miles, 2),
"USD for", loaded_miles, "loaded miles")
carriers = get("/fuel-surcharge")
rows = carriers.get("carriers") if isinstance(carriers, dict) else None
if not isinstance(rows, list) or not rows:
raise SystemExit("Carrier table unavailable; do not infer a zero rate")
shown = 0
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("carrier"), str):
continue
percent = row.get("surcharge_percent")
if (isinstance(percent, (int, float)) and not isinstance(percent, bool)
and math.isfinite(percent) and percent >= 0
and valid_effective_date(row.get("effective_date"))):
print(row["carrier"], percent, "% effective", row["effective_date"])
shown += 1
if shown == 0:
raise SystemExit("No carrier row has a usable rate and effective date")
parcel = get("/fuel-surcharge/parcel/ups/latest")
levels = parcel.get("service_levels") if isinstance(parcel, dict) else None
if (not isinstance(levels, list) or parcel.get("carrier") != "ups"
or parcel.get("mode") != "parcel"):
raise SystemExit("UPS parcel service levels unavailable")
shown = 0
for row in levels:
if not isinstance(row, dict) or row.get("carrier") != "ups":
continue
percent = row.get("surcharge_percent")
if (isinstance(percent, (int, float)) and not isinstance(percent, bool)
and math.isfinite(percent) and percent >= 0
and isinstance(row.get("service_level"), str) and row["service_level"]
and valid_effective_date(row.get("effective_date"))):
print("UPS", row["service_level"], percent, "% effective",
row["effective_date"])
shown += 1
if shown == 0:
raise SystemExit("No UPS parcel service level has a usable rate and date")
The per-mile calculation is an illustration: above a $2.50/gal baseline, divide the index difference by 6 miles per gallon, then multiply by 500 loaded miles. Replace those three inputs with your actual contract. Do not add a published LTL percentage to that example; carrier tariffs can use different bands and effective dates.
Choose the right carrier path
The API reference lists /v1/fuel-surcharge and one-carrier LTL paths. Parcel rates have separate /v1/fuel-surcharge/parcelpaths because service levels differ. The example asks for UPS levels without assuming that ground is present; use the returned level and effective date before quoting. A missing row is unavailable, not a zero rate.