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.

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:

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:

1

2

3

curl-gX GEThttp://localhost:8080/Spring4WithSwagger/rest/users|\

json_pp|\

pygmentize-ljson

Or simply store the custom function in your profile:

1

2

3

4

5

functionjcurl(){

curl"$@"|json_pp|pygmentize-ljson

}

export jcurl

Running this command produces following output:

The previous command applies to JSON, but the similar works with XML as well:

1

2

3

curl-gX GEThttp://localhost:8080/Spring4WithSwagger/rest/products|\

xml_pp|\

pygmentize-lxml

And the custom function as follows:

1

2

3

4

5

functionxcurl(){

curl"$@"|xml_pp|pygmentize-lxml

}

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:

If you enjoyed this post, then make sure you subscribe to my Newsletter and/or Feed