You need a reliable, finance-grade way to fetch the official diesel fuel price fixture as JSON so your surcharge formulas, budgets, or risk dashboards use a consistent source of truth. By the end of this guide, you will make a successful first request to the FreightPulse Fuel Prices API, parse the canonical fields, and integrate them into a finance workflow without guessing fields or formats.
What you will implement
This guide is a first-request walkthrough that gets you from zero to a working call against the FreightPulse Finance metric “Fuel Prices,” returning the official JSON fixture you will reference in your models. You will:
- Authenticate with the required header and understand the guest request cap.
- Call the endpoint that returns the envelope and documented fields for diesel prices.
- Parse the JSON to read diesel.national_average and related fields for downstream finance calculations (e.g., surcharge indexing, budget variance tracking).
- Apply practical integration details—units, currency, caching strategy, and caveats around data refresh.
Every step below uses only the documented endpoint, fields, and behaviors, so you can copy and paste with confidence.
Endpoint and authentication
The Fuel Prices Finance metric is available at a single endpoint:
- Endpoint: https://freightpulsehq.com/api/v1/fuel-prices
- Method: GET
- Auth: header X-API-Key: YOUR_API_KEY
- Guest usage: Without an API key, you can make up to 100 requests per day per IP.
All responses use a consistent envelope: {"success":true,"data":{...}}. You will read your required fields from data.
Data dictionary for finance workflows
The fixture exposes the diesel price and related aggregates you will most likely need for finance calculations:
- data.diesel.national_average: The key figure you will index against for expenses and surcharges.
- data.diesel.change_week: Week-over-week change, useful for monitoring volatility.
- data.diesel.regions.california: Regional figure, often required for West Coast operations and compliance modeling.
- data.diesel.historical.30d_avg: Rolling 30-day average for smoothing daily/weekly noise in budgets.
Units and source of record:
- Currency: USD
- Unit: gallon
- Source: EIA (Energy Information Administration)
Important constraint for finance users: Do not quote a freight-rates USD fare as today’s price using this endpoint; it is specifically the Fuel Prices metric (diesel). When modeling freight spend, keep fares separate from fuel price indexing.
Make your first request (curl)
Copy and run the following command. It includes the documented authentication header and calls the single Fuel Prices endpoint:
curl -H "X-API-Key: YOUR_API_KEY" "https://freightpulsehq.com/api/v1/fuel-prices"
If you do not supply a key, your IP is limited to 100 requests per day. For production finance jobs, use an API key to avoid silent throttling during end-of-month close or daily batch windows. You can create a key after you Register.
Sample JSON response and field mapping
The following response illustrates the documented fields and envelope. Values are illustrative and not live prices:
{
"success": true,
"data": {
"diesel": {
"national_average": 4.21,
"change_week": -0.03,
"regions": {
"california": 5.15
},
"historical": {
"30d_avg": 4.27
}
}
}
}
How to use these fields in finance contexts:
- diesel.national_average: Index your fuel surcharge or adjust cost-of-goods-sold allocations.
- diesel.change_week: Track directional movement for risk dashboards; alert when change breaches a threshold.
- diesel.regions.california: Apply regional overrides or compliance-linked assumptions for operations concentrated in California.
- diesel.historical.30d_avg: Smooth intra-month volatility for accruals or forecast true-ups.
Minimal Python example
This Python snippet calls the same endpoint, checks the envelope, and extracts the core finance fields for downstream calculations:
import requests
API_URL = "https://freightpulsehq.com/api/v1/fuel-prices"
headers = {
"X-API-Key": "YOUR_API_KEY"
}
resp = requests.get(API_URL, headers=headers, timeout=10)
resp.raise_for_status()
payload = resp.json()
if not payload.get("success"):
raise RuntimeError("Fuel Prices API returned success=false")
data = payload.get("data", {})
diesel = data.get("diesel", {})
national_avg = diesel.get("national_average")
weekly_change = diesel.get("change_week")
regions = diesel.get("regions", {})
california = regions.get("california")
historical = diesel.get("historical", {})
avg_30d = historical.get("30d_avg")
# Example: decide which value to index in your finance model
if national_avg is None:
raise ValueError("Missing diesel.national_average from Fuel Prices fixture")
print({
"national_average_usd_per_gallon": national_avg,
"change_week_usd_per_gallon": weekly_change,
"california_usd_per_gallon": california,
"avg_30d_usd_per_gallon": avg_30d
})
How to wire these fields into finance formulas
This section shows where each field typically lands in finance logic. Replace the model specifics with your organization’s policy; do not substitute this with a freight fare.
- Fuel surcharge basis: Use diesel.national_average as the price index. Multiply by your contracted conversion factors (e.g., mpg assumptions) and volume to derive the fuel component of spend.
- Accrual smoothing: For monthly close, diesel.historical.30d_avg can reduce end-of-period noise if your policy allows rolling averages for accrual calculations.
- Regional exposure: If operations are weighted to California, apply diesel.regions.california in a weighted blend to better align with actual station prices paid, subject to your compliance requirements.
- Volatility triggers: diesel.change_week can feed alerts that escalate review of surcharge pass-throughs or hedging decisions.
Governance tip: Keep the input fixture (the JSON you fetch) immutable in storage to support audit trails for close reviews and external audit sampling.
Units, currency, and accuracy notes
Every numeric fuel price value in this fixture is denominated in USD per gallon, with the source noted as EIA. Build unit tests that assert both currency and unit to avoid silent regressions if your pipeline ever ingests an incompatible data source.
Do not re-interpret this endpoint as a live freight fare or a live congestion proxy. The Fuel Prices metric is separate from freight fares; keep those models distinct. Additionally, where your finance suite references congestion alongside fuel (for scenario analysis), note that port congestion in this catalog is sourced from IMF PortWatch, lagged approximately 6–7 days and based on a 7-day average versus a 90-day baseline (not live AIS). Keep that lag in mind when pairing congestion insights with weekly diesel changes.
Caching and refresh strategy
Because fuel-linked finance jobs often run on fixed schedules (daily or weekly), you should:
- Cache the response in your data store for the job’s run date/time. Use the cached value consistently across the run to ensure every ledger entry uses the same figure.
- If your scheduler retries jobs, persist the first successful fixture to prevent within-day drift if a later retry occurs after an upstream refresh.
- If the fixture has not changed between runs, skip downstream recalculations to save compute and lower reconciliation noise.
Guest usage is capped at 100 requests per day per IP. If your finance workflows involve multiple environments (dev, CI, prod), count aggregate calls against this limit or use an API key in each environment to avoid unplanned throttling.
Error handling and envelope validation
Always check the top-level envelope before reading nested fields:
- Verify success is true. If false, raise an actionable error with the full response body captured to your logs.
- Confirm data is present, then assert the existence of diesel and diesel.national_average specifically.
- Guard optional fields like regions.california and historical.30d_avg with safe fallbacks in your code paths.
If you encounter unexpected shapes, note the time, the run context (e.g., close vs. forecast), and halt mutation of your finance data until the response validates. This prevents tainting your subledgers with partial inputs.
Non-functional considerations for Finance teams
- Idempotency: Store a content hash of the response so you can quickly detect changes during the same accounting period.
- Observability: Emit metrics for request latency, success flag, and presence of diesel.national_average. Alarm on absence or repeated parsing failures.
- Version control: Archive the raw JSON with a clear as-of timestamp from your system clock; the documented fixture does not include a native timestamp field.
- Access control: Restrict API keys used in close processes to a secure secret manager; rotate keys on a defined cadence.
JavaScript example (Node.js, fetch)
If you prefer JavaScript, this snippet demonstrates the same minimal extraction against the official fixture:
import fetch from "node-fetch";
const API_URL = "https://freightpulsehq.com/api/v1/fuel-prices";
async function getFuelPrices() {
const res = await fetch(API_URL, {
method: "GET",
headers: { "X-API-Key": "YOUR_API_KEY" }
});
if (!res.ok) {
throw new Error(`HTTP ${res.status}`);
}
const payload = await res.json();
if (!payload.success) {
throw new Error("Fuel Prices API returned success=false");
}
const diesel = payload.data?.diesel || {};
const nationalAverage = diesel.national_average;
const weeklyChange = diesel.change_week;
const california = diesel.regions?.california;
const avg30d = diesel.historical?.["30d_avg"];
if (nationalAverage == null) {
throw new Error("Missing diesel.national_average");
}
return {
national_average_usd_per_gallon: nationalAverage,
change_week_usd_per_gallon: weeklyChange,
california_usd_per_gallon: california,
avg_30d_usd_per_gallon: avg30d
};
}
getFuelPrices()
.then(console.log)
.catch(err => {
console.error("Failed to fetch Fuel Prices:", err);
process.exit(1);
});
Testing strategy that avoids rework at month-end
- Schema contract tests: Assert presence and numeric type for diesel.national_average, diesel.change_week, and numeric or null for optional fields.
- Unit invariants: Confirm currency=USD and unit=gallon are documented; reject any pipeline that attempts conversions without explicit approval.
- Cache behavior: In integration tests, ensure only one fetch is performed per scheduled job regardless of retry count.
- Drift watch: Validate that weekly variance (change_week) is not accidentally treated as a percentage when your models expect an absolute delta in USD per gallon.
Operational runbook notes
When the job fails to parse the envelope or diesel.national_average is missing:
- Quarantine the run: Do not push partial entries to your ledger or forecasts.
- Re-run with the same inputs after investigation. If you must move forward, explicitly document the contingency method (e.g., use the previous archived fixture) per your finance policy.
- File the incident with logs and the raw JSON in your ticketing system for audit traceability.
Where your finance team pairs fuel exposure with congestion or other operational indicators, remember the provided congestion metric is lagged by ~6–7 days and is a 7-day average versus a 90-day baseline, sourced from IMF PortWatch—not live AIS. Align analysis windows accordingly to prevent mismatched time bases in scenario models.
Common pitfalls to avoid
- Using the Fuel Prices endpoint as a proxy for freight fares. Keep fare models separate and do not quote a fare as today’s price based on this metric.
- Assuming timestamps are present in the fixture. Archive with your own as-of time so finance can reproduce results.
- Skipping envelope validation. Always check success and the presence of data before parsing.
- Over-polling without a key. Guest mode has a 100 requests/day per IP limitation; use an API key in production.
FAQ
Is there pagination on this endpoint?
No pagination is required for this fixture. The documented response is a small, single-object payload.
How often does the price update?
The guide does not specify an update schedule in the fixture itself. Treat the endpoint as providing the latest available EIA-sourced dataset and archive each pull with your system’s timestamp for auditability.
What units and currency should I model in my ledger?
All prices are USD per gallon. Do not convert unless your policy explicitly calls for a different presentation currency or unit.
Can I access the API without a key?
Yes, as a guest you are limited to 100 requests per day per IP. For batch jobs or month-end close, create an API key to avoid rate-related interruptions.
Does the response include live congestion or freight fare data?
No. This endpoint is strictly the Fuel Prices Finance metric. Do not treat it as a live congestion or freight fare source. Where referenced, congestion data is IMF PortWatch-based and lagged ~6–7 days.
Ready to wire the official Fuel Prices fixture into your finance models? Create your key and start integrating today: Register. For field-by-field references and additional context, see the Documentation.