I wrote a tool to parse an OpenAPI spec from Swift data models

This is another outcome of my journey to make my SwiftUI app, Passepartout, multiplatform. I'll write more about the whole process in my blog, but I want to add a few lines about why I made this little repo in the first place. People attempting cross-platform Swift apps might find the story interesting, and the tool useful.

As I went for a native frontend + C ABI + Swift backend architecture, I needed a way for the non-Swift frontends to exchange data with the Swift backend across the @_cdecl ABI boundary. swift-protobuf was enticing after the move to FoundationEssentials, but I eventually chose JSON for simplicity, as my Swift model was already Codable.

At this point, I needed to express my Swift data models in Kotlin and C++, but I didn't want to spoil my Swift code, which is both production code and involved in serialized user data. Neither did I want to maintain 3 codebases manually in sync. So, I've used SwiftSyntax to parse an intermediate representation (IR) from (a subset of) Swift. I could then use the IR to emit a language-agnostic spec to express my domain in.

After some experimentation, I realized that OpenAPI offered the best environment for the matter, despite being focused on REST services. In fact, openapi-generator can autogenerate JSON-codable models from the YAML spec without any HTTP, also for dozens of modern programming languages. Therefore, it seemed convenient for my tool to generate an OpenAPI YAML from the logical IR.

With this strategy:

  • I could keep Swift as the single source of truth (provided that the Codable entities are very essential).
  • CI uses codegen to keep the OpenAPI representation in sync.
  • I autogenerate the Kotlin and C++ data models for the Android, Linux, and Windows frontends with openapi-generator.
  • No changes will be required to support a new frontend language.

I hope you will find this useful.

1 Like