NewAnswers MCP: one question, one checked answer for your agent.See how it works

Guides

EIA API v2: get a key, query routes and facets, page in Python, connect an MCP server

By , founder of HyperresearchPublished

The EIA API is the U.S. Energy Information Administration’s free Open Data API, version 2, at https://api.eia.gov/v2/. You register with your name and email at eia.gov/opendata/register.php, EIA emails you a key, and you add api_key= to every request; there is no paid tier. A query walks a route tree (for example electricity/retail-sales), ends in /data/, names the columns it wants in data[], filters with facets[...], and returns at most 5,000 rows per call, so you page with offset and length.

Everything below was read from EIA’s API Technical Documentation, its FAQ and its Open Data page on November 15, 2026, and checked with live requests that day. The API reported "apiVersion":"2.1.14".

How to get an EIA API key

You get a key by filling in a short form; EIA sends it to your inbox automatically. The registration page says “Users of the EIA API are required to obtain an key.”

  1. Open eia.gov/opendata/register.php.
  2. Enter first name, last name and email, pick the category that describes you (Business/Industry, Student, Government, Research/Consulting and so on), and optionally say why you want the API.
  3. Tick “I agree to these terms of service” and submit.
  4. Copy the key from the email and add ?api_key=YOUR_EIA_API_KEY to every request. The documentation says the key “must always appear in the URL”; it is not read from HTTP headers.

If the email does not arrive, the FAQ says to make sure developer@eia.gov is whitelisted by your spam filter. A lost key can be resent from Forgot API Key. Keep it out of your code:

Terminal window
export EIA_API_KEY=YOUR_EIA_API_KEY

On Windows PowerShell: $env:EIA_API_KEY = "YOUR_EIA_API_KEY".

Testing without a key. api.eia.gov also accepted the public DEMO_KEY in our tests on November 15, 2026. It is not documented on eia.gov, and it allowed 10 requests from our IP address before returning HTTP 429 with a Retry-After that pointed to midnight UTC. It is enough to try one query, not to build anything.

Cost, rate limits and update timing

The API is free. EIA’s site says its data “is provided free of charge and should be used in compliance with our Copyrights and Reuse Policy.”

EIA does not publish exact throttles. Its FAQ says that “due to cybersecurity concerns, we are not able to publish our specific firewall rules”, and then gives a working guide: if you “keep your sustained rate less than ~9,000 per hour and your burst rate beneath 5 per second, your key won’t be throttled or temporarily disabled.” Some routes have slower limits. A throttled key is suspended for “between a few seconds and a number of minutes”, and bans do not last beyond an hour “unless under the most extreme circumstances.”

Limit Value Source
Price Free Open Data page
Rows per JSON response 5,000 Documentation and FAQ
Rows per XML response (out=xml) 300 Documentation and FAQ
Sustained rate that avoids throttling about 9,000 requests an hour FAQ, “speaking generally”
Burst rate that avoids throttling under 5 requests a second FAQ
Ban after throttling seconds to minutes, rarely an hour FAQ
DEMO_KEY 10 requests, reset at midnight UTC Observed 2026-11-15, not documented

The data has no fixed refresh schedule. The FAQ says APIv2 “directly accesses our public-facing databases” and is “updated constantly.” Weekly Petroleum Status Report and Weekly Natural Gas Storage Report figures reach the API within two hours of their 10:30 a.m. release; for the first seconds after release EIA points to ir.eia.gov.

How an EIA API v2 query is built

Every request is a path through the route tree plus query parameters. Ask for a route without /data and you get metadata; add /data and you get rows.

https://api.eia.gov/v2/electricity/retail-sales/data/?api_key=YOUR_EIA_API_KEY&frequency=monthly&data[0]=price&facets[stateid][]=CO&facets[sectorid][]=RES&sort[0][column]=period&sort[0][direction]=desc&offset=0&length=12
Parameter Example What it does
route electricity/retail-sales The dataset, a path in the tree
/data/ .../retail-sales/data/ Returns rows instead of metadata
data[] data[0]=price&data[1]=revenue The value columns; without it rows come back with no values
facets[x][] facets[stateid][]=CO Filter; repeat to pass several values or several facets
frequency monthly, weekly, daily, annual Periodicity, if the route has more than one
start, end 2026-01, 2026-10-01 Date bounds, in the frequency’s format
sort[n][column], sort[n][direction] period, desc Order; n starts at 0
offset, length 0, 5000 Paging; length cannot exceed 5,000
out xml XML instead of JSON (300-row cap)

The documentation also accepts the parameters in the HTTP request instead of the URL for very long queries, but the key always stays in the URL.

Each response carries response.total, the number of rows that match regardless of length; response.data, the rows; and a request block echoing what the API understood. Values arrive as strings: the January 2024 release (v2.1.6) standardized them that way because some identifiers need leading zeros. In our tests the /v2/seriesid/ route still returned value and total as JSON numbers, so convert with float() either way.

Browsing the route tree

Start at the root and walk down. GET https://api.eia.gov/v2/?api_key=... lists the top-level routes (coal, crude-oil-imports, electricity, international, natural-gas, petroleum, seds, steo, aeo, ieo, total-energy and others). Each child route answers the same way until you reach a leaf, whose metadata lists its frequencies, facets, data columns and date range. For petroleum/pri/gnd (retail gasoline and diesel prices) on November 15, 2026 it reported frequencies weekly, monthly and annual; facets duoarea, product, process and series; one data column, value; and a range from 1990-08-20 to 2026-11-09.

To list the allowed values of one facet, request /{route}/facet/{facet_id}/, for example /v2/electricity/retail-sales/facet/sectorid/, which returns COM, RES, ALL, OTH, TRA and IND. The documentation warns that a facet value not on the list is not an error: the query succeeds and returns no rows.

The API browser on eia.gov builds the same URLs by point and click and is the fastest way to find a route and its facet codes.

Paging past 5,000 rows

The API returns at most 5,000 rows per JSON call, so a larger result needs several calls. Keep the same sort, read total, and step offset by the number of rows you received until you reach it. Without a sort, results used to come back in an unpredictable order; since September 2025 (v2.1.9) every query has a default sort, but an explicit sort keeps pages stable.

When a query matches more rows than one response can hold, the API adds a warning beside the data: “The API can only return 5000 rows in JSON format. Please consider constraining your request with facet, start, or end, or using offset to paginate results.” In our tests this “incomplete return” warning also appeared on small queries that set length (one matched only 308 rows), so compare total with the rows you received rather than trusting the warning.

Dates and frequencies

Pass start and end in the period format of the frequency you asked for: 2026 for annual, 2026-08 for monthly, 2026-11-09 for weekly and daily. Since January 2026 (v2.1.11), start=2024&end=2024 on a monthly route returns all twelve months of 2024; before that it returned nothing.

Translating v1 series IDs to v2

Old v1 series IDs still work through the /v2/seriesid/ route. EIA added it in November 2022 (v2.1.0) for backward compatibility:

https://api.eia.gov/v2/seriesid/PET.EMM_EPM0_PTE_NUS_DPG.W?api_key=YOUR_EIA_API_KEY

On November 15, 2026 that call returned the U.S. all-grades retail gasoline price with its v2 route in the echo: "route":"petroleum/pri/gnd", "facets":{"series":["EMM_EPM0_PTE_NUS_DPG"]}, "frequency":"weekly". That echo is the translation: copy the route, facet and frequency into a /data/ query and you no longer depend on the old ID. The Open Data page also has a “Translate APIv1 Series ID to APIv2” form.

The FAQ warns there is “not a perfect 1:1 mapping”, so a translated query can return more or fewer rows than the v1 series did. The old v1 URL form, api.eia.gov/series/?series_id=..., belongs to the retired API: EIA’s FAQ gave January 2023 as the target, and a GitHub issue on the rOpenSci eia R package reported v1 gone on March 13, 2023. Code written against v1, including several Python and R wrappers that still rank for “eia api”, needs the v2 route or the seriesid path.

EIA API endpoints

Endpoint Key Returns
GET /v2/ Yes Top-level routes
GET /v2/{route}/ Yes Child routes, or a leaf’s frequencies, facets, data columns and date range
GET /v2/{route}/facet/{facet_id}/ Yes Allowed values for one facet
GET /v2/{route}/data/ Yes Rows, up to 5,000 per call
GET /v2/seriesid/{v1_series_id} Yes Rows for a v1 series ID, with the v2 route echoed
https://www.eia.gov/opendata/bulk/{FILE}.zip No A whole dataset as one zip
https://www.eia.gov/opendata/bulk/manifest.txt No JSON list of bulk files with last_updated

Common recipes: gasoline, electricity and Henry Hub

Three routes answer most “EIA price API” searches. All three were called on November 15, 2026; the figures are what the API returned that day.

Need Route Filter Frequency and unit Latest row, Nov 15, 2026
U.S. regular gasoline retail price petroleum/pri/gnd facets[series][]=EMM_EPMR_PTE_NUS_DPG weekly, $/gal 2026-11-09: 3.995
U.S. all-grades gasoline retail price petroleum/pri/gnd facets[series][]=EMM_EPM0_PTE_NUS_DPG (or duoarea=NUS, product=EPM0) weekly, $/gal 2026-11-09: 4.134
Retail electricity price by state electricity/retail-sales data[]=price, facets[stateid][]=CO, facets[sectorid][]=RES monthly, cents per kWh 2026-08: 17.17 (Colorado residential)
Henry Hub natural gas spot price natural-gas/pri/fut facets[series][]=RNGWHHD daily, $/MMBtu 2026-11-11: 3

Three details trip people up. Henry Hub’s spot price lives under the futures route (pri/fut), as series RNGWHHD with the description “Henry Hub Natural Gas Spot Price (Dollars per Million Btu)”. The gasoline route’s only data column is value, so data[0]=price fails there with a 400. And stateid on the electricity route also holds census regions and the U.S. total (its facet is described as “State / Census Region”), so filter or drop those rows when you want states only. Electricity sector codes are RES (residential), COM (commercial), IND (industrial), TRA (transportation), OTH (other) and ALL.

Python with requests and pagination

This client uses requests only. It sends the key, retries 429 and 5xx responses with backoff, raises a readable error for EIA’s two error shapes, and pages through any /data query until it has total rows.

import os
import time
import requests
API_KEY = os.environ["EIA_API_KEY"] # set to YOUR_EIA_API_KEY
BASE_URL = "https://api.eia.gov/v2"
MAX_ROWS = 5000 # the most rows one JSON response can hold
class EIAError(RuntimeError):
pass
def eia_get(path, params=(), retries=3):
"""GET one EIA API v2 path; return the parsed JSON or raise EIAError."""
url = f"{BASE_URL}/{path.strip('/')}/"
query = list(params) + [("api_key", API_KEY)]
for attempt in range(retries + 1):
resp = requests.get(url, params=query, timeout=60)
retryable = resp.status_code in (429, 502, 503, 504)
wait = int(resp.headers.get("Retry-After", 5 * 2**attempt))
if retryable and attempt < retries and wait <= 120:
time.sleep(wait)
continue
break
try:
body = resp.json()
except ValueError: # 504s come back as an HTML page
raise EIAError(f"HTTP {resp.status_code}: {resp.text[:200]}") from None
error = body.get("error")
if isinstance(error, dict): # key and rate-limit errors
raise EIAError(f"HTTP {resp.status_code} {error.get('code')}: {error.get('message')}")
if error: # bad route, column, facet or frequency
raise EIAError(f"HTTP {resp.status_code}: {error}")
return body
def eia_data(route, data, frequency=None, facets=None, start=None, end=None,
sort=(("period", "asc"),), page_size=MAX_ROWS):
"""Fetch every row of a /data query, paging with offset and length."""
params = []
if frequency:
params.append(("frequency", frequency))
for i, column in enumerate(data):
params.append((f"data[{i}]", column))
for facet, values in (facets or {}).items():
for value in values:
params.append((f"facets[{facet}][]", value))
if start:
params.append(("start", start))
if end:
params.append(("end", end))
for i, (column, direction) in enumerate(sort):
params += [(f"sort[{i}][column]", column), (f"sort[{i}][direction]", direction)]
rows, offset = [], 0
while True:
page = [("offset", offset), ("length", min(page_size, MAX_ROWS))]
response = eia_get(f"{route}/data", params + page)["response"]
batch = response["data"]
rows.extend(batch)
offset += len(batch)
if not batch or offset >= int(response["total"]):
return rows
time.sleep(0.5) # stay well under the documented 5 requests a second
def to_float(value):
"""EIA values arrive as strings (sometimes numbers, sometimes null)."""
return None if value in (None, "") else float(value)

The three recipes from the table, using that client:

# Weekly U.S. regular gasoline retail price since January 2026
gas = eia_data(
"petroleum/pri/gnd", ["value"], frequency="weekly",
facets={"series": ["EMM_EPMR_PTE_NUS_DPG"]}, start="2026-01-01",
)
print(gas[-1]["period"], to_float(gas[-1]["value"]), gas[-1]["units"])
# Residential electricity price for every state in August 2026 (cents per kWh)
power = eia_data(
"electricity/retail-sales", ["price"], frequency="monthly",
facets={"sectorid": ["RES"]}, start="2026-08", end="2026-08",
)
for row in sorted(power, key=lambda r: to_float(r["price"]) or 0, reverse=True)[:5]:
print(row["stateid"], row["stateDescription"], row["price"])
# Henry Hub daily spot price, full history (about 7,500 rows, so two pages)
henry_hub = eia_data(
"natural-gas/pri/fut", ["value"], frequency="daily",
facets={"series": ["RNGWHHD"]},
)
print(len(henry_hub), henry_hub[-1]["period"], henry_hub[-1]["value"])

To use an old v1 ID, call eia_get("seriesid/PET.EMM_EPM0_PTE_NUS_DPG.W", [("length", 5)]) and read body["request"]["params"] and body["request"]["route"] for the v2 equivalent. For a pandas DataFrame, pass the rows in with pd.DataFrame(rows) and convert the value column with pd.to_numeric(df["value"], errors="coerce").

EIA API errors and fixes

EIA returns two error shapes. Key and rate-limit errors come from the gateway as {"error": {"code": ..., "message": ...}}; query errors come from the API as {"error": "...", "code": 400}. Since October 2025 (v2.1.10) the HTTP status matches the error in the body. These bodies were recorded on November 15, 2026:

Status Body or symptom Cause Fix
403 {"error": {"code": "API_KEY_MISSING", "message": "No api_key was supplied. Please register for one at https://www.eia.gov/opendata/register.php"}} No api_key in the URL Add api_key=; the key is not read from headers
403 {"error": {"code": "API_KEY_INVALID", "message": "An invalid api_key was supplied. Get one at https://api.eia.gov:443"}} Key mistyped, padded or not issued Copy the key from the email again
429 {"error": {"code": "OVER_RATE_LIMIT", "message": "You have exceeded your rate limit. Try again later or contact us for assistance: https://api.eia.gov:443"}} plus Retry-After Too many requests (seen with DEMO_KEY) Wait for Retry-After; stay under 5 a second
400 {"error":"Requested path \/petroleum\/nosuchroute is not valid.","code":400} Route does not exist Walk the tree from /v2/
400 {"error":"Invalid data 'price' provided. The only valid data are 'value'.","code":400} Column not on this route Read the route’s metadata data block
400 "Invalid frequency 'millenially' provided. The only valid frequencies are 'monthly', 'quarterly', and 'annual'." Frequency not offered (example from EIA’s docs) Use one from the metadata
504 HTML page “504 Gateway Time-out” after about 10 seconds Slow or overloaded route Retry with backoff; narrow the query
200, no values Rows with period and facets but no numbers Missing data[] Add data[0]=...
200, metadata only Frequencies and facets, no rows Route does not end in /data Add /data/
200, zero rows "total": 0 Facet value not in the list, or dates outside the range Check /facet/{id}/ and the route’s date range
Embed shows API_KEY_MISSING Chart embed on a website Embeds now need a key Add your key to the embed code

