Cannot get response headers into JSON format

Viewed 23

I am making a call to a third-party vendor my company works with, I am trying to send a request and receive my session API token. The problem is, the session id value I need is returned through the response headers. I can see it come back but I cannot get it as a JSON to parse through later.

headers = {'Authorization': 'Basic madeUpKey'}

response = requests.get('theThirdPartyURL/api/login', headers=headers, verify=false)

data = response.headers

If I just print data here and don't run the below line I get a string that looks like a JSON with the values I want

data=data.json()

I then get this error: AttributeError: 'CaseInsensitiveDict' object had no attribute 'json'

I have tried everything on StackOverflow and have not had any luck.

I have also tried json.dumps(dict(response.headers))) and a few other suggestions.

1 Answers

The problem is that response.headers is of type:

type(data) == requests.structures.CaseInsensitiveDict

which is not serializable.

Not sure about how you want to save your data to "parse through later", but you could use dict() and save it to a file. This is what works for me:

import json
import requests

response = requests.get('https://www.google.com')

with open("file1.json", "w") as file:
    json.dump(dict(response.headers), file)
Related