jd_h2003
jd_h2003

Reputation: 304

JSONDecodeError when trying to call REST api in python

I am trying to access the opensecrets.org api to get some information on congress members. I am trying to access all rows in the database for each member of congress, which I have in my ID's, and append them to a dataframe for manipulation.

Here's my code:

new_house_df = pd.DataFrame([])

for row in house_crp_id:
    r = requests.get('http://www.opensecrets.org/api/?method=candSummary&cid=' + row + 
                     '&cycle=2022&apikey=' + my_key)
    data = r.json()
    df_temp = pd.DataFrame.from_dict(data['candSummary'])
    new_house_df = new_house_df.append(df_temp, ignore_index = True, sort = False)

Which is producing this error at data = r.json()

JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Here is a sample output from the api. enter image description here

I'm searching through stackoverflow but not finding anything explaining what the problem is within my code, or if it's a problem with opensecrets api.

Here is the documentation if it helps. https://www.opensecrets.org/open-data/api-documentation

Upvotes: 1

Views: 826

Answers (1)

Corralien
Corralien

Reputation: 120489

Try to fix headers and use output=json:

headers = {'content-type': 'application/json'}
data = requests.get('http://www.opensecrets.org/api/...?...output=json', headers=headers)

Upvotes: 1

Related Questions