625 Market Street 6th Floor

San Francisco, CA 94105

415.395.9525

Main menu

REST API Models in Swift

There are a lot of APIs out there, a lot of networking layers, a lot of abstractions, I’m going to offer just one way to start building Swift models backed by a RESTful API. Out of personal preference, PromiseKit will be used instead of callbacks and ObjectMapper will be used to convert between JSON and Swift objects.

The basic idea is now you can take JSON and convert it into a User object with let user = User(JSONString: JSONString). And you can convert that user object back to JSON with user.toJSONString().

To take this a step further, the library AlamofireObjectMapper will convert JSON retrieved through the Alamofire networking library to any Mappable type you provide. It allows us to write a method on a User model like this:

If you’re cringing at how everything is hard-coded, I’ll fix that later. But right now, we can already say:

User.me.then{ user -> Void in
// do something with our user
}

The me method could easily be abstracted back to support more URLs, methods, parameters, headers (including auth), and it could even support any Type. For simplicity, I’m going to skip headers and assume no authentication is required with the API. Here’s an example BaseAPIModel protocol: