Prettifying JSON for Curl Development

In the same vein as my post from a few weeks ago on developing an API with Curl and Netrc, here’s a handy trick for sending pre-prettified JSON output back to clients, but only those that are identifying as Curl. The reasoning being that prettified JSON isn’t useful most of the time, but it’s a nice touch while using developing or testing against an API with Curl.

Bundle MultiJson in your Gemfile:

gem "multi_json"

Now define a helper for identifying Curl clients, and use it wherever encoding JSON:

# sample Sinatra app

helpers do
  def curl?
    !!(request.user_agent =~ /curl/)
  end
end

get "/articles" do
  articles = Article.all
  [200, MultiJson.encode(articles, pretty: curl?)]
end

Posted on September 2, 2012 from San Francisco

About

My name is Brandur. I'm a polyglot software engineer and part-time designer working at Heroku in San Francisco, California. I'm a Canadian expat. My name is Icelandic. Drop me a line at brandur@mutelight.org.

Aside from technology, I'm interested in energy and how it relates to our society, travel, longboarding, muay thai, symphonic metal, and the guitar.

If you liked this article, consider finding me on Twitter.