1

I have a curl request that works:

curl "https://api.propublica.org/campaign-finance/v1/2016/candidates/search.json?query=Wilson" 
-H "X-API-Key: PROPUBLICA_API_KEY"

How can I translate this into Python? I tried the following:

payload = {'X-API-Key': 'myapikey'}
r = requests.get("https://api.propublica.org/campaign-finance/v1/2016/candidates/search.json?query=Wilson", params = payload)

Then, I got:

>>> print(r.url)
https://api.propublica.org/campaign-finance/v1/2016/candidates/search.json?query=Wilson&X-API-Key=myapikey
>>> r.text
u'{"message": "Forbidden"}'
book
  • 253
  • 1
  • 2
  • 10
  • 3
    Params are get params, you want headers: `r = requests.get(url, headers={'X-API-Key': 'myapikey'})` – solarc Feb 16 '16 at 22:31
  • This worked, thanks! – book Feb 17 '16 at 00:19
  • Remark to the folks who marked this as duplicate: It is not duplicate! The OP does not ask how to send headers (as in the other question) but has an issue that can be solved by sending headers. – flaschbier Feb 17 '16 at 13:47

2 Answers2

2

The simplest way to translate your curl work to python will be to use pycurl instead of requests.

Your Forbidden issue, however, does not depend on using requests or pycurl. It comes from sending the X-API-Key as query parameters instead of sending it as header (as you did in the curl call).

flaschbier
  • 3,910
  • 2
  • 24
  • 36
-1

Try this out:

import urllib2
url = your_url
payload = {'X-API-Key': 'myapikey'}
req = Request(url, payload, {'Content-Type': 'application/json'})
open = urlopen(req)

after this you can use whatever way you want to print. Hope this works for you.

Jay T.
  • 307
  • 1
  • 6