Requests: Pretty print http response headers

I am using the requests library to interact with an API.

If I need to pretty print the response body it is pretty straightforward. I just use the json library, no mystery there. But when it comes to the response headers that are returned as a dict. I am having a hard time to pretty print anything in the terminal. I would like to see the dict nicely formatted instead of the word salad that now meet my eyes.

I understand that the Rich library is just the tool for the job, but still I have no success.

A bit of context first: I am on a Windows machine and use the integrated terminal in Vs code.


import requests
import json
import pprint
import rich


# get response from API
res = requests.get("")

# output to terminal

This is what I see in my terminal, a long mess of non formatted output :

I got the idea to use Rich in this SO thread and I have tried pretty much everything else they suggest in the thread with no success. I would really appreciate any help. It may seem trivial but I will be using the requests library for a lot of testing and analysis of http responses, and a pretty output goes a long way in making that work a pleasant experience.

requests.get returns a custom class called CaseInsensitiveDict, which Rich cannot parse, at least not by default. You can pretty-print it if you first map it back to a dict: rich.pretty.pprint(dict(res.headers))

The contents of ["Report-To"] and ["NEL"] are JSON strings, so they won’t be pretty-printed unless you first convert them with json.loads.

1 Like

That did the trick. Thanks a lot @bvanb !

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.