Home → Blog

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:

Authentication:

Envelope and data path:

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:

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

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

Validation and guardrails

Add lightweight checks before you apply the value to pricing logic:

Operational notes specific to FreightPulse

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

Testing strategy

Before deploying to production, create a small integration test that:

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

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.