How to debug REST/JSON services

I recently had to write a webservice in PHP that were to be used by iPhone/Android apps to post data and images to. With standard HTTP POSTS I’ve usually just created a quick dummy html to post data to the server to test, but this time I had to do some research on how to quickly test the services while developing… Just writing it down here so I don’t forget :-)

cURL to the rescue

So, let’s say I have a service that requires a session_id, title and comment_text. This can be called from the command line with cURL like this:

curl -X POST -d '{"session_id":"2399024390","title":"This is my title","comment_text":"Some text"}'

You’ll get the response on the command line right there so it makes it quick to debug stuff while developing.

What about posting files?

I had a challenge where one of the services were to accept a base64_encoded image in the JSON post, so the simple curl example above wouldn’t suffice. My friend Frode had the idea of using PHP on the command line to save the JSON request array to a file and then posting that request using cURL afterwards. That did the trick!

So, to create the JSON array to POST to the server I ran this PHP code:

php -r 'file_put_contents("json.txt", json_encode(array("session_id" => "3d6e4871170d4c1c2d91a18264904587b2c8ee0d","image_caption" => "This is an image","sender_email" => "[email protected]","sender" => "My nick", "image_base64" => base64_encode(file_get_contents("gmail.png")))));'

Notice the “image_base64” key in the JSON array there. The server expects to receive a base64 encoded binary image (this is how I got it from the apps that were interacting with the webservice). So that code would read gmail.png which was located in the same folder, base64 encode it and add it to the JSON array.

With a complete JSON array all that remained was the actual POST:

curl -X POST -d @json.txt

And the server returned {status:ok} and all was well!

There are probably better ways and some awesome tools for doing this out there so please hit me with those in the comments ;-)


Comment by Mike V. on 2012-03-27 02:48:31 +0000

I agree with cURL. But why go through all of the pain to install PHP when there are easier ways. If you use Firefox, just install the “Poster” extension. It also supports all of the HTTP verbs, not just POST.

Comment by Bjørn Børresen on 2012-03-27 11:25:39 +0000

Cool, haven’t seen that one – will try it out. Wouldn’t be able to test file upload with that one(?), but it’s nice for testing most services I guess.

Comment by Martin Bean on 2012-03-27 21:37:58 +0000

I just use a standalone HTTP REST Client. Does the job without having to mess about on the command line.

Comment by Wessley McInroy on 2012-03-28 09:16:18 +0000

You might also want to check out httpie which looks like an awesome easy way to curl api’s!

Found it here: