robrem / opensecrets-crpapi

Python client for the Center for Responsive Politics API at OpenSecrets.org.
MIT License
40 stars 3 forks source link

JSONDecodeError #3

Open scanf13ld opened 4 years ago

scanf13ld commented 4 years ago

Hello! I am getting this error when trying to use this method. It was working before back in early 2019, but for some reason it isn't working anymore. I recently regenerated an API key for my account and have access to the basic API functions.

---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-68-0abce5d0bc4f> in <module>()
----> 1 cand = crp.candidates.get('N00007360') #N00007360 corresponds to Nancy Pelosi's crp_id - a unique ID provided by the API
      2 cand['@attributes']['firstlast']

4 frames
/usr/local/lib/python3.6/dist-packages/crpapi.py in get(self, id_code)
     67             state code, or a four character district code.
     68         """
---> 69         return self.fetch('getLegislators', id=id_code)['legislator']
     70 
     71     def pfd(self, cid, year=None):

/usr/local/lib/python3.6/dist-packages/crpapi.py in fetch(self, method, **kwargs)
     48 
     49         resp, content = self.http.request(url, headers=headers)
---> 50         content = json.loads(content)
     51 
     52         if not resp.get('status') == '200':

/usr/lib/python3.6/json/__init__.py in loads(s, encoding, cls, object_hook, parse_float, parse_int, parse_constant, object_pairs_hook, **kw)
    352             parse_int is None and parse_float is None and
    353             parse_constant is None and object_pairs_hook is None and not kw):
--> 354         return _default_decoder.decode(s)
    355     if cls is None:
    356         cls = JSONDecoder

/usr/lib/python3.6/json/decoder.py in decode(self, s, _w)
    337 
    338         """
--> 339         obj, end = self.raw_decode(s, idx=_w(s, 0).end())
    340         end = _w(s, end).end()
    341         if end != len(s):

/usr/lib/python3.6/json/decoder.py in raw_decode(self, s, idx)
    355             obj, end = self.scan_once(s, idx)
    356         except StopIteration as err:
--> 357             raise JSONDecodeError("Expecting value", s, err.value) from None
    358         return obj, end

JSONDecodeError: Expecting value: line 1 column 1 (char 0)
grumble1965 commented 3 years ago

I've got a similar issue. When I request data that doesn't exist (like, a candidate's industry contributions from an industry they haven't got any contributions from), I also get a JSON decode error.

I think the issue is the fetch() method trying to decode the http response before checking the http response status. There's no JSON to decode if the response isn't 200.

Here's my fix: Untitled