1

I have been trying to use python to get data from an API - which I am able to access manually like below

curl --location --compressed --header “Authorization: Bearer [ACCESS_TOKEN]” [STREAM_URL]

How do I go about using it in python - I have read examples it says use requestsbut how to handle the Access_Token part in python

Any help would be appreciated?

Regards VB

Suren Baskaran
  • 1,228
  • 1
  • 10
  • 17

2 Answers2

0

Just define your headers like you do in your curl example. In this case though, it's a dict. Assuming you want to use requests you would do something like this:

import requests

url = [STREAM_URL]
headers = {"Authorization": "Bearer [ACCESS TOKEN]"}
r = requests.get(url, headers=headers)
print(r.text)
M. Adam Kendall
  • 1,202
  • 9
  • 8
0

There's no different what to use. urllib come with the python and if you don't like to download additional package, use urllib.

As OP mentioned --compressed in curl command, we should do the same to get gzipped content:

Edited ars answer:

import sys
if sys.version_info.major == 3:
  import urllib.request as urllib2
else:
  import urllib2

from StringIO import StringIO
import gzip

request = urllib2.Request('http://example.com/')
request.add_header('Accept-encoding', 'gzip')
request.add_header('Authorization', 'Bearer [ACCESS_TOKEN]')
response = urllib2.urlopen(request)
if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO( response.read())
    f = gzip.GzipFile(fileobj=buf)
    data = f.read()

Does python urllib2 automatically uncompress gzip data fetched from webpage?

Community
  • 1
  • 1
Reishin
  • 1,854
  • 18
  • 21
  • I am getting a HTTP Error 406:Not acceptable error---- and I read that we need to append the header to the URL - how do I append my header to the URL ----- "?Authorization:Bearer [Token]" – Suren Baskaran Apr 30 '15 at 22:20
  • try to checkout, what you really need. Headers couldn't be appended to url, but argument params could. You may need something like this: http://example.com/?authorization=xxxxxxxxxxx – Reishin Apr 30 '15 at 22:49