Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python request with authentication (access_token)

I am trying to get an API query into python. The command line

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

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. Any ideas? Before authentication was needed I have done that with urllib2. I have also taken a look at the requests module but couldn't figure out how to do that.

Many thanks.

like image 595
user1895406 Avatar asked Dec 11 '12 17:12

user1895406


People also ask

How do you send an authentication request in Python?

To achieve this authentication, typically one provides authentication data through Authorization header or a custom header defined by server. Replace “user” and “pass” with your username and password. It will authenticate the request and return a response 200 or else it will return error 403.

How do I authenticate API requests in Python?

There are a few common authentication methods for REST APIs that can be handled with Python Requests. The simplest way is to pass your username and password to the appropriate endpoint as HTTP Basic Auth; this is equivalent to typing your username and password into a website.


2 Answers

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.com/id', headers={'Authorization': 'access_token myToken'}) 

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

>>> import urllib2 >>> response = urllib2.urlopen( ... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'}) 
like image 185
wosc Avatar answered Sep 18 '22 15:09

wosc


I had the same problem when trying to use a token with Github.

The only syntax that has worked for me with Python 3 is:

import requests  myToken = '<token>' myUrl = '<website>' head = {'Authorization': 'token {}'.format(myToken)} response = requests.get(myUrl, headers=head) 
like image 21
bloodrootfc Avatar answered Sep 21 '22 15:09

bloodrootfc