You need a dependable way to pull the latest US Gasoline price from the EIA in JSON so you can automate surcharges, budgeting, or dashboards. By the end of this guide, you will call the FreightPulse endpoint for the US Gasoline metric, parse the exact field that matters, and ship code that handles auth, rate limits, and caching safely.
What you will get from the US Gasoline metric
The US Gasoline metric on FreightPulse exposes the EIA-sourced national average in a simple JSON envelope. You do not need to stitch together multiple sources or screen-scrape anything. The value is denominated in USD per gallon and is suitable for programmatic use in TMS, BI dashboards, and billing logic.
This article focuses only on the “US Gasoline” metric. It explains the exact field path to read, how to authenticate, and how to handle practical concerns like rate limits and caching. No guesswork, no scraping.
Access and authentication
Endpoint:
- GET https://freightpulsehq.com/api/v1/fuel-prices
Authentication:
- Header X-API-Key: YOUR_API_KEY
- Guest access without a key: 100 requests/day per IP
Envelope and data path:
- The API wraps results in the envelope: {"success":true,"data":{...}}
- For US Gasoline, read: data.gasoline.national_average
Units, currency and source
The US Gasoline metric is expressed in USD per gallon. The source is the U.S. Energy Information Administration (EIA). Do not invent or hardcode a “national average” in your code; always read it directly from data.gasoline.national_average.
This endpoint is intended for machine use. If you need additional fields, consult the Documentation. The product docs may show example shapes that include fields like diesel.national_average, change_week, regions.california, or historical.30d_avg. Treat those examples as illustrative unless those exact fields are present in your response.
Quickstart: cURL
Use the following cURL to test the endpoint. Replace YOUR_API_KEY with your key, or omit the header to use guest access (100 requests/day per IP).
curl -H "X-API-Key: YOUR_API_KEY" "https://freightpulsehq.com/api/v1/fuel-prices"
This request returns a JSON envelope with a data object. The field to read is data.gasoline.national_average.
Python example: fetch the US Gasoline national average
This Python example calls the same endpoint and extracts the EIA national average for gasoline. Values are not cached here; see the caching notes below to productionize.
import os
import requests
API_URL = "https://freightpulsehq.com/api/v1/fuel-prices"
API_KEY = os.getenv("FREIGHTPULSE_API_KEY", "YOUR_API_KEY")
def fetch_us_gasoline_avg():
headers = {"X-API-Key": API_KEY} if API_KEY else {}
resp = requests.get(API_URL, headers=headers, timeout=15)
resp.raise_for_status()
payload = resp.json()
# Validate the standard envelope
if not isinstance(payload, dict) or not payload.get("success"):
raise ValueError("Unexpected response envelope or success=false")
data = payload.get("data", {})
gasoline = data.get("gasoline", {})
avg = gasoline.get("national_average")
if avg is None:
raise KeyError("data.gasoline.national_average is missing in the response")
# The metric: USD per gallon, source EIA
return float(avg)
if __name__ == "__main__":
try:
national_avg = fetch_us_gasoline_avg()
print(f"US Gasoline (EIA) national average [USD/gal]: {national_avg}")
except Exception as e:
# In production: log with context, backoff, and retry if needed
print(f"Error: {e}")
Minimal JSON example (illustrative values)
The response uses a consistent envelope. The field you will actually consume is data.gasoline.national_average. Values below are illustrative only; do not persist or present them as live data.
{
"success": true,
"data": {
"gasoline": {
"national_average": 3.87
}
}
}
Field notes you will use:
- success: Boolean indicating whether the call succeeded.
- data.gasoline.national_average: The EIA-based US Gasoline national average in USD per gallon.
How to use the gasoline price safely in production
Read only the documented field
Bind your logic strictly to data.gasoline.national_average. Avoid depending on undocumented fields to minimize future breakage. When the shape expands, pin your client to the fields you need and review release notes in the Documentation.
Caching and request budgets
- Guest without a key is limited to 100 requests/day per IP. Add a simple cache (e.g., 1–24 hours depending on your business need) so you do not exhaust the quota.
- With a key, you still benefit from caching to reduce latency and improve resilience.
- When caching, always invalidate based on your refresh policy rather than attempting to infer intraday updates. If your workflow needs tighter freshness, decrease the TTL and monitor for changes.
Timestamps and timezone
If your UI or job runner needs to display “as of” times, prefer recording your fetch time alongside the value you received. If the response includes an explicit timestamp field in future versions, prefer that. When logging fetches, store in UTC for consistency across services.
Error handling
- Network or transient errors: retry with backoff (e.g., exponential backoff capped at a few seconds) and a modest retry budget.
- Non-JSON or unexpected envelope: treat as a hard error, log the body for inspection, and fall back to a cached value if available.
- Missing data.gasoline.national_average: fail gracefully and alert; do not substitute fabricated values.
Validation and guardrails
Add lightweight checks before you apply the value to pricing logic:
- Type check: ensure data.gasoline.national_average parses as a float.
- Range sanity: if your system has historical values, alert on abrupt deviations instead of auto-applying them. Keep any override process manual unless you have robust review workflows.
- Units: treat the number as USD per gallon. If your downstream expects liters or another currency, convert explicitly and keep conversion factors versioned.
Operational notes specific to FreightPulse
- Envelope shape: {"success":true,"data":{...}}. Always test success before consuming data.
- Authentication: header X-API-Key: YOUR_API_KEY. You may omit it for guest use, with 100 requests/day per IP.
- Fuel scope: Metric is US Gasoline. Do not invent or hardcode the national average.
- Port congestion data on FreightPulse is sourced from IMF PortWatch, lagged ~6–7 days, presented as a 7-day average vs a 90-day baseline. It is not live AIS.
- Freight rates: Do not quote a freight-rates USD fare as “today’s price.” This guide is only about the US Gasoline metric.
Embedding the price in applications
Billing and surcharges
When applying a fuel surcharge, read data.gasoline.national_average and use your internal formula. Keep the raw API value and your computed surcharge separate for auditability. Store a timestamp of when you fetched the value, and your cache duration setting, so you can reconstruct pricing decisions later.
Dashboards
For dashboards, pull the value server-side and push to widgets rather than calling the API from browsers. This keeps your key secure and avoids per-user duplication of guest request counts. If the dashboard is public, use a backend cache to decouple view traffic from API calls.
Scripting and automation
For cron jobs or Airflow tasks, set a deterministic fetch window (e.g., once daily during your accounting close hour) and implement retries followed by a cached fallback. Log the response envelope and the extracted value.
JavaScript alternative (Node.js)
If your stack is Node.js, the following snippet mirrors the Python logic and reads the same field:
import fetch from "node-fetch";
const API_URL = "https://freightpulsehq.com/api/v1/fuel-prices";
const API_KEY = process.env.FREIGHTPULSE_API_KEY || "YOUR_API_KEY";
async function fetchGasolineAverage() {
const headers = API_KEY ? { "X-API-Key": API_KEY } : {};
const resp = await fetch(API_URL, { headers, timeout: 15000 });
if (!resp.ok) {
throw new Error(`HTTP ${resp.status}`);
}
const payload = await resp.json();
if (!payload || payload.success !== true) {
throw new Error("Unexpected response envelope or success=false");
}
const avg = payload?.data?.gasoline?.national_average;
if (avg == null) {
throw new Error("data.gasoline.national_average is missing");
}
return Number(avg);
}
fetchGasolineAverage()
.then((v) => {
console.log(`US Gasoline (EIA) national average [USD/gal]: ${v}`);
})
.catch((err) => {
console.error("Error:", err.message);
});
Common pitfalls and how to avoid them
- Hardcoding a value: Never hardcode a “current” national average; always read data.gasoline.national_average.
- Over-polling without caching: Even if the value has not changed, you will burn through guest limits. Cache sensibly.
- Assuming undocumented fields: Bind strictly to the documented gasoline.national_average path.
- Mixing units: Downstream formulas must expect USD per gallon. Convert explicitly if required elsewhere.
Testing strategy
Before deploying to production, create a small integration test that:
- Makes a single GET request to the endpoint with your key or as a guest.
- Asserts payload.success === true and that data.gasoline.national_average is present and numeric.
- Verifies your cache write/read path by making a second call that returns the cached value instead of re-hitting the API.
In staging, run the test on a schedule near your intended production cadence to confirm your retry and fallback paths behave correctly during transient faults.
Security and key management
- Store YOUR_API_KEY in a secrets manager or environment variable; never commit it to source control.
- If you operate without a key under the guest plan, still route calls through your backend to avoid sharing your infrastructure’s IP quota with clients you do not control.
- Log only minimal metadata (status code, envelope success, numeric value) to avoid leaking keys or sensitive headers.
FAQ
Q: Which field contains the US Gasoline national average?
A: data.gasoline.national_average.
Q: What are the units and currency?
A: USD per gallon, source EIA.
Q: How do I authenticate?
A: Send your key in the header X-API-Key: YOUR_API_KEY. Without a key, you have guest access limited to 100 requests/day per IP.
Q: Is the response paginated?
A: No pagination is documented for this endpoint. Expect a single JSON envelope with the data object.
Q: Can I rely on additional fields like regions or historical data?
A: Use only fields present in your response. Examples in the docs may show shapes like diesel.national_average, change_week, regions.california, or historical.30d_avg. Treat them as illustrative unless they appear in your payload.
Ready to integrate the US Gasoline metric into your systems? Create an account to get an API key and explore the product details in the docs. Register and read the Documentation to ship your integration today.