user16022131
user16022131

Reputation: 38

Using Python with usaspending.gov API to submit an advanced filtered query criteria and access data using pandas

I'm a beginner programmer and I'm using the following python code to access usaspending.gov data. I would like to use their available API instead to avoid having to download a zipped file and then opening it using pandas to perform a data analysis. Would anyone be able to direct me on how to use the website's API to enter advanced query parameters and then access the data with pandas without having to download their zipped file? If you can provide a code snippet with an example of an extracted query with random parameters, I'd appreciate that!

Here's the link to their API advanced query: https://www.usaspending.gov/search And here's the link to their API endpoints: https://api.usaspending.gov/docs/endpoints

Lastly, here's the current code, I'm using:

from selenium import webdriver
import time

driver webdriver.Chrome (r"C:\Users\m\Desktop\chromedriver.exe") driver.get("https://www.usaspending.gov/search/?hash=54611813edefaca2978066b4b4620302")

time.sleep (1)

download driver.find_element_by_xpath("//div[@class='label' ]").click() download driver.find_element_by_xpath("//button[@title='Award']").click()
download driver.find_element_by_xpath("//button[@title='Everything']").click()

Upvotes: 1

Views: 1170

Answers (1)

Corralien
Corralien

Reputation: 120509

A simple case to start:

import pandas as pd
import requests

url = "https://api.usaspending.gov"
endpoint = "/api/v2/financial_balances/agencies"
payload = {"funding_agency_id": 775, "fiscal_year": 2017}

response = requests.get(f"{url}{endpoint}", params=payload)
data = response.json()

df = pd.DataFrame(data["results"])
>>> df
  budget_authority_amount obligated_amount   outlay_amount
0         101176701717.16   82181642249.31  75144058726.11

Upvotes: 2

Related Questions