Post data to a web api in json format from swift

How would you write the code to post data in json format from swift to a web api?

Lets say that you want to post new data to an api and it accepts the parameters firstname and familyname and lets say the url to the api is https://namesapi.example.com/api/names/ ?

Replies

Easiest way is to use a combination of Alamofire and SwiftyJSON if your nested post request contains different types. If not then you can use Apple way which serializes your data into JSON format. It's just a case of posting this data and dealing with the result.


if let json = try? NSJSONSerialization.dataWithJSONObject(array, options: []) { 
 
}

Well, I would never create an API that encodes the concept of “first and family names”; that’s problematic on so many levels. But hopefully that was just an example (-:

btw If you’re curious about the details here, I strongly recommend you read Falsehoods Programmers Believe About Names. It’s an absolute classic! And if you’re looking for similar articles about other topics, type “falsehoods programmers believe about” into the Google search box and follow the auto completes (-:

Anyway, back to your question…

IMO the answer depends on how complex your web service API is, or will get. If the web service API is as simple as you’ve said, I strongly recommend against bringing in complex frameworks to do this work. Rather:

  1. Use JSONSerialization to create JSON data from a dictionary

  2. Post that data using URLSession

However, if you’re talking to a complex web service API, with lots of requests taking lots of parameters, it may be worthwhile bringing in some frameworks to help.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"