Posts in "iphone" tag

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"}' http://example.com/api/method

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" => "blabla@gmail.com","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 http://example.com/gallery/api/image/post

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 ;-)