Formatting and coloring the cURL output
When it comes to documenting the APIs (especially the REST ones), having the cURL samples that one can try out and play around with has become the defacto standard these days. However if you actually want to read through the response body, look up certain piece of information or just simply check the integrity of the response itself, you will run into a big inconvenience that comes with cURL – the format of the response body. Don’t get me wrong, I love cURL as much as the next guy, but the things can be improved upon. And that is the aim of this article.<!– after-
Motivation
Working with well designed and implemented APIs can be a really pleasant and educative experience. GitHub API is an example of such an implementation. Given the size of their responses and the amount of information being served, it helps a great deal that they serve it in a formatted way. However, not all APIs behave in the same way. Lets take the app I developed for some of my older posts, Spring4WithSwagger. The app is serving metadata about the interface using Swagger framework and upon hitting the following URL:
http://localhost:8080/Spring4WithSwagger/rest/users
You get the response looking like this:
{"users":[{"userName":"kyle","firstName":"Kyle","surname":"Broflovski","email":"kyle@jakubstas.com","lastUpdated":"2016-07-10T20:52:57.241+0000"},{"userName":"stan","firstName":"Stanley","surname":"Marsh","email":"stan@jakubstas.com","lastUpdated":"2016-07-10T20:52:57.241+0000"}],"count":2}%
Little bit hard to read, isn’t it? I think we can do better.
Toolset I decided to use
By simple chaining of a few command line tools, we can achieve a simple, nice to read, formatted and colored responses. For this setup, I decided to use the following tools:
xml-twig-tools
json
pygments
How does it work?
To see this setup in action, just install the required software and issue the following command:
curl -gX GET http://localhost:8080/Spring4WithSwagger/rest/users | \ json_pp | \ pygmentize -l json
Or simply store the custom function in your profile:
function jcurl() { curl "$@" | json_pp | pygmentize -l json } export jcurl
Running this command produces following output:
The previous command applies to JSON, but the similar works with XML as well:
curl -gX GET http://localhost:8080/Spring4WithSwagger/rest/products | \ xml_pp | \ pygmentize -l xml
And the custom function as follows:
function xcurl() { curl "$@" | xml_pp | pygmentize -l xml } export xcurl
Running this command produces the following output:
How to use it?
There are two approaches you can choose from make the most out of this setup. Either set it up locally, or use the Docker image I created to save up on the overall setup time. For more details, check out the following links:
Reference: | Formatting and coloring the cURL output from our SCG partner Jakub Stas at the Jakub Stas blog. |