The Treasury FiscalData API exposes federal financial datasets programmatically without requiring an account or registration token. Endpoints accept HTTP GET requests and default to JSON responses. Reliable debt dashboards anchor every figure to a dated Treasury record rather than an undated headline or an assumption of live market data.
The code snippets below demonstrate debt queries, interest-rate filters and a basic local file cache. Sample outputs serve purely as illustrations rather than verified observations. Always inspect a fresh dated record before relying on a value, and remember that open access guarantees neither unlimited request rates nor uninterrupted availability.
On this page
Request a dated debt record#
Treasury documents the request structure, access requirements and response format in its official API documentation: https://fiscaldata.treasury.gov/api-documentation/. This is the source for the API behavior described here; individual dataset definitions still need checking before interpreting figures.
The base URL is https://api.fiscaldata.treasury.gov/services/api/fiscal_service, followed by an endpoint and optional parameters. This example requests two fields, sorts by descending record date and asks for one row:
import urllib.request, json
BASE = "https://api.fiscaldata.treasury.gov/services/api/fiscal_service"
def get(endpoint, params):
q = "&".join(f"{k}={v}" for k, v in params.items())
req = urllib.request.Request(f"{BASE}{endpoint}?{q}",
headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=25) as r:
return json.load(r)
debt = get("/v2/accounting/od/debt_to_penny", {
"fields": "record_date,tot_pub_debt_out_amt",
"sort": "-record_date",
"page[size]": "1",
})
row = debt["data"][0]
print(f"As of {row['record_date']}: "
f"${float(row['tot_pub_debt_out_amt'])/1e12:.2f} trillion")
Illustrative output, not a verified observation: As of 2026-07-06: $39.39 trillion. The script reads tot_pub_debt_out_amt, converts it to a floating-point number and displays trillions rounded to two decimal places. That display is not a penny-precision representation, despite the dataset’s name.
The record date carries as much analytical weight as the dollar figure. Requesting the latest row returns only the newest entry in the dataset, which may lag behind the current calendar date. Furthermore, this minimal snippet assumes a populated payload and valid numeric text without guarding against empty responses or network errors.
Filter interest-rate records without implying freshness#
The API accepts fields, filter, sort and pagination parameters. This query selects a fixed date and prints up to five returned rows. It does not discover the most recent reporting period:
rates = get("/v2/accounting/od/avg_interest_rates", {
"fields": "record_date,security_desc,avg_interest_rate_amt",
"filter": "record_date:eq:2026-06-30",
"sort": "-avg_interest_rate_amt",
})
for r in rates["data"][:5]:
print(f"{r['security_desc']:35} {r['avg_interest_rate_amt']}%")
Illustrative figures, not verified Treasury observations or a character-for-character transcript of this script:
Domestic Series 7.577%
United States Savings Inflation... 4.418%
Treasury Bills 3.706%
Treasury Floating Rate Notes (FRN) 3.512%
Treasury Bonds 3.430%
General API documentation confirms endpoint syntax, not the accounting methodology behind individual series. Never assume the reported Treasury Bills rate reflects a specific weighting formula or live secondary-market trading. Review the dataset's specific documentation before estimating debt-service costs or comparing yields across security classes.
The filter syntax is field:operator:value. Supported operators include eq, gt, gte, lt, lte and in. Put multiple conditions in one comma-separated filter rather than repeating the parameter.
Choose the dataset before interpreting its numbers#
These datasets address different questions; sharing an API does not make their definitions or reporting periods interchangeable:
- Debt to the Penny (
/v2/accounting/od/debt_to_penny) is the debt endpoint used above. Consult its dataset documentation for field definitions and publication timing. - Average Interest Rates (
/v2/accounting/od/avg_interest_rates) is the endpoint used in the fixed-date example. Verify the period and calculation method before drawing comparisons. - Treasury Reporting Rates of Exchange (
/v1/accounting/od/rates_of_exchange) appears in Treasury’s documentation examples. Those examples do not establish universal currency coverage or suitability for every accounting requirement. - Monthly Treasury Statement includes multiple tables and endpoints covering federal spending, revenue, debt and related information. Select the table that matches the question.
Treasury advises consulting each dataset's data dictionary, metadata, and notes and known limitations tabs. That documentation provides essential interpretive rules rather than optional reading. Notably, omitting available columns in a field list can trigger automatic row aggregation and numeric summing on certain endpoints, altering the underlying calculation alongside payload size.
Read pagination and numeric values deliberately#
The pagination parameters are page[size] and page[number]. Treasury documents defaults of 100 rows and page 1. Its response examples show encoded brackets, such as page%5Bsize%5D. Do not assume a single response contains an entire historical series.
The helper above joins query strings directly; it is not a general-purpose URL encoder. When adapting requests for requests, another client or curl, check that client’s parameter handling rather than assuming the same literal URL will work everywhere.
An additional first-party source is this fetched Treasury auction response: https://api.fiscaldata.treasury.gov/services/api/fiscal_service/v1/accounting/od/auctions_query?fields=auction_date,high_yield&filter=inflation_index_security:eq:Yes,original_security_term:eq:10-Year,auction_date:gte:2008-10-08,auction_date:lte:2026-09-17,high_yield:gte:2.653. It contains data, metadata and pagination links, with numeric yields represented as strings. It supports the response-format discussion—not the debt amount or interest-rate sample above.
According to Treasury documentation, JSON responses enclose every field value as a string—even nulls, which arrive as the literal text "null" rather than a native JSON null. Parse and validate strings explicitly before casting types, and inspect response metadata and pagination links to confirm dataset completeness.
Understand what the daily cache does not guarantee#
A cache can avoid repeating the same request on every dashboard load. This example reuses a stored value when its fetch date matches the local calendar date:
import json, os, datetime
CACHE = "/tmp/treasury_debt.json"
def cached_debt():
today = datetime.date.today().isoformat()
if os.path.exists(CACHE):
data = json.load(open(CACHE))
if data.get("fetched") == today:
return data["value"]
row = get("/v2/accounting/od/debt_to_penny", {
"fields": "tot_pub_debt_out_amt",
"sort": "-record_date",
"page[size]": "1",
})["data"][0]
value = float(row["tot_pub_debt_out_amt"])
json.dump({"fetched": today, "value": value}, open(CACHE, "w"))
return value
Treat this snippet as a minimal caching sketch rather than a production data collector. It evaluates staleness passively upon invocation without scheduling background updates. Because it records the local fetch date while discarding the Treasury record date, it will miss intraday dataset updates published after the initial read.
The code also omits safeguards against corrupted JSON files, concurrent write races and HTTP timeouts. Moreover, requesting only the debt amount column requires checking the endpoint against Treasury's automatic-aggregation behavior. Production code must retain the source record date, handle network exceptions, write files atomically and verify field-selection behavior.
Keep fiscal and company-data workflows distinct#
Related reading includes the SEC EDGAR XBRL API guide for company-financial-data workflows and the EDGAR full-text search guide for filing searches. The algorithmic trading engineering guide addresses a separate engineering context; retrieving Treasury data alone does not establish a trading signal.
Anchor every query to an explicit record date, inspect the full JSON payload and read the dataset's field definitions. Display the Treasury reporting date alongside every published metric so consumers do not mistake a successful HTTP response for real-time or self-explanatory financial data.