Skip to content

Instantly share code, notes, and snippets.

@rruntsch
Created April 23, 2022 11:38
Show Gist options
  • Save rruntsch/71a1a5d0dc625d77406393fb7cafb075 to your computer and use it in GitHub Desktop.
Save rruntsch/71a1a5d0dc625d77406393fb7cafb075 to your computer and use it in GitHub Desktop.
Python class to retrieve US federal government debt data, by date, for th specified date range. The class writes the retrieved JSON data structur to the specified file.
#
# Name: c_us_debt.py
# Date: April 22, 2022
# Author: Randy Runtsch
#
# Description:
#
# Obtain all US debt records, for the specified date range,
# as JSON structures, from the Treasury Direct Debt Informatin API.
# Write each record to the specified output folder and file.
#
import requests
import json
import csv
class c_us_debt:
def __init__(self, out_file_nm, start_dt, end_dt):
# Set the base URL.
self.base_url = 'https://www.treasurydirect.gov/NP_WS/debt/search'
# Set the parameter variables for the API request.
self.out_file_nm = out_file_nm
self.start_dt = start_dt
self.end_dt = end_dt
# Get data in JSON format and then write it to a CSV file.
self.get_data()
def get_data(self):
# Build the full URL. Then, request the data through the Debt Information API.
# Write the returned JSON structure to the specified folder and file.
# Create full URL and retrieve data structure in JSON format by calling API with get() function.
full_url = self.base_url + '?startdate=' + self.start_dt + '&enddate=' + self.end_dt + '&format=json'
json_structure = requests.get(full_url)
# Write JSON data structure to file.
with open(self.out_file_nm, "w") as out_file:
out_file.write(json_structure.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment