Swift OpenAPI Generator
Generate Swift client and server code from an OpenAPI document.
This module is an executable target. It cannot be imported.
Overview
OpenAPI is a specification for documenting HTTP services. An OpenAPI document is written in either YAML or JSON, and can be read by tools to help automate workflows, such as generating the necessary code to send and receive HTTP requests.
Swift OpenAPI Generator is a Swift package plugin that can generate the ceremony code required to make API calls, or implement API servers.
The code is generated at build-time, so it’s always in sync with the OpenAPI document and doesn’t need to be committed to your source repository.
Features
Works with OpenAPI Specification versions 3.0 and 3.1.
Streaming request and response bodies enabling use cases such as JSON event streams, and large payloads without buffering.
Support for JSON, multipart, URL-encoded form, base64, plain text, and raw bytes, represented as value types with type-safe properties.
Client, server, and middleware abstractions, decoupling the generated code from the HTTP client library and web framework.
To see these features in action, see Checking out an example project.
Usage
Swift OpenAPI Generator can be used to generate API clients and server stubs.
Below you can see some example code, or you can follow one of the Working with Swift OpenAPI Generator tutorials.
Using a generated API client
The generated Client
type provides a method for each HTTP operation defined in the OpenAPI document and can be used with any HTTP library that provides an implementation of ClientTransport
.
import OpenAPIURLSession
import Foundation
let client = Client(
serverURL: URL(string: "http://localhost:8080/api")!,
transport: URLSessionTransport()
)
let response = try await client.getGreeting()
print(try response.ok.body.json.message)
Using generated API server stubs
To implement a server, define a type that conforms to the generated APIProtocol
, providing a method for each HTTP operation defined in the OpenAPI document.
The server can be used with any web framework that provides an implementation of ServerTransport
, which allows you to register your API handlers with the HTTP server.
import OpenAPIRuntime
import OpenAPIVapor
import Vapor
struct Handler: APIProtocol {
func getGreeting(_ input: Operations.getGreeting.Input) async throws -> Operations.getGreeting.Output {
let name = input.query.name ?? "Stranger"
return .ok(.init(body: .json(.init(message: "Hello, \(name)!"))))
}
}
@main struct HelloWorldVaporServer {
static func main() async throws {
let app = Vapor.Application()
let transport = VaporTransport(routesBuilder: app)
let handler = Handler()
try handler.registerHandlers(on: transport, serverURL: URL(string: "/api")!)
try await app.execute()
}
}
Package ecosystem
The Swift OpenAPI Generator project is split across multiple repositories to enable extensibility and minimize dependencies in your project.
Repository | Description |
---|---|
apple/swift-openapi-generator | Swift package plugin and CLI |
apple/swift-openapi-runtime | Runtime library used by the generated code |
apple/swift-openapi-urlsession | ClientTransport using URLSession |
swift-server/swift-openapi-async-http-client | ClientTransport using AsyncHTTPClient |
swift-server/swift-openapi-vapor | ServerTransport using Vapor |
swift-server/swift-openapi-hummingbird | ServerTransport using Hummingbird |
swift-server/swift-openapi-lambda | ServerTransport using AWS Lambda |
Requirements and supported features
Generator versions | Supported OpenAPI versions | Minimum Swift version |
---|---|---|
1.0.0 … main | 3.0, 3.1 | 5.9 |
See also Supported OpenAPI features.
Supported platforms and minimum versions
The generator is used during development and is supported on macOS and Linux.
The generated code, runtime library, and transports are supported on more platforms, listed below.
Component | macOS | Linux | iOS | tvOS | watchOS | visionOS |
---|---|---|---|---|---|---|
Generator plugin and CLI | ✅ 10.15+ | ✅ | ✖️ | ✖️ | ✖️ | ✖️ |
Generated code and runtime library | ✅ 10.15+ | ✅ | ✅ 13+ | ✅ 13+ | ✅ 6+ | ✅ 1+ |
Documentation and example projects
To get started, check out the topics below, or one of the Working with Swift OpenAPI Generator tutorials.
You can also experiment with one of the examples in Checking out an example project that use Swift OpenAPI Generator and integrate with other packages in the ecosystem.
Or if you prefer to watch a video, check out Meet Swift OpenAPI Generator from WWDC23.
Example OpenAPI document
openapi: '3.1.0'
info:
title: GreetingService
version: 1.0.0
servers:
- url: https://example.com/api
description: Example service deployment.
paths:
/greet:
get:
operationId: getGreeting
parameters:
- name: name
required: false
in: query
description: The name used in the returned greeting.
schema:
type: string
responses:
'200':
description: A success response with a greeting.
content:
application/json:
schema:
$ref: '#/components/schemas/Greeting'
components:
schemas:
Greeting:
type: object
description: A value with the greeting contents.
properties:
message:
type: string
description: The string representation of the greeting.
required:
- message
Essentials
Checking out an example project
Check out a working example to learn how packages using Swift OpenAPI Generator can be structured and integrated with the ecosystem.
Read MoreGenerating a client in a Swift package
This tutorial guides you through building GreetingServiceClient—an API client for a fictitious service that returns a personalized greeting.
Read MoreGenerating a client in an Xcode project
This tutorial guides you through building GreetingServiceClient—an API client for a fictitious service that returns a personalized greeting.
Read MoreGenerating server stubs in a Swift package
This tutorial guides you through building GreetingService—an API server for a fictitious service that returns a personalized greeting.
Read More
OpenAPI
Exploring an OpenAPI document
This tutorial covers the basics of the OpenAPI specification and guides you through writing an OpenAPI document that describes a service API. We’ll use a fictitious service that returns a personalized greeting.
Read MoreAdding OpenAPI and Swagger UI endpoints
One of the most popular ways to share your OpenAPI document with your users is to host it alongside your API server itself.
Read MorePracticing spec-driven API development
Design, iterate on, and generate both client and server code from your hand-written OpenAPI document.
Read MoreUseful OpenAPI patterns
Explore OpenAPI patterns for common data representations.
Read MoreSupported OpenAPI features
Learn which OpenAPI features are supported by Swift OpenAPI Generator.
Read More
Generator plugin and CLI
Configuring the generator
Create a configuration file to control the behavior of the generator.
Read MoreManually invoking the generator CLI
Manually invoke the command-line tool to generate code as an alternative to the Swift package build plugin.
Read MoreFrequently asked questions
Review some frequently asked questions below.
Read More
API stability
API stability of the generator
Understand the impact of updating the generator package plugin on the generated Swift code.
Read MoreAPI stability of generated code
Understand the impact of changes to the OpenAPI document on generated Swift code.
Read More
Getting involved
Project scope and goals
Learn about what is in and out of scope of Swift OpenAPI Generator.
Read MoreContributing to Swift OpenAPI Generator
Help improve Swift OpenAPI Generator by implementing a missing feature or fixing a bug.
Read MoreProposals
Collaborate on API changes to Swift OpenAPI Generator by writing a proposal.
Read MoreDocumentation for maintainers
Learn about the internals of Swift OpenAPI Generator.
Read More