Developing software in the Real World

POSTing data using KituraNet

I had a need to send a POST request with a JSON body from Swift and as I had KituraNet and SwiftyJSON already around, it proved to reasonably easy.

To send a POST request using KituraNet, I wrote this code:

As you can see, I’ve liberally commented it, so it should be easy to follow. Let’s look at some interesting bits.

SwiftJSON is convenient

SwiftyJSON does all the heavy lifting of converting dictionaries. As KituraNet requires a Data object for the body, we can do this in one line with SwiftyJSON:

(admittedly, this assumes a valid dictionary! In a real app, consider better error checking…)

Similarly, if we get a JSON string back from the server, converting it to a dictionary is as easy as:

(This time, with some checking!)


Making a JSON-based POST request is easy enough with KituraNet and SwiftyJSON. Of course, the reason I chose this approach is that they are baked into OpenWhisk which is where this code is running.

I also refactored this code into the methods postTo() and postJsonTo() as you can see in this gist.

2 thoughts on “POSTing data using KituraNet

  1. Hi,
    Great how-to summary which really helped me as I'm struggling to find consistent documentation on the matter.
    What would be the way to handle Body in either application/x-www-form-urlencoded format or form data ?
    I have a hint, i need to call "BodyParser.readBodyData(with:)" but the overall syntax is still pretty obscure…
    Any pointer would be greatly appreciated ! Thanks

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *