Developing software in the Real World

Pretty print curl -i

My favourite tool for working with APIs is curl, though I recognise that lots of people like HTTPie and seem very keen to tell about it every time I mention curl…

With curl, I particularly like using the -i switch to view the status line and headers too without the additional cruft of -v:

This generates an output that looks like this:

What I would like to do is pretty print the body if it’s JSON or XML so that it’s easier to read. There are some tools out there, like jq which will format JSON, but they can’t seem to cope if the first part of the string is not JSON:

Solution 1: Use -D flag

The easiest solution is to use the -D flag to send the headers to stderr:

To make this easier, you can add to your ~/.curlrc. Mine looks like this:

Now you never need to think about it.

Solution 2: A simple script to pipe the output through

Another way to do it is via a script that knows where the body starts. We can write this in PHP and it can automatically pretty print XML for us too:

Save this as as /usr/local/prettyprint, make it executable with chmod a+w /usr/bin/prettyprint and you’re good to go:

Pick the solution that works best for you!

3 thoughts on “Pretty print curl -i

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *