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:

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:

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