Wrapping Third Party APIs
In our Swift Talk backend, we call out to a number of third-party APIs: CircleCI, Github, Mailchimp, Recurly, Sendgrid, and Vimeo. You can see the code here.
We wrote each of these interfaces using our tiny networking library. While some of the third-party services have iOS libraries available, they are often quite complicated, or iOS-only — they have dependencies themselves, are written in Objective-C, or just have old-fashioned APIs. Over time, we would need to make sure that these dependencies keep working.
Instead of using a library, we decided to keep our dependencies to an absolute minimum. In the case of Vimeo, we only needed access to a single endpoint. We decided to create a single RemoteEndpoint
that directly calls the HTTP API. By using Codable
, we can parse results in a type-safe manner without having to write lots of code. The entire method is 13 lines:
func downloadURL(for videoId: Int) -> RemoteEndpoint<URL?> {
struct Video: Codable {
var download: [Download]
}
struct Download: Codable {
var width: Int
var height: Int
var link: URL
}
return RemoteEndpoint<Video>(json: .get, url: base.appendingPathComponent("videos/\(videoId)"), headers: headers).map { video in
video.download.first { $0.width == 1920 }?.link
}
}
For the other third-party services we wrote similar wrappers, adding methods as we needed them. This meant we only had to look at the HTTP API documentation, and don't have to worry about taking on another code dependency (or worse: forking a library to make it work outside of iOS).
For us, this strategy worked really well, and we're very glad we made this decision.
We show how our tiny networking library uses Codable
in Swift Talk 133 (a public episode).
To learn more about our Swift Talk backend, watch the first episode of our introduction series, or check out the source code on GitHub.
Thanks again to our subscribers! 😊
If you'd like to support us, you can subscribe too.