Skip to content

Instantly share code, notes, and snippets.

@rruntsch
Last active March 3, 2022 16:51
Show Gist options
  • Save rruntsch/1f64574729015cc6eabdcdf08fe8e078 to your computer and use it in GitHub Desktop.
Save rruntsch/1f64574729015cc6eabdcdf08fe8e078 to your computer and use it in GitHub Desktop.
Python c_analytics_usa_gov_api class and controller program to download reports from analytics.usa.gov
import requests
import json
class c_analytics_usa_gov_api:
"""
File name: c_analytics_usa_gov_api.py
Class name: c_analytics_usa_gov
Author: Randy Runtsch
Date: March 23, 2021
Description: Call the analytics.usa.gov API with a query and handle the results.
"""
def __init__(self, report, json_file_nm):
# Open the output JSON file, get the report from api.gsa.gov, and close the output file.
# IMPORTANT: Visit https://open.gsa.gov/api/dap/ to request a personal API key and insert it between the quotes:
self.API_KEY = "INSERT_YOUR_PERSONAL_API_KEY_HERE"
json_file = open(json_file_nm, 'w', encoding='utf-8')
self.get_report(report, json_file)
json_file.close()
def get_report(self, report, json_file):
# Call the API to get the report. Write it to a JSON file.
response = requests.get('https://api.gsa.gov/analytics/dap/v1.1/reports/' + report + '/data?api_key=' + self.API_KEY)
if response.status_code != 200:
# Something went wrong.
raise ApiError('GET /tasks/ {}'.format(resp.status_code))
json.dump(response.json(), json_file, indent = 6)
"""
File name: call_analytics_usa_gov_api.py
Author: Randy Runtsch
Date: March 23, 2021
Description: Controller for calls to obtain report from the c_analytics_usa_gov_api class.
"""
from c_analytics_usa_gov_api import c_analytics_usa_gov_api
# Call c_analytics_usa_gov_api with the name of the report to retrieve and the name of the
# JSON file to store it in.
print("Program started.")
c_analytics_usa_gov_api('os-browser', 'D:\project_data/analytics_usa_gov/os_browser_report.json')
print("Program completed")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment