pythonpython-3.xpython-requests

How to send dict in Header as value to key 'Authorization' in python requests?


I have to test the results of the API. I am sending

Key - 'Authorization'
value - { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}

I am getting proper output in postman but my code fails in requests

import requests
from pprint import pprint

def main():
    url = "http://test.example.com/recharger-api/merchant/getPlanList?circleid=1&operatorid=1&categoryid=1"
    headers = {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}}
    response = requests.get(url, headers = headers)
    data = response.json()
    pprint(data)

if __name__ == "__main__":
    main()

The error I get:

requests.exceptions.InvalidHeader: Value for header {'Authorization': { "merchantIp": "13.130.189.149", "merchantHash": "c8b71ea1ab250adfc67f90938750cd30" , "merchantName": "test"}} must be of type str or bytes, not <class 'dict'>

Solution

  • The header is almost certainly expecting JSON data. A Python dictionary, even simply converted to a string, is not the same thing as JSON. The requests library doesn't accept anything other than strings for headers anyway. POSTMan only deals in strings, not Python objects, so you wouldn't see the issue there.

    Explicitly convert it:

    import json
    
    headers = {
        'Authorization': json.dumps({
            "merchantIp": "13.130.189.149",
            "merchantHash": "c8b71ea1ab250adfc67f90938750cd30",
            "merchantName": "test"
        })
    }