-1

I am calling my REST services with the following command using curl

export TOKEN= '<random>'
curl -X "GET" -H "Content-Type:application/json" -H "Authorization:Bearer ${TOKEN}" http://my-server.com

I am trying to map the same code using requests library of Python

import requests

url = 'https://httpbin.org/bearer'
headers = {'Authorization': 'Bearer', 'Content-Type':'application/json'}

r = requests.get(url, headers=headers)
print(r.status_code)

My question is, how can I set my TOKEN value in the code?

Mark Estrada
  • 9,013
  • 37
  • 119
  • 186
  • Python has string interpolation just like your shell does. `f'Bearer {token}"` for example, puts the value of the variable `token` into the string value for the header `Authorization`. – Martijn Pieters Jul 17 '19 at 14:29
  • Or just use concatenation, so `'Bearer ' + token`. None of this is specific to Python requests, this is *just* string manipulation. – Martijn Pieters Jul 17 '19 at 14:30
  • Are you (at least in part) asking how to get the value of token from the TOKEN environment variable in Python? – Scott Hunter Jul 17 '19 at 14:31
  • Oh so using just 'Authorization': 'Bearer' + would do the trick? – Mark Estrada Jul 17 '19 at 14:32
  • Yeah..thanks it worked. I was trying out {'Authorization': 'Bearer='}. Sorry for this dumb question. My thinking was totally lost.. – Mark Estrada Jul 17 '19 at 14:40
  • Possible duplicate of [Python requests library how to pass Authorization header with single token](https://stackoverflow.com/questions/19069701/python-requests-library-how-to-pass-authorization-header-with-single-token) – Prayson W. Daniel Jul 17 '19 at 14:49

2 Answers2

2

The authorization token can be added in a dict form to the headers argument as shown below:

hed = {'Authorization': 'Bearer ' + auth_token,
       'Content-Type': 'application/json'}
r = requests.post(url=url, headers=hed)

I suggest reading up on this https://2.python-requests.org/en/master/user/quickstart/

1

Just replace your current line for this one

headers = {'Authorization': 'Bearer ' + token, 'Content-Type':'application/json'}

Depends now where you get the token from, but to include the token that's the way.

Roman
  • 146
  • 5