-1

Need some help here. I am trying to send a JWT token with header in my request. When i directly copy paste the token in the request (line 6) its working fine. Where as when i concatenate as string and send (line 3 & 5) it throwing error. But when print the token its having the correct token value.THe error i have pasted below after the code

response = requests.post("some URL")
token = response.text
header_content = "{'Authorization': 'Bearer "+token+"'}"
print(header_content)
response = requests.get(url, headers=header_content)
#response = requests.get(url, headers = {'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1bmlxdWVfbmFtZSI6ImhjbF9yZXBvcnRpbmcuc2VydmljZWFjY291bnRAc2x1LnRlYW1keW5hbWl4LmNvbSIsInRkeF9lbnRpdHkiOiIyIiwidGR4X3BhcnRpdGlvbiI6IjcwIiwiaXNzIjoiVEQiLCJhdWQiOiJodHRwczovL3d3dy50ZWFtZHluYW1peC5jb20vIiwiZXhwIjoxNjIyOTgyNzg5LCJuYmYiOjE2MjI4OTYzODl9.82FuBtybRBk3Ot-whKYEXw2yFeNXBp566MubEA9G-BE'})

the error i am seeing is

Traceback (most recent call last):
File "C:\Users\prasannakumaravel\PycharmProjects\SLU_DailyReport_Automation\Rest_Testing.py", line 24, in <module>
response = requests.get(url, headers=header_content)
File "C:\Users\prasannakumaravel\PycharmProjects\SLU_DailyReport_Automation\venv\lib\site-packages\requests\api.py", line 76, in get
return request('get', url, params=params, **kwargs)
File "C:\Users\prasannakumaravel\PycharmProjects\SLU_DailyReport_Automation\venv\lib\site-packages\requests\api.py", line 61, in request
return session.request(method=method, url=url, **kwargs)
File "C:\Users\prasannakumaravel\PycharmProjects\SLU_DailyReport_Automation\venv\lib\site-packages\requests\sessions.py", line 528, in request
prep = self.prepare_request(req)
File "C:\Users\prasannakumaravel\PycharmProjects\SLU_DailyReport_Automation\venv\lib\site-packages\requests\sessions.py", line 456, in prepare_request
p.prepare(
File "C:\Users\prasannakumaravel\PycharmProjects\SLU_DailyReport_Automation\venv\lib\site-packages\requests\models.py", line 317, in prepare
self.prepare_headers(headers)
File "C:\Users\prasannakumaravel\PycharmProjects\SLU_DailyReport_Automation\venv\lib\site-packages\requests\models.py", line 449, in prepare_headers
for header in headers.items():
AttributeError: 'str' object has no attribute 'items'
1
  • headers= needs to be a dict Commented Jun 5, 2021 at 13:04

3 Answers 3

3

header_content should be a dictionary not string

Change this

header_content = "{'Authorization': 'Bearer "+token+"'}"

to

header_content = {'Authorization': "Bearer "+token}

You can trace that from error Traceback :

for header in headers.items():
AttributeError: 'str' object has no attribute 'items'

.items() is an attribute for a dictionary not string which returns a list of tuple pair :

In your case header.items() is

[('Authorization', 'Bearer your_token')]
Sign up to request clarification or add additional context in comments.

3 Comments

header_content = {'Authorization': 'Bearer "+token+"'} Not working. token variable is not replacing with values not sure how to solve this
i made this happen by below <br/> value = "Bearer "+token header_content = {'Authorization': value} print(header_content) response = requests.get(url, headers=header_content) <br/> This worked
Yup! my bad, i didn't focused on that part, anyway that's a small fix which you yourself have made it. Cheers!
1

the issue here is requests is expecting a dictionary, not a string that resembles a python dictionary. in the 2nd last line of the error messages it shows for header in headers.items(): which is a python dictionary method. to address this problem u can use json module from python.

import json
header_content = '{"Authorization": "Bearer " + "some_token"}'
header_content = dict(json.loads(header_content)
response = requests.get(url, headers = header_content)

Note: for some reason json requires the contents enclosed with " instead of '.

2 Comments

hi thanks for your help. But i am appending the token variable in run time with the Authorization: Bearer Token...Not sure how to append. Your code is throwing error <error> raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not dict </error>
'{"Authorization": "Bearer "' + some_token + '}'
0

I am not quite sure what framework you use, but usually there is a separate function to add headers, instead of just adding them as a string.

According to this answer, in Python with urllib2 it would be:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('Referer', 'http://www.python.org/')
resp = urllib2.urlopen(req)
content = resp.read()

For node.js with express it is explained in this answer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.