We saw two 504 responses in nine keyed calls: one on a bad route, which later returned the 400 above, and one on a valid gasoline query filtered by duoarea and product, while a gasoline query through the series facet answered normally a few minutes later. Treat 504 as retryable.

Bulk download files

Bulk files give you an entire dataset in one zip, and they need no key. The registration page says “An API key is not required to use the bulk download facility.” The list is on the Open Data page; sizes below are in kilobytes as printed there on November 15, 2026.

File Contents Size (KB)
PET.zip Petroleum 53,941
NG.zip Natural gas 4,332
ELEC.zip Electricity 294,600
EBA.zip Hourly electric system operating data, 2019 to present 687,295
SEDS.zip State Energy Data System 9,246
STEO.zip Short-Term Energy Outlook 5,297
INTL.zip International 23,583
TOTAL.zip Total energy 3,170
COAL.zip, PET_IMPORTS.zip, NUC_STATUS.zip, EMISS.zip, IEO*.zip, AEO2014.zip to AEO2026.zip Coal, crude imports, nuclear outages, emissions, outlooks 391 to 89,505

Each zip holds one .txt file in which “each line of the extracted text file is a complete object in JSON”: every series (with its v1-style series_id, name, units, frequency and a data array of [period, value] pairs), then the category tree. EIA says the bulk update “runs twice daily at 5 a.m. and 3 p.m. eastern time” and files are ready 30 to 45 minutes later. Check manifest.txt first: on November 15, 2026 it showed PET last updated 2026-11-12 and ELEC 2026-10-22, so download only what changed.

EIA version history with dates

The current API is v2; v1 is retired. These dates come from the patch notes on EIA’s documentation page unless marked otherwise.

Date Change
2012 Original API (v1) launched
February 2022 v2.0.1 community release
May 2022 v2.0.2 public release; XML output with out=xml
November 2022 v2.1.0: /v2/seriesid/ translation for v1 IDs; in-response warnings
March 13, 2023 v1 reported retired (rOpenSci eia GitHub issue #11)
January 2024 v2.1.6: all data values returned as strings
September 2025 v2.1.9: default sort on every query; v1 IDs not found return 404
October 2025 v2.1.10: HTTP status codes match the error in the body
January 2026 v2.1.11: identical start and end dates return the whole period
March 2026 v2.1.12: fix to total with date bounds; performance work
November 15, 2026 Live API reports apiVersion 2.1.14

EIA MCP servers for Claude, Cursor and ChatGPT

EIA does not publish an MCP server. A search of the official MCP registry for “eia” on November 15, 2026 found no entry from EIA, and EIA’s GitHub account (EIAgov) holds four repositories, none of them an MCP server. Every EIA MCP server is a community or third-party wrapper around the same v2 API, and all of them need an EIA key except a hosted instance that uses its operator’s.

Repository Stars Last push Language Tools Notes
cyanheads/eia-energy-mcp-server 3 2026-11-15 TypeScript 4 core + 3 SQL v0.6.0 on npm; in the MCP registry; hosted instance; resolves v1 series IDs; Apache-2.0
GSA-TTS/mcp-server-eia 0 2026-11-15 Python 3.14 4 From the GSA Technology Transformation Services org, built for a GSA MCP gateway; run from source with uv
zen-tradings/eia-mcp 6 2026-01-18 Python 14 Electricity and natural gas only; one tool per route
MissionSquad/mcp-eia 1 2025-08-13 TypeScript analysis tools Electricity datasets only
QuentinCody/eia-mcp-server 0 2026-11-13 TypeScript search and execute Cloudflare Worker; README says live validation with a key is still pending

cyanheads/eia-energy-mcp-server covers all of v2. Its tools are eia_browse_routes, eia_describe_route, eia_search_routes (which finds “Henry Hub” as natural-gas/pri/fut series RNGWHHD and turns a v1 ID such as ELEC.PRICE.TX-RES.M into the route and filters), eia_query_route, and three eia_dataframe_* tools that run read-only SQL over staged results. The snippets below are from its README and the clients’ docs.

Claude Desktop

Open Settings > Developer > Edit Config (claude_desktop_config.json, in ~/Library/Application Support/Claude/ on macOS or %APPDATA%\Claude\ on Windows) and add:

{
"mcpServers": {
"eia-energy": {
"command": "npx",
"args": ["-y", "@cyanheads/eia-energy-mcp-server@latest"],
"env": {
"MCP_TRANSPORT_TYPE": "stdio",
"EIA_API_KEY": "YOUR_EIA_API_KEY"
}
}
}
}

Restart Claude Desktop. The project also ships a one-click Claude Desktop bundle, eia-energy-mcp-server.mcpb, on its releases page.

Claude Code

Terminal window
claude mcp add --transport stdio eia-energy -s user \
-e MCP_TRANSPORT_TYPE=stdio -e EIA_API_KEY=YOUR_EIA_API_KEY \
-- npx -y @cyanheads/eia-energy-mcp-server@latest

To try it without a key, point Claude Code at the author’s public hosted instance:

Terminal window
claude mcp add --transport http eia-energy https://eia-energy.caseyjhand.com/mcp

That endpoint answered an MCP initialize call on November 15, 2026 with server version 0.6.0 and no sign-in. It is run by the project’s author, not by EIA, and your queries go through it and its key, so use your own key for anything regular.

Cursor

Put the same entry in ~/.cursor/mcp.json (all projects) or .cursor/mcp.json (one project). Cursor can read the key from your environment:

{
"mcpServers": {
"eia-energy": {
"command": "npx",
"args": ["-y", "@cyanheads/eia-energy-mcp-server@latest"],
"env": {
"MCP_TRANSPORT_TYPE": "stdio",
"EIA_API_KEY": "${env:EIA_API_KEY}"
}
}
}
}

ChatGPT

ChatGPT connects only to remote MCP servers, so it needs an HTTP endpoint such as the hosted instance above or your own deployment (MCP_TRANSPORT_TYPE=http). OpenAI’s help page on connecting custom MCP servers says full MCP is for Business and Enterprise/Edu workspaces and that “Pro users can connect custom MCP servers with read/fetch permissions.” Add it from Plugins, the plus button, then Add custom MCP server, with the URL https://eia-energy.caseyjhand.com/mcp. If you host your own copy with your key inside, put authentication in front of it: the server supports jwt and oauth modes.

Terms of use

EIA’s API Terms of Service, shown on the registration page, let you use the API “to develop a service to search, display, analyze, retrieve, view and otherwise ‘get’ information from EIA data.” You should name “EIA” or “the U.S. Energy Information Administration” as the source, may not imply EIA endorses your product, may not use the EIA logo without written permission, and may not modify content and still call EIA the source. A “Right to Limit” clause lets EIA block users who try to exceed or get around its limits.

Choosing a route for EIA data

The right route depends on how much data you need and where you use it.

  • One series or a filtered slice, kept current: the /v2/{route}/data/ endpoint with the client above.
  • Code or a spreadsheet built on v1 series IDs: /v2/seriesid/{id} once to read the v2 route, then switch to /data/.
  • A whole dataset, or thousands of series: the bulk zip files, which need no key and spare you the 5,000-row paging.
  • Excel or Google Sheets: EIA’s spreadsheet add-ins; the FAQ says the Excel add-in converts v1 series IDs in your workbooks automatically.
  • The weekly petroleum and gas storage numbers the moment they are released: ir.eia.gov, since the API can lag by up to two hours.
  • Questions in Claude, Cursor or ChatGPT: an EIA MCP server, with your own key.
  • EIA prices next to other sources in one cited answer: Hyperresearch reads EIA electricity and natural gas prices by state and sector as one of its 120+ data sources.

For other public data APIs, see the guides to the FRED API in Python, the Census Data API and the SEC EDGAR API; for MCP servers across public datasets, see research data MCP servers.

Sources