154

I have a request URI and a token. If I use:

curl -s "<MY_URI>" -H "Authorization: TOK:<MY_TOKEN>"

etc., I get a 200 and view the corresponding JSON data. So, I installed requests and when I attempt to access this resource I get a 403 probably because I do not know the correct syntax to pass that token. Can anyone help me figure it out? This is what I have:

import sys,socket
import requests

r = requests.get('<MY_URI>','<MY_TOKEN>')
r. status_code

I already tried:

r = requests.get('<MY_URI>',auth=('<MY_TOKEN>'))
r = requests.get('<MY_URI>',auth=('TOK','<MY_TOKEN>'))
r = requests.get('<MY_URI>',headers=('Authorization: TOK:<MY_TOKEN>'))

But none of these work.

9 Answers9

156

In python:

('<MY_TOKEN>')

is equivalent to

'<MY_TOKEN>'

And requests interprets

('TOK', '<MY_TOKEN>')

As you wanting requests to use Basic Authentication and craft an authorization header like so:

'VE9LOjxNWV9UT0tFTj4K'

Which is the base64 representation of 'TOK:<MY_TOKEN>'

To pass your own header you pass in a dictionary like so:

r = requests.get('<MY_URI>', headers={'Authorization': 'TOK:<MY_TOKEN>'})
Ian Stapleton Cordasco
  • 26,944
  • 4
  • 67
  • 72
  • Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 55, in get return request('get', url, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/api.py", line 44, in request return session.request(method=method, url=url, **kwargs) File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/requests/sessions.py", line 323, in request prep = self.prepare_request(req) –  Sep 29 '13 at 00:16
  • @rebHelium can you [gist](https://gist.github.com) that? That is not the whole stack trace and there's no indication of what you actually tried. – Ian Stapleton Cordasco Sep 29 '13 at 00:25
  • Sorry, Stack Overflow did not allow me to post the whole output. I did exactly as you suggested: r = requests.get('whatever url i have', headers={'Authorization': 'TOK:whatever token i have'}) –  Sep 29 '13 at 02:19
  • No need to apologize. Did it work? You accepted my answer but it seems to have caused an exception for you. If you create a [gist](https://gist.github.com) I can help you with greater ease than having a conversation here. – Ian Stapleton Cordasco Sep 29 '13 at 13:55
  • Sigma, I actually missed one small detail on your code that caused the error. The actual code is confidential so I cannot gist. But I will post additional questions since I want to improve my Python skills, if you want to look. They are very simple questions I am sure you would know. –  Oct 03 '13 at 02:50
  • Thanks. Here's the link: http://stackoverflow.com/questions/19150208/python-search-regex-from-variable-inside-a-list I haven't been able to use regex and get what I need. I will re-edit the question. –  Oct 04 '13 at 05:19
  • I was able to get it to work using: > r = requests.get('', headers={'Authorization': 'MY_TOKEN_HERE'}) – se_brandon Sep 21 '16 at 15:20
  • 1
    This works! Make sure the spelling of Authorization is right. I used it as Authorisation and the request failed. – SeaWarrior404 May 06 '19 at 12:38
62

I was looking for something similar and came across this. It looks like in the first option you mentioned

r = requests.get('<MY_URI>', auth=('<MY_TOKEN>'))

"auth" takes two parameters: username and password, so the actual statement should be

r=requests.get('<MY_URI>', auth=('<YOUR_USERNAME>', '<YOUR_PASSWORD>'))

In my case, there was no password, so I left the second parameter in auth field empty as shown below:

r=requests.get('<MY_URI', auth=('MY_USERNAME', ''))

Hope this helps somebody :)

Epoc
  • 7,208
  • 8
  • 62
  • 66
BajajG
  • 2,134
  • 2
  • 25
  • 32
  • 7
    if you try `r = requests.get('',auth=(''))`, you will get `TypeError: 'str' object is not callable`. that stumped me for a while until i came across this :/ – aydow Aug 24 '17 at 00:23
  • Your anserd helped me but only after readin the link you provide which you came accros. Working with the HTTPBasicAuth import from requests.auth makes it very easy! – Wallem89 Dec 14 '19 at 22:22
53

This worked for me:

access_token = #yourAccessTokenHere#

result = requests.post(url,
      headers={'Content-Type':'application/json',
               'Authorization': 'Bearer {}'.format(access_token)})
Jan Trienes
  • 2,501
  • 1
  • 16
  • 28
Lone Ronin
  • 2,530
  • 1
  • 19
  • 31
28

You can also set headers for the entire session:

TOKEN = 'abcd0123'
HEADERS = {'Authorization': 'token {}'.format(TOKEN)}

with requests.Session() as s:

    s.headers.update(HEADERS)
    resp = s.get('http://example.com/')
Anton Tarasenko
  • 8,099
  • 11
  • 66
  • 91
9

I found it here, it's working for me with Linkedin: https://auth0.com/docs/flows/guides/auth-code/call-api-auth-code The code I used with Linkedin login is:

ref = 'https://api.linkedin.com/v2/me'
headers = {"content-type": "application/json; charset=UTF-8",'Authorization':'Bearer {}'.format(access_token)}
Linkedin_user_info = requests.get(ref1, headers=headers).json()
carkod
  • 1,844
  • 19
  • 32
Tri Tran
  • 131
  • 1
  • 4
6

You can try something like this

r = requests.get(ENDPOINT, params=params, headers={'Authorization': 'Basic %s' %  API_KEY})
swatisinghi
  • 667
  • 7
  • 9
5

Requests natively supports basic auth only with user-pass params, not with tokens.

You could, if you wanted, add the following class to have requests support token based basic authentication:

import requests
from base64 import b64encode

class BasicAuthToken(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        authstr = 'Basic ' + b64encode(('token:' + self.token).encode('utf-8')).decode('utf-8')
        r.headers['Authorization'] = authstr
        return r

Then, to use it run the following request :

r = requests.get(url, auth=BasicAuthToken(api_token))

An alternative would be to formulate a custom header instead, just as was suggested by other users here.

Amit Blum
  • 51
  • 1
  • 2
3

This worked for me:

r = requests.get('http://127.0.0.1:8000/api/ray/musics/', headers={'Authorization': 'Token 22ec0cc4207ebead1f51dea06ff149342082b190'})

My code uses user generated token.

Io-oI
  • 2,514
  • 3
  • 22
  • 29
2

You have a request needing an authorization maybe you have a result 401.

Suppose your request is like this :

REQ ='https://api.asite.com/something/else/else'

You have your token :

TOKEN = 'fliuzabuvdgfnsuczkncsq12454632'

build your header like this :

HEADER = {'Authorization': f'{TOKEN}'}

and use it like this :

req.get(REQ, headers=HEADER)

display your result like this :

req.get(COACH, headers=HEADER).json()
Nicoolasens
  • 2,871
  • 17
  • 22