pythonauthenticationcurlaccess-token

Python request with authentication (access_token)


I am trying to use an API query in Python. From the command line I can use curl like so:

curl --header "Authorization:access_token myToken" https://website.example/id

This gives some JSON output. myToken is a hexadecimal variable that remains constant throughout.

I would like to make this call from python so that I can loop through different ids and analyze the output. Before authentication was needed I had done that with urllib2. I have also taken a look at the requests module but couldn't figure out how to authenticate with it.


Solution

  • The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):

    >>> import requests
    >>> response = requests.get(
    ... 'https://website.example/id', headers={'Authorization': 'access_token myToken'})
    

    If you don't want to use an external dependency, the same thing using urllib2 of the Python 2 standard library looks like this (source: official docs):

    >>> import urllib2
    >>> response = urllib2.urlopen(
    ... urllib2.Request('https://website.example/id', headers={'Authorization': 'access_token myToken'})
    

    For Python 3, simply use urllib instead of urllib2