python requests equivalent to curl -H

2.5k views Asked by At

I'm trying to subscribe to an event stream coming from my particle photon. The docs suggest

curl -H "Authorization: Bearer {ACCESS_TOKEN_GOES_HERE}" \
https://api.particle.io/v1/events/motion-detected

I've tried

address3 ='https://api.particle.io/v1/events/motion-detected'
data = {'access_token': access_token}
r3 = requests.get(address3,params=data)

but I get nothing, and I mean nothing, in response

I expect a response like:

event: motion-detected
data: {"data":"intact","ttl":"60","published_at":"2015-06-25T05:08:22.136Z","coreid":"coreid"}

event: motion-detected
data: {"data":"broken","ttl":"60","published_at":"2015-06-25T05:08:23.014Z","coreid":"coreid"}

I just don't understand what curl is doing relative to what requests is doing. Thanks for the help, JR

2

There are 2 answers

0
Konstantin On

Custom headers are passed as a dictionary in headers argument

address3 ='https://api.particle.io/v1/events/motion-detected'
data = {'Authorization': 'Bearer {ACCESS_TOKEN_GOES_HERE}'}
r3 = requests.get(address3, headers=data)

params argument is used to pass URL parameters. Basically your code issues a request to https://api.particle.io/v1/events/motion-detected?access_token=token_goes_here, this can be veriefied by printing url print(r3.url)

0
user2313067 On

As stated in Alik's response, custom headers are passed as a dictionary in the headers argument. In your case, that would be

address3 ='https://api.particle.io/v1/events/motion-detected'
data = {'Authorization': 'Bearer ' + access_token}
r3 = requests.get(address3, headers=data)

Since this is authentication, the cleanest way would be to implement a custom authentication handler that set this header as described in the documentation.