I work with JSON APIs a lot. On a current API I work on, there is an OAuth-esque request signing process that is required to make sure that others cannot forge requests simply by changing parameters arround.

A typical request might look like this:

    HTTP 1.1
    GET /foo/bars.json

    Headers:
        Accept-Encoding = gzip;
        Accept = application/json
        Authorization = "cHOLIOb7bAeqFEmsz3io%2Bxg4sQA%3D";
        Account-Id = 201;
        User-Agent = "...";

The Authorization header is generated by concatenating the HTTP Method, URL, any parameters, and then signed with a key.

Because of this security, it is very difficult to create adhoc requests just to try them out. So instead, we have our iPhone app NSLog the proper curl command for us. Now it’s as simple as copy & paste from the Xcode Console, which gives me a less-than-readable output of the JSON.

Usually for this I just pipe the command into pbcopy to get it on my clipboard, then I visit JSON Lint to make it easy to read.

Doin’ it all from Terminal

I looked at ways of doing this all from the Terminal, and came across this python command:

python -mjson.tool

It takes input from stdin and outputs it formatted nicely. Sweet! Now all that’s needed is to make this a bit more easy to remember, so I made a script to do this for me called format_json and put it in my path.

Now, any time I want to see the JSON output of an API, I can simply type:

    $ curl some.server.com/api/devices.json?key=124512312 -H Authorization:"124151231231123123" | 
        format_json

And here is the output:

    {
      "devices": [
          {
              "device_id": "40f4fc8a5818608dbb9a6c981179222b6f", 
              "device_type": "iPhone", 
              "id": 24, 
              "name": "Ben's iPhone", 
              "push_enabled": true, 
              "push_token": "a3a36......480c25fdf"
          }
      ]
    }

Very handy, indeed.