Blog

Swift Tip: Stable APIs on the Server

In our Swift Talk backend, one of the endpoints we have to support is a JSON API. Other apps, such as our main website and our unreleased tvOS app, expect the JSON to be in a specific format. Importantly, this format shouldn't change over time (except for additive changes), because that would break existing clients.

The easiest way to generate JSON in Swift is by using Codable. In our backend, we have an Episode struct that represents a single episode. However, the struct doesn't quite match the JSON we want to generate: it has some private data that we don't want to expose publicly, and it has fields that are named differently.

Rather than changing our Episode struct to match the JSON API, we took a different approach. In our view file, we created a second episode struct. This struct has exactly the fields we want to expose, in the format the JSON API expects:

								fileprivate struct EpisodeView: Codable {
    var number: Int
    var title: String
    var synopsis: String
    var url: URL
    var small_poster_url: URL
    var media_duration: Int
    var released_at: Date
    var collection: String
    var subscription_only: Bool
}

							

We then created an initializer on EpisodeView that takes an Episode as the input. It can be a bit tedious to copy properties over, but there are some big advantages.

First of all, the EpisodeView struct serves as documentation for our API. We know that this is exactly the format we will get. Secondly, we don't have to customize any JSON generation, but instead rely on Codable to generate JSON. Thirdly, we're now free to change our internal implementation of Episode. If we change the name of a field, or the type, the compiler will make sure that we also change the conversion from Episode into EpisodeView.

On Swift Talk, we have covered a number of topics around server-side Swift programming, which are all in our Server-Side Swift Collection.

If you'd like to support us, you can subscribe, or give a subscription as a gift.


Stay up-to-date with our newsletter or follow us on Twitter .

Back to the Blog

Recent Posts