Skip to content

Instantly share code, notes, and snippets.

@rruntsch
Created August 16, 2021 18:56
Show Gist options
  • Save rruntsch/51168aa37e5e88aa01f0d8cdbb586e93 to your computer and use it in GitHub Desktop.
Save rruntsch/51168aa37e5e88aa01f0d8cdbb586e93 to your computer and use it in GitHub Desktop.
Python class and calling code to retrieve US Consumer Price Index data from the Bureau of Labor Statistics (BLS) V2.0 Data API.
import requests
import json
class c_bls_data_api:
"""
File name: c_bls_data_api.py
Class name: c_bls_data_api
Author: Randy Runtsch
Date: August 12, 2021
Description: Call BLS Data API with a query and handle the results.
Reference: https://www.bls.gov/developers/api_python.htm
"""
def __init__(self, parameters, json_file_nm):
# Open the output JSON file, get the report from api.bls.gov, and close the output file.
json_file = open(json_file_nm, 'w', encoding='utf-8')
self.get_report(parameters, json_file)
json_file.close()
def get_report(self, parameters, json_file):
# Call the API to get the report. Write it to a JSON file.
headers = {'Content-type': 'application/json'}
response = requests.post('https://api.bls.gov/publicAPI/v2/timeseries/data/', data = parameters, headers = headers)
if response.status_code != 200:
# Something went wrong.
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
json.dump(response.json(), json_file, indent = 6)
import json
from c_bls_data_api import c_bls_data_api
# Call c_bls_data_api.py with a request for CPI data from 2002 through 2021
# and the name of the file to store the returned JSON data structure in.
print("Program started.")
# Set the register, series ID for CPI, start year, end year, and calculations. Note that setting calculations to true
# returns CPI percentages as well as the raw CPI.
parameters = json.dumps({"registrationkey":"PasteYourKeyHere", "seriesid":['CUUR0000SA0'], "startyear":"2002", "endyear":"2021", "calculations":"true"})
# Call the bls data api class with the parameters and the name of the data output file.
c_bls_data_api(parameters, 'D:/project_data/cpi/cpi_data_report.json')
print("Program completed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment