Type-safe API call with Protocol Buffers in Swift

Yusuke Kita
Dec 27, 2016 · 5 min read

What’s Protocol Buffers?

Languages

How it works

message Token { 
string accessToken = 1;
}
// GET - Response
message GetTokenResponse {
Token token = 1;
}
// POST - Request
message PostTokenRequest {
string accessToken = 1;
}
// POST - Response
message PostTokenResponse {
Token token = 1;
}
struct Token: SwiftProtobuf.Message { 
var accessToken: String = ""
init() {}
}
struct GetTokenResponse: SwiftProtobuf.Message {
init() {}
var token: Token {...}
}
struct PostTokenRequest: SwiftProtobuf.Message {
var accessToken: String = ""
init() {}
}
struct PostTokenResponse: SwiftProtobuf.Message {
init() {}
var token: Token {...}
}

Basic Type

Customization

Pros

Type safety

Unified schema of structured data

Faster API call

Versioning

Cons

Human readability of raw data

Stability

Compatibility with plugin’s Swift

Usage in web browser

Summary

References

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade