repo_name
stringlengths
1
62
dataset
stringclasses
1 value
lang
stringclasses
11 values
pr_id
int64
1
20.1k
owner
stringlengths
2
34
reviewer
stringlengths
2
39
diff_hunk
stringlengths
15
262k
code_review_comment
stringlengths
1
99.6k
swift-openapi-generator
github_2023
others
471
apple
czechboy0
@@ -14,6 +14,71 @@ import OpenAPIKit +/// Validates all content types from an OpenAPI document represented by a ParsedOpenAPIRepresentation. +/// +/// This function iterates through the paths, endpoints, and components of the OpenAPI document, +/// checking and reporting any invalid content types using the provided validation closure. +/// +/// - Parameters: +/// - doc: The OpenAPI document representation. +/// - validate: A closure to validate each content type. +/// - Throws: An error with diagnostic information if any invalid content types are found. +func validateContentTypes(in doc: ParsedOpenAPIRepresentation, validate: (String) -> Bool) throws { + for (path, pathValue) in doc.paths { + guard case .b(let pathItem) = pathValue else { continue } + for endpoint in pathItem.endpoints { + + if let eitherRequest = endpoint.operation.requestBody { + if case .b(let actualRequest) = eitherRequest { + for contentType in actualRequest.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in requestBody at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + } + + for eitherResponse in endpoint.operation.responses.values { + if case .b(let actualResponse) = eitherResponse { + for contentType in actualResponse.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in responses at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + } + } + } + + for component in doc.components.requestBodies.values {
Let's iterate both keys and values, to allow us to print the key later down. ```suggestion for (key, component) in doc.components.requestBodies { ```
swift-openapi-generator
github_2023
others
471
apple
czechboy0
@@ -14,6 +14,71 @@ import OpenAPIKit +/// Validates all content types from an OpenAPI document represented by a ParsedOpenAPIRepresentation. +/// +/// This function iterates through the paths, endpoints, and components of the OpenAPI document, +/// checking and reporting any invalid content types using the provided validation closure. +/// +/// - Parameters: +/// - doc: The OpenAPI document representation. +/// - validate: A closure to validate each content type. +/// - Throws: An error with diagnostic information if any invalid content types are found. +func validateContentTypes(in doc: ParsedOpenAPIRepresentation, validate: (String) -> Bool) throws { + for (path, pathValue) in doc.paths { + guard case .b(let pathItem) = pathValue else { continue } + for endpoint in pathItem.endpoints { + + if let eitherRequest = endpoint.operation.requestBody { + if case .b(let actualRequest) = eitherRequest { + for contentType in actualRequest.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in requestBody at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + } + + for eitherResponse in endpoint.operation.responses.values { + if case .b(let actualResponse) = eitherResponse { + for contentType in actualResponse.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in responses at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + } + } + } + + for component in doc.components.requestBodies.values { + for contentType in component.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in #/components/requestBodies. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + + for component in doc.components.responses.values {
```suggestion for (key, component) in doc.components.responses { ``` Same here. And please include the key in the diagnostic.
swift-openapi-generator
github_2023
others
471
apple
czechboy0
@@ -14,6 +14,71 @@ import OpenAPIKit +/// Validates all content types from an OpenAPI document represented by a ParsedOpenAPIRepresentation. +/// +/// This function iterates through the paths, endpoints, and components of the OpenAPI document, +/// checking and reporting any invalid content types using the provided validation closure. +/// +/// - Parameters: +/// - doc: The OpenAPI document representation. +/// - validate: A closure to validate each content type. +/// - Throws: An error with diagnostic information if any invalid content types are found. +func validateContentTypes(in doc: ParsedOpenAPIRepresentation, validate: (String) -> Bool) throws { + for (path, pathValue) in doc.paths { + guard case .b(let pathItem) = pathValue else { continue } + for endpoint in pathItem.endpoints { + + if let eitherRequest = endpoint.operation.requestBody { + if case .b(let actualRequest) = eitherRequest { + for contentType in actualRequest.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in requestBody at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + } + + for eitherResponse in endpoint.operation.responses.values { + if case .b(let actualResponse) = eitherResponse { + for contentType in actualResponse.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in responses at path '\(path.rawValue)'. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + } + } + } + + for component in doc.components.requestBodies.values { + for contentType in component.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in #/components/requestBodies. Must have 2 components separated by a slash '<type>/<subtype>'.\n" + ) + } + } + } + + for component in doc.components.responses.values { + for contentType in component.content.keys { + if !validate(contentType.rawValue) { + throw Diagnostic.error( + message: + "Invalid content type string: '\(contentType.rawValue)' found in #/components/responses. Must have 2 components separated by a slash '<type>/<subtype>'.\n"
```suggestion message: "Invalid content type string." context: ["contentType": contentType.rawValue, "location": "#/components/responses/\(key.rawValue)", "recoverySuggestion": "Must have 2 components separated by a slash '<type>/<subtype>'."] ``` Please keep the message a static string, so that we can group errors easily, and put the dynamic data into the context dictionary, for example like this. Please do this for the rest of the diagnostics you added.
swift-openapi-generator
github_2023
others
489
apple
czechboy0
@@ -1,21 +1,86 @@ -REPO_URL = https://github.com/apple/swift-openapi-generator -VERSION = 1.0.0 -TMP_DIR = /tmp -REPO_DIR = $(TMP_DIR)/swift-openapi-generator -CLI_EXECUTABLE = $(REPO_DIR)/.build/release/swift-openapi-generator +# To see how to drive this makefile use: +# +# % make help -$(REPO_DIR): - git clone --branch $(VERSION) --depth 1 $(REPO_URL) $(REPO_DIR) +# The following values can be changed here, or passed on the command line. +SWIFT_OPENAPI_GENERATOR_GIT_URL ?= https://github.com/apple/swift-openapi-generator +SWIFT_OPENAPI_GENERATOR_GIT_TAG ?= 1.0.0 +SWIFT_OPENAPI_GENERATOR_CLONE_DIR ?= $(CURRENT_MAKEFILE_DIR)/.swift-openapi-generator +SWIFT_OPENAPI_GENERATOR_BUILD_CONFIGURATION ?= debug
The default was release before, should we retain that?
swift-openapi-generator
github_2023
others
492
apple
czechboy0
@@ -48,6 +48,7 @@ extension TypesFileTranslator { let nestedDecls = try translateSchema(typeName: elementType.typeName, schema: items, overrides: .none) inline.append(contentsOf: nestedDecls) } + if items.nullable { elementType = elementType.asOptional }
Please remove this one, doesn't seem necessary.
swift-openapi-generator
github_2023
others
488
apple
groue
@@ -613,13 +613,16 @@ final class Test_Client: XCTestCase { } func testProbe_undocumented() async throws { - transport = .init { request, requestBody, baseURL, operationID in (.init(status: .serviceUnavailable), nil) } + transport = .init { request, requestBody, baseURL, operationID in (.init(status: .serviceUnavailable), "oh no") + } let response = try await client.probe(.init()) - guard case let .undocumented(statusCode, _) = response else { + guard case let .undocumented(statusCode, payload) = response else { XCTFail("Unexpected response: \(response)") return } XCTAssertEqual(statusCode, 503) + XCTAssertEqual(payload.headerFields, [:]) + try await XCTAssertEqualStringifiedData(payload.body, "oh no")
🀣❀️
swift-openapi-generator
github_2023
others
479
apple
czechboy0
@@ -8,60 +8,171 @@ Generate Swift client and server code from an OpenAPI document. ## Overview -[OpenAPI][openapi] is an open specification for documenting HTTP APIs. +[OpenAPI][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. -## Repository organization +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. -The Swift OpenAPI Generator project is split across multiple repositories to enable extensibility and minimize dependencies in your project. +## 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.
```suggestion - Client, server, and middleware abstractions, decoupling the generated code from the HTTP client library and web framework. ```
swift-openapi-generator
github_2023
others
479
apple
czechboy0
@@ -8,60 +8,171 @@ Generate Swift client and server code from an OpenAPI document. ## Overview -[OpenAPI][openapi] is an open specification for documenting HTTP APIs. +[OpenAPI][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. -## Repository organization +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. -The Swift OpenAPI Generator project is split across multiple repositories to enable extensibility and minimize dependencies in your project. +## 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, check out the list of [example projects][examples-generator]. + +## 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 [step-by-step tutorials][tutorials-generator]. + +### Using a generated API client + +The generated `Client` type provides a method for each HTTP operation defined in the OpenAPI document[^example-openapi-yaml] and can be used with any HTTP library that provides an implementation of `ClientTransport`. + +```swift +import OpenAPIURLSession +import Foundation + +let client = Client( + serverURL: URL(string: "http://localhost:8080/api")!, + transport: URLSessionTransport()
```suggestion serverURL: URL(string: "http://localhost:8080/api")!, transport: URLSessionTransport() ``` Just to make the spaces consistent with the server example below.
swift-openapi-generator
github_2023
others
479
apple
czechboy0
@@ -8,49 +8,90 @@ Generate Swift client and server code from an OpenAPI document. ## Overview -[OpenAPI][openapi] is an open specification for documenting HTTP APIs. An OpenAPI document is written in either YAML or JSON. These machine-readable formats can be read by tools to automate workflows. OpenAPI has an large, existing [ecosystem of tooling][tools]. +[OpenAPI][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. -### Getting started +## Features -> Tip: In a rush? Get started quickly by <doc:Checking-out-an-example-project>. +- 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. -Alternatively, to integrate Swift OpenAPI Generator into your existing project, or to create a new one, follow one of our _getting started_ guides: -- <doc:ClientXcode> -- <doc:ClientSwiftPM> -- <doc:ServerSwiftPM> +To see these features in action, see <doc:Checking-out-an-example-project>. -### Repository organization +## Usage -The Swift OpenAPI Generator project is split across multiple repositories to enable extensibility and minimize dependencies in your project. +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 <doc: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](#Example-OpenAPI-document) and can be used with any HTTP library that provides an implementation of `ClientTransport`. -**swift-openapi-generator** ([source][repo-generator], [docs][docs-generator]) provides the plugin. +```swift +import OpenAPIURLSession +import Foundation -**swift-openapi-runtime** ([source][repo-runtime], [docs][docs-runtime]) provides a library with common types and abstractions used by the generated code. +let client = Client( + serverURL: URL(string: "http://localhost:8080/api")!, + transport: URLSessionTransport()
```suggestion serverURL: URL(string: "http://localhost:8080/api")!, transport: URLSessionTransport() ``` Same as above.
swift-openapi-generator
github_2023
others
479
apple
czechboy0
@@ -8,49 +8,90 @@ Generate Swift client and server code from an OpenAPI document. ## Overview -[OpenAPI][openapi] is an open specification for documenting HTTP APIs. An OpenAPI document is written in either YAML or JSON. These machine-readable formats can be read by tools to automate workflows. OpenAPI has an large, existing [ecosystem of tooling][tools]. +[OpenAPI][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. -### Getting started +## Features -> Tip: In a rush? Get started quickly by <doc:Checking-out-an-example-project>. +- 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.
```suggestion - Client, server, and middleware abstractions, decoupling the generated code from the HTTP client library and web framework. ```
swift-openapi-generator
github_2023
others
480
apple
simonjbeaumont
@@ -0,0 +1,59 @@ +# Frequently asked questions + +Review some frequently asked questions below. + +## Overview + +This article includes some commonly asked questions and answers. + +### Which underlying HTTP library does the generated code use? + +Swift OpenAPI Generator is not tied to any particular HTTP library. Instead, the generated code utilizies a general protocol called [`ClientTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clienttransport) for client code, and [`ServerTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servertransport) for server code. + +The user of the generated code provides one of the concrete transport implementations, based on what's appropriate for their use case. + +Swift OpenAPI Generator links to some commonly used transport implementations from the [README](https://github.com/apple/swift-openapi-generator#repository-organization), but anyone is welcome to create their own custom transport implementation and share it as a package with the community.
Avoiding the word linked, in case people get the wrong idea about compile-time linking. ```suggestion Swift OpenAPI Generator lists some transport implementations in its [README](https://github.com/apple/swift-openapi-generator#repository-organization), but anyone is welcome to create their own custom transport implementation and share it as a package with the community. ```
swift-openapi-generator
github_2023
others
480
apple
simonjbeaumont
@@ -0,0 +1,59 @@ +# Frequently asked questions + +Review some frequently asked questions below. + +## Overview + +This article includes some commonly asked questions and answers. + +### Which underlying HTTP library does the generated code use? + +Swift OpenAPI Generator is not tied to any particular HTTP library. Instead, the generated code utilizies a general protocol called [`ClientTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clienttransport) for client code, and [`ServerTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servertransport) for server code. + +The user of the generated code provides one of the concrete transport implementations, based on what's appropriate for their use case. + +Swift OpenAPI Generator links to some commonly used transport implementations from the [README](https://github.com/apple/swift-openapi-generator#repository-organization), but anyone is welcome to create their own custom transport implementation and share it as a package with the community. + +To learn more, check out <doc:Checking-out-an-example-project#Getting-started>, which shows how to use some of the transport implementations. + +### How do I customize the HTTP requests and responses? + +If the code generated from the OpenAPI document, combined with the concrete transport implementation, doesn't behave exactly as you need, you can provide a _middleware_ type that can inspect and modify the HTTP requests and responses that are passed between the generated code and the transport. + +Just like with transports, there are two types, [`ClientMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clientmiddleware) and [`ServerMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servermiddleware). + +To learn more, check out <doc:Checking-out-an-example-project#Middleware> examples. + +### Is the generated code committed to my git repository?
```suggestion ### Do I commit the generated code to my source repository? ```
swift-openapi-generator
github_2023
others
480
apple
simonjbeaumont
@@ -0,0 +1,59 @@ +# Frequently asked questions + +Review some frequently asked questions below. + +## Overview + +This article includes some commonly asked questions and answers. + +### Which underlying HTTP library does the generated code use? + +Swift OpenAPI Generator is not tied to any particular HTTP library. Instead, the generated code utilizies a general protocol called [`ClientTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clienttransport) for client code, and [`ServerTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servertransport) for server code. + +The user of the generated code provides one of the concrete transport implementations, based on what's appropriate for their use case. + +Swift OpenAPI Generator links to some commonly used transport implementations from the [README](https://github.com/apple/swift-openapi-generator#repository-organization), but anyone is welcome to create their own custom transport implementation and share it as a package with the community. + +To learn more, check out <doc:Checking-out-an-example-project#Getting-started>, which shows how to use some of the transport implementations. + +### How do I customize the HTTP requests and responses? + +If the code generated from the OpenAPI document, combined with the concrete transport implementation, doesn't behave exactly as you need, you can provide a _middleware_ type that can inspect and modify the HTTP requests and responses that are passed between the generated code and the transport. + +Just like with transports, there are two types, [`ClientMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clientmiddleware) and [`ServerMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servermiddleware). + +To learn more, check out <doc:Checking-out-an-example-project#Middleware> examples. + +### Is the generated code committed to my git repository? + +It depends on the way you're integrating Swift OpenAPI Generator. + +The recommended way is to use the Swift package plugin, and let the build system generate the code on-demand, without the need to check it into your git repository. + +However, if you require to check your generated code into git, you can use the command plugin, or manually invoke the command-line tool. + +For details, check out <doc:Manually-invoking-the-generator-CLI>. + +### Does regenerating code from an updated OpenAPI document overwrite any of my code? + +Swift OpenAPI Generator was designed for a workflow called spec-driven development (check out <doc:Practicing-spec-driven-API-development> for details). That means that it is expected that the OpenAPI document changes frequently, and no developer-written code is overwritten when the Swift code is regenerated from the OpenAPI document. + +On the client, the generator emits a type called `Client` that conforms to a generated protocol called `APIProtocol`, which defines one method per OpenAPI operation. Client code generation provides you with a concrete implementation that makes HTTP requests over a provided transport. From your code, you _use_ the `Client` type, so when it gets updated, unless the OpenAPI document removed API you're using, you don't need to make any changes to your code.
```suggestion When run in `client` mode, the generator emits a type called `Client` that conforms to a generated protocol called `APIProtocol`, which defines one method per OpenAPI operation. Client code generation provides you with a concrete implementation that makes HTTP requests over a provided transport. From your code, you _use_ the `Client` type, so when it gets updated, unless the OpenAPI document removed API you're using, you don't need to make any changes to your code. ```
swift-openapi-generator
github_2023
others
480
apple
simonjbeaumont
@@ -0,0 +1,59 @@ +# Frequently asked questions + +Review some frequently asked questions below. + +## Overview + +This article includes some commonly asked questions and answers. + +### Which underlying HTTP library does the generated code use? + +Swift OpenAPI Generator is not tied to any particular HTTP library. Instead, the generated code utilizies a general protocol called [`ClientTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clienttransport) for client code, and [`ServerTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servertransport) for server code. + +The user of the generated code provides one of the concrete transport implementations, based on what's appropriate for their use case. + +Swift OpenAPI Generator links to some commonly used transport implementations from the [README](https://github.com/apple/swift-openapi-generator#repository-organization), but anyone is welcome to create their own custom transport implementation and share it as a package with the community. + +To learn more, check out <doc:Checking-out-an-example-project#Getting-started>, which shows how to use some of the transport implementations. + +### How do I customize the HTTP requests and responses? + +If the code generated from the OpenAPI document, combined with the concrete transport implementation, doesn't behave exactly as you need, you can provide a _middleware_ type that can inspect and modify the HTTP requests and responses that are passed between the generated code and the transport. + +Just like with transports, there are two types, [`ClientMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clientmiddleware) and [`ServerMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servermiddleware). + +To learn more, check out <doc:Checking-out-an-example-project#Middleware> examples. + +### Is the generated code committed to my git repository? + +It depends on the way you're integrating Swift OpenAPI Generator. + +The recommended way is to use the Swift package plugin, and let the build system generate the code on-demand, without the need to check it into your git repository. + +However, if you require to check your generated code into git, you can use the command plugin, or manually invoke the command-line tool. + +For details, check out <doc:Manually-invoking-the-generator-CLI>. + +### Does regenerating code from an updated OpenAPI document overwrite any of my code? + +Swift OpenAPI Generator was designed for a workflow called spec-driven development (check out <doc:Practicing-spec-driven-API-development> for details). That means that it is expected that the OpenAPI document changes frequently, and no developer-written code is overwritten when the Swift code is regenerated from the OpenAPI document. + +On the client, the generator emits a type called `Client` that conforms to a generated protocol called `APIProtocol`, which defines one method per OpenAPI operation. Client code generation provides you with a concrete implementation that makes HTTP requests over a provided transport. From your code, you _use_ the `Client` type, so when it gets updated, unless the OpenAPI document removed API you're using, you don't need to make any changes to your code. + +On the server, the generator emits the same `APIProtocol` protocol, and you implement a type that conforms to it, providing one method per OpenAPI operation. The other server generated code takes care of registering the generated routes on the underlying server. That means that when a new operation is added to the OpenAPI document, you get a build error telling you that your custom type needs to implement the new method to conform to `APIProtocol` again, guiding you towards writing code that complies with your OpenAPI document. However, none of your hand-written code is overwritten.
```suggestion When run in `server` mode, the generator emits the same `APIProtocol` protocol, and you implement a type that conforms to it, providing one method per OpenAPI operation. The other server generated code takes care of registering the generated routes on the underlying server. That means that when a new operation is added to the OpenAPI document, you get a build error telling you that your custom type needs to implement the new method to conform to `APIProtocol` again, guiding you towards writing code that complies with your OpenAPI document. However, none of your hand-written code is overwritten. ```
swift-openapi-generator
github_2023
others
480
apple
simonjbeaumont
@@ -0,0 +1,59 @@ +# Frequently asked questions + +Review some frequently asked questions below. + +## Overview + +This article includes some commonly asked questions and answers. + +### Which underlying HTTP library does the generated code use? + +Swift OpenAPI Generator is not tied to any particular HTTP library. Instead, the generated code utilizies a general protocol called [`ClientTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clienttransport) for client code, and [`ServerTransport`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servertransport) for server code. + +The user of the generated code provides one of the concrete transport implementations, based on what's appropriate for their use case. + +Swift OpenAPI Generator links to some commonly used transport implementations from the [README](https://github.com/apple/swift-openapi-generator#repository-organization), but anyone is welcome to create their own custom transport implementation and share it as a package with the community. + +To learn more, check out <doc:Checking-out-an-example-project#Getting-started>, which shows how to use some of the transport implementations. + +### How do I customize the HTTP requests and responses? + +If the code generated from the OpenAPI document, combined with the concrete transport implementation, doesn't behave exactly as you need, you can provide a _middleware_ type that can inspect and modify the HTTP requests and responses that are passed between the generated code and the transport. + +Just like with transports, there are two types, [`ClientMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/clientmiddleware) and [`ServerMiddleware`](https://swiftpackageindex.com/apple/swift-openapi-runtime/documentation/openapiruntime/servermiddleware). + +To learn more, check out <doc:Checking-out-an-example-project#Middleware> examples. + +### Is the generated code committed to my git repository? + +It depends on the way you're integrating Swift OpenAPI Generator. + +The recommended way is to use the Swift package plugin, and let the build system generate the code on-demand, without the need to check it into your git repository. + +However, if you require to check your generated code into git, you can use the command plugin, or manually invoke the command-line tool. + +For details, check out <doc:Manually-invoking-the-generator-CLI>. + +### Does regenerating code from an updated OpenAPI document overwrite any of my code? + +Swift OpenAPI Generator was designed for a workflow called spec-driven development (check out <doc:Practicing-spec-driven-API-development> for details). That means that it is expected that the OpenAPI document changes frequently, and no developer-written code is overwritten when the Swift code is regenerated from the OpenAPI document. + +On the client, the generator emits a type called `Client` that conforms to a generated protocol called `APIProtocol`, which defines one method per OpenAPI operation. Client code generation provides you with a concrete implementation that makes HTTP requests over a provided transport. From your code, you _use_ the `Client` type, so when it gets updated, unless the OpenAPI document removed API you're using, you don't need to make any changes to your code. + +On the server, the generator emits the same `APIProtocol` protocol, and you implement a type that conforms to it, providing one method per OpenAPI operation. The other server generated code takes care of registering the generated routes on the underlying server. That means that when a new operation is added to the OpenAPI document, you get a build error telling you that your custom type needs to implement the new method to conform to `APIProtocol` again, guiding you towards writing code that complies with your OpenAPI document. However, none of your hand-written code is overwritten. + +To learn about the different ways of integrating Swift OpenAPI Generator, check out <doc:Manually-invoking-the-generator-CLI>. + +### How do I fix the build error "Decl has a package access level but no -package-name was passed"? + +The build error `Decl has a package access level but no -package-name was passed` appears when the package or project is not configured with the [`package` access level](https://github.com/apple/swift-evolution/blob/main/proposals/0386-package-access-modifier.md) feature yet. + +The cause of this error is that the generated code is using the `package` access modifier for its API, but the project or package are not passing the `-package-name` option to the Swift compiler yet. + +For Swift packages, the fix is to ensure your `Package.swift` has a `swift-tools-version` of 5.9 or later. + +For Xcode projects, make sure the target that uses the Swift OpenAPI Generator build plugin provides the build setting `SWIFT_PACKAGE_NAME` (called "Package Access Identifier"). Set it to any name, for example the name of your Xcode project.
"any name" will work?
swift-openapi-generator
github_2023
others
478
apple
simonjbeaumont
@@ -44,11 +44,11 @@ } } @Section(title: "Add a Swagger UI endpoint") { - Now we'll add a static `openapi.html` page that serves Swagger UI and add a redirect to this page from `/` for discoverability. + Now we'll add a static `openapi.html` page that serves Swagger UI and add a redirect to this page from `/openapi` for discoverability.
Either this, or the `@Section` need updating. One says the endpoint is `/openapi`, the other `openapi.yaml`.
swift-openapi-generator
github_2023
others
478
apple
simonjbeaumont
@@ -3,12 +3,7 @@ import PackageDescription let package = Package( name: "GreetingServiceClient", - platforms: [ - .macOS(.v10_15), - .iOS(.v13), - .tvOS(.v13), - .watchOS(.v6), - ], + platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6)],
`visionOS`?
swift-openapi-generator
github_2023
others
478
apple
simonjbeaumont
@@ -1 +1,4 @@ +// The Swift Programming Language +// https://docs.swift.org/swift-book +
Do we want this?
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,106 @@ +name: 🐞 Report a bug +description: > + Report a deviation from expected or documented behavior, but not a crash. +labels: [kind/bug, status/triage] +body: + - type: markdown + attributes: + value: > + This repository hosts issues for the Swift OpenAPI generator, the Swift + OpenAPI runtime library, the Swift OpenAPI URLSession transport library, + and the AsyncHTTPClient transport library. + It does *not* track feedback on Xcode and other closed source Apple + developer software such as URLSession itself; please direct it to + [Feedback Assistant](https://developer.apple.com/bug-reporting) instead. + + ___ + - type: textarea + attributes: + label: Description + description: > + A concise description of what causes the problem, in human language. + Though not required, it may help us to more accurately triage the issue + as well as understand a non-trivial test case. + validations: + required: false + - type: textarea + attributes: + label: Reproduction + description: > + Please provide inputs to help us reproduce the issue. + + If the issue relates to code generation, provide an example OpenAPI + document, a generator configuration file, and extract of the Swift + code you believe to contain the issue. If generation fails, please + provide the generator output. + + If the issue is with using the generated code, or the runtime or + transport libraries, provide a test case, provide sample Swift code, and + explain how to build or run it to reproduce the problem. + + If the problem is a poor or unexpected error, warning, or output, please + show them. + + Consider reducing the test case to the smallest amount of code possible + β€” a smaller test case is easier to reason about and more appealing to + contributors. + placeholder: | + ```yaml + # openapi.yaml + openapi: '3.1.0' + ... + ``` + + ```yaml + # openapi-generator-config.yaml + mode: types, client
```suggestion generate: [types, client] ```
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,106 @@ +name: 🐞 Report a bug +description: > + Report a deviation from expected or documented behavior, but not a crash. +labels: [kind/bug, status/triage] +body: + - type: markdown + attributes: + value: > + This repository hosts issues for the Swift OpenAPI generator, the Swift + OpenAPI runtime library, the Swift OpenAPI URLSession transport library, + and the AsyncHTTPClient transport library. + It does *not* track feedback on Xcode and other closed source Apple + developer software such as URLSession itself; please direct it to + [Feedback Assistant](https://developer.apple.com/bug-reporting) instead. + + ___ + - type: textarea + attributes: + label: Description + description: > + A concise description of what causes the problem, in human language. + Though not required, it may help us to more accurately triage the issue + as well as understand a non-trivial test case. + validations: + required: false + - type: textarea + attributes: + label: Reproduction + description: > + Please provide inputs to help us reproduce the issue. + + If the issue relates to code generation, provide an example OpenAPI + document, a generator configuration file, and extract of the Swift + code you believe to contain the issue. If generation fails, please + provide the generator output. + + If the issue is with using the generated code, or the runtime or + transport libraries, provide a test case, provide sample Swift code, and + explain how to build or run it to reproduce the problem. + + If the problem is a poor or unexpected error, warning, or output, please + show them. + + Consider reducing the test case to the smallest amount of code possible + β€” a smaller test case is easier to reason about and more appealing to + contributors. + placeholder: | + ```yaml + # openapi.yaml + openapi: '3.1.0' + ... + ``` + + ```yaml + # openapi-generator-config.yaml + mode: types, client + ... + ``` + + ```swift + let message = try await client.getGreeting() + ``` + validations: + required: true + - type: textarea + attributes: + label: Package vesrion(s)
```suggestion label: Package version(s) ```
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,106 @@ +name: 🐞 Report a bug +description: > + Report a deviation from expected or documented behavior, but not a crash. +labels: [kind/bug, status/triage] +body: + - type: markdown + attributes: + value: > + This repository hosts issues for the Swift OpenAPI generator, the Swift + OpenAPI runtime library, the Swift OpenAPI URLSession transport library, + and the AsyncHTTPClient transport library. + It does *not* track feedback on Xcode and other closed source Apple + developer software such as URLSession itself; please direct it to + [Feedback Assistant](https://developer.apple.com/bug-reporting) instead. + + ___ + - type: textarea + attributes: + label: Description + description: > + A concise description of what causes the problem, in human language. + Though not required, it may help us to more accurately triage the issue + as well as understand a non-trivial test case. + validations: + required: false + - type: textarea + attributes: + label: Reproduction + description: > + Please provide inputs to help us reproduce the issue. + + If the issue relates to code generation, provide an example OpenAPI + document, a generator configuration file, and extract of the Swift + code you believe to contain the issue. If generation fails, please + provide the generator output. + + If the issue is with using the generated code, or the runtime or + transport libraries, provide a test case, provide sample Swift code, and + explain how to build or run it to reproduce the problem. + + If the problem is a poor or unexpected error, warning, or output, please + show them. + + Consider reducing the test case to the smallest amount of code possible + β€” a smaller test case is easier to reason about and more appealing to + contributors. + placeholder: | + ```yaml + # openapi.yaml + openapi: '3.1.0' + ... + ``` + + ```yaml + # openapi-generator-config.yaml + mode: types, client + ... + ``` + + ```swift + let message = try await client.getGreeting() + ``` + validations: + required: true + - type: textarea + attributes: + label: Package vesrion(s) + description: > + Provide the versions of the relevant Swift OpenAPI packages used when + encountering the issue. + placeholder: | + ```console + % swift package show-dependencies + ``` + validations: + required: true + - type: textarea + attributes: + label: Expected behavior + description: > + Describe the behavior you expected. + validations: + required: true + - type: textarea + attributes: + label: Environment + description: > + Provide the Swift version, tag, or revision. If you suspect that the + problem might be specific to a particular development platform or + deployment target, please specify them as well. + placeholder: | + ```console + % swift -version
Maybe also `sw_vers` if on an Apple platform?
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,35 @@ +blank_issues_enabled: true +contact_links: + - name: πŸ“– Learn about Swift OpenAPI Generator + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/ + about: > + Read the rendered Swift OpenAPI Generator documentation on Swift Package Index. + - name: πŸ§‘β€πŸ« Example projects + url: https://github.com/apple/swift-openapi-generator/blob/main/Examples/README.md + about: > + Build, run, and experiment with sample projects that use Swift OpenAPI + Generator and integrate with other packages in the ecosystem. + - name: βœ… Take a look at the FAQ + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/useful-openapi-patterns + about: > + See solutions to commonly-asked questions and common workflows.
Can you actually add a new blank FAQ page so that these links can be accurate? I don't suppose the OpenAPI patterns page will actually be our FAQ?
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,35 @@ +blank_issues_enabled: true +contact_links: + - name: πŸ“– Learn about Swift OpenAPI Generator + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/ + about: > + Read the rendered Swift OpenAPI Generator documentation on Swift Package Index. + - name: πŸ§‘β€πŸ« Example projects + url: https://github.com/apple/swift-openapi-generator/blob/main/Examples/README.md + about: > + Build, run, and experiment with sample projects that use Swift OpenAPI + Generator and integrate with other packages in the ecosystem. + - name: βœ… Take a look at the FAQ + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/useful-openapi-patterns + about: > + See solutions to commonly-asked questions and common workflows. + - name: 🧩 Check the list of supported OpenAPI features + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/supported-openapi-features + about: > + See which features of the OpenAPI Specification are currently supported by + the Swift OpenAPI Generator. + - name: πŸ“„ Formally propose a change + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/proposals + about: > + Formally propose an addition, removal, or change to the features of the
```suggestion Formally propose an addition, or change to the features of the ``` Post 1.0 I don't think we're likely to accept any removals.
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,35 @@ +blank_issues_enabled: true +contact_links: + - name: πŸ“– Learn about Swift OpenAPI Generator + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/ + about: > + Read the rendered Swift OpenAPI Generator documentation on Swift Package Index. + - name: πŸ§‘β€πŸ« Example projects + url: https://github.com/apple/swift-openapi-generator/blob/main/Examples/README.md + about: > + Build, run, and experiment with sample projects that use Swift OpenAPI + Generator and integrate with other packages in the ecosystem. + - name: βœ… Take a look at the FAQ + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/useful-openapi-patterns + about: > + See solutions to commonly-asked questions and common workflows. + - name: 🧩 Check the list of supported OpenAPI features + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/supported-openapi-features + about: > + See which features of the OpenAPI Specification are currently supported by + the Swift OpenAPI Generator. + - name: πŸ“„ Formally propose a change + url: https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/proposals + about: > + Formally propose an addition, removal, or change to the features of the + Swift OpenAPI Generator using the proposal process. + - name: πŸ’¬ Join the \#openapi Slack channel + url: https://swift-open-source.slack.com/archives/C05AZ55J75K + about: > + Chat with other adopters and contributors on the Swift Open Source Slack + workspace. + - name: πŸͺ² Report an issue using Feedback Assistant + url: https://developer.apple.com/bug-reporting + about: > + Report an issue with Xcode or other closed source Apple developer + software such as URLSession.
Can we move this much higher? I suspect otherwise people will still file it on us. Should come before the button to create an issue on us.
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,30 @@ +name: πŸ™‹ Ask a question +description: > + Ask a question about or get help with Swift OpenAPI Generator. Beginner + questions welcome! +labels: [kind/support, status/triage] +body: + - type: markdown + attributes: + value: > + This repository hosts issues for the Swift OpenAPI generator, the Swift + OpenAPI runtime library, the Swift OpenAPI URLSession transport library, + and the AsyncHTTPClient transport library. + It does *not* track feedback on Xcode and other closed source Apple + developer software such as URLSession itself; please direct it to + [Feedback Assistant](https://developer.apple.com/bug-reporting) instead. + + ___ + + Please use this issue template to ask a question. + + You may also like to check out our + [FAQ](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/useful-openapi-patterns)
Same here, let's update with a link to the real FAQ.
swift-openapi-generator
github_2023
others
477
apple
czechboy0
@@ -0,0 +1,30 @@ +name: πŸ™‹ Ask a question +description: > + Ask a question about or get help with Swift OpenAPI Generator. Beginner + questions welcome! +labels: [kind/support, status/triage] +body: + - type: markdown + attributes: + value: > + This repository hosts issues for the Swift OpenAPI generator, the Swift + OpenAPI runtime library, the Swift OpenAPI URLSession transport library, + and the AsyncHTTPClient transport library. + It does *not* track feedback on Xcode and other closed source Apple + developer software such as URLSession itself; please direct it to + [Feedback Assistant](https://developer.apple.com/bug-reporting) instead. + + ___ + + Please use this issue template to ask a question. + + You may also like to check out our + [FAQ](https://swiftpackageindex.com/apple/swift-openapi-generator/documentation/swift-openapi-generator/useful-openapi-patterns) + for solutions to commonly-asked questions and common workflows.
```suggestion for solutions to commonly asked questions and common workflows. ``` I believe a hyphen is not needed after -ly?
swift-openapi-generator
github_2023
others
466
apple
simonjbeaumont
@@ -16,7 +16,7 @@ The tool uses the [Vapor](https://github.com/vapor/vapor) server framework to ha The CLI starts the server on `http://localhost:8080` and can be invoked by running the `AuthenticationClientMiddleware` example client or on the command line using: ```
Nice-to-have: if you use ``` \`\`\`console % command line console output % command line console output console output \`\`\` ``` ```console % command line console output % command line console output console output ```
swift-openapi-generator
github_2023
others
467
apple
czechboy0
@@ -8,12 +8,9 @@ that use `swift-log` to log requests and responses. ## Overview This example extends the [hello-world-urlsession-client-example](../hello-world-urlsession-client-example) -with a new target, `LoggingMiddleware`, which is then used when creating -the `Client`. - -The `LoggingMiddleware` provides two types: -- `LoggingClientMiddleware`, which implements the `OpenAPIRuntime.ClientMiddleware` protocol. -- `LoggingServerMiddleware`, which implements the `OpenAPIRuntime.ServerMiddleware` protocol. +with a new target, `LoggingMiddleware`, which can eb used when creating
```suggestion with a new target, `LoggingMiddleware`, which can be used when creating ```
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,123 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import OpenAPIRuntime +import OpenAPIURLSession +import Foundation + +@main struct ContentTypesClient { + static func main() async throws { + let client = Client(serverURL: URL(string: "http://localhost:8080/api")!, transport: URLSessionTransport()) + do { + let response = try await client.getExampleJSON(query: .init(name: "CLI")) + let greeting = try response.ok.body.json + print("Received greeting: \(greeting.message)") + } + do { + let message = "Hello, Stranger!" + let response = try await client.postExampleJSON(body: .json(.init(message: message))) + _ = try response.accepted + print("Sent JSON greeting: \(message)") + } + do { + let message = "Hello, Stranger!" + let response = try await client.postExampleURLEncoded(body: .urlEncodedForm(.init(message: message))) + _ = try response.accepted + print("Sent URLEncoded greeting: \(message)") + } + do { + let response = try await client.getExampleMultipart() + let multipartBody = try response.ok.body.multipartForm + for try await part in multipartBody { + switch part { + case .greetingTemplate(let template): + let message = template.payload.body.message + print("Received a template message: \(message)") + case .names(let name): + let stringName = try await String(collecting: name.payload.body, upTo: 1024) + // Multipart parts can have headers. + let locale = name.payload.headers.x_hyphen_name_hyphen_locale ?? "<nil>" + print("Received a name: '\(stringName)', header value: '\(locale)'") + case .undocumented(let part): + // Any part with a raw HTTPBody body must have its body consumed before moving on to the next part. + let bytes = try await [UInt8](collecting: part.body, upTo: 1024 * 1024) + print( + "Received an undocumented part with \(part.headerFields.count) headers and \(bytes.count) bytes." + ) + } + } + } + do { + let multipartBody: MultipartBody<Operations.postExampleMultipart.Input.Body.multipartFormPayload> = [ + .greetingTemplate(.init(payload: .init(body: .init(message: "Hello, {name}!")))), + .names(.init(payload: .init(headers: .init(x_hyphen_name_hyphen_locale: "en_US"), body: "Frank"))), + .names(.init(payload: .init(body: "Not Frank"))), + ] + let response = try await client.postExampleMultipart(body: .multipartForm(multipartBody)) + _ = try response.accepted + print("Sent multipart") + } + do { + let response = try await client.getExamplePlainText() + let plainText = try response.ok.body.plainText + let bufferedText = try await String(collecting: plainText, upTo: 1024) + print("Received text: \(bufferedText)") + } + do { + let response = try await client.postExamplePlainText( + body: .plainText( + """ + A snow log. + --- + [2023-12-24] It snowed. + [2023-12-25] It snowed even more. + """ + ) + ) + _ = try response.accepted + print("Sent plain text") + } + do { + let response = try await client.getExampleRawBytes() + let binary = try response.ok.body.binary + // Processes each chunk as it comes in, avoids buffering the whole body into memory. + for try await chunk in binary { print("Received chunk: \(chunk)") } + } + do { + let response = try await client.postExampleRawBytes(body: .binary([0x73, 0x6e, 0x6f, 0x77, 0x0a])) + _ = try response.accepted + print("Sent binary") + } + do { + let response = try await client.getExampleMultipleContentTypes( + headers: .init(accept: [ + .init(contentType: .json, quality: 1.0), .init(contentType: .plainText, quality: 0.8), + ]) + ) + let body = try response.ok.body + switch body { + case .json(let json): print("Received a JSON greeting with the message: \(json.message)") + case .plainText(let body): + let text = try await String(collecting: body, upTo: 1024) + print("Received a text greeting with the message: \(text)") + } + }
I think we should move this one up before multipart, so that the flow is: 1. Simple request with one content type. 2. Simple request with one (other) content type. (we have these already). 3. Request that can return one of several content types. 4. Then move onto multipart things. I also think we could use some code comments accompanying (3), explaining that we can handle the undocumented response. We might consider also adding the switch-based flow for an example with one documented type too, just to show how to be defensive against updated APIs.
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,161 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import OpenAPIRuntime +import OpenAPIVapor +import Vapor + +struct Handler: APIProtocol { + + func getExampleJSON(_ input: Operations.getExampleJSON.Input) async throws -> Operations.getExampleJSON.Output { + let name = input.query.name ?? "Stranger" + print("Greeting a person with the name: \(name)") + return .ok(.init(body: .json(.init(message: "Hello, \(name)!")))) + } + + func postExampleJSON(_ input: Operations.postExampleJSON.Input) async throws -> Operations.postExampleJSON.Output { + let requestBody: Components.Schemas.Greeting + switch input.body { + case .json(let json): requestBody = json + } + print("Received a greeting with the message: '\(requestBody.message)'") + return .accepted(.init()) + } + + func postExampleURLEncoded(_ input: Operations.postExampleURLEncoded.Input) async throws + -> Operations.postExampleURLEncoded.Output + { + let requestBody: Operations.postExampleURLEncoded.Input.Body.urlEncodedFormPayload + switch input.body { + case .urlEncodedForm(let form): requestBody = form + } + print("Received a greeting with the message: '\(requestBody.message)'") + return .accepted(.init()) + } + + func getExampleMultipart(_ input: Operations.getExampleMultipart.Input) async throws + -> Operations.getExampleMultipart.Output + { + let multipartBody: MultipartBody<Operations.getExampleMultipart.Output.Ok.Body.multipartFormPayload> = [ + .greetingTemplate(.init(payload: .init(body: .init(message: "Hello, {name}!")))), + .names(.init(payload: .init(headers: .init(x_hyphen_name_hyphen_locale: "en_US"), body: "Frank"))), + .names(.init(payload: .init(body: "Not Frank"))), + ] + return .ok(.init(body: .multipartForm(multipartBody))) + } + + func postExampleMultipart(_ input: Operations.postExampleMultipart.Input) async throws + -> Operations.postExampleMultipart.Output + { + let multipartBody: MultipartBody<Operations.postExampleMultipart.Input.Body.multipartFormPayload> + switch input.body { + case .multipartForm(let form): multipartBody = form + } + for try await part in multipartBody { + switch part { + case .greetingTemplate(let template): + let message = template.payload.body.message + print("Received a template message: \(message)") + case .names(let name): + let stringName = try await String(collecting: name.payload.body, upTo: 1024) + // Multipart parts can have headers. + let locale = name.payload.headers.x_hyphen_name_hyphen_locale ?? "<nil>" + print("Received a name: '\(stringName)', header value: '\(locale)'") + case .undocumented(let part): + // Any part with a raw HTTPBody body must have its body consumed before moving on to the next part. + let bytes = try await [UInt8](collecting: part.body, upTo: 1024 * 1024) + print("Received an undocumented part with \(part.headerFields.count) headers and \(bytes.count) bytes.") + } + } + return .accepted(.init()) + } + + func getExamplePlainText(_ input: Operations.getExamplePlainText.Input) async throws + -> Operations.getExamplePlainText.Output + { + .ok( + .init( + body: .plainText( + """ + A snow log. + --- + [2023-12-24] It snowed. + [2023-12-25] It snowed even more.
β›„ ❀️
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,161 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import OpenAPIRuntime +import OpenAPIVapor +import Vapor + +struct Handler: APIProtocol { + + func getExampleJSON(_ input: Operations.getExampleJSON.Input) async throws -> Operations.getExampleJSON.Output { + let name = input.query.name ?? "Stranger" + print("Greeting a person with the name: \(name)") + return .ok(.init(body: .json(.init(message: "Hello, \(name)!")))) + } + + func postExampleJSON(_ input: Operations.postExampleJSON.Input) async throws -> Operations.postExampleJSON.Output { + let requestBody: Components.Schemas.Greeting + switch input.body { + case .json(let json): requestBody = json + } + print("Received a greeting with the message: '\(requestBody.message)'") + return .accepted(.init()) + } + + func postExampleURLEncoded(_ input: Operations.postExampleURLEncoded.Input) async throws + -> Operations.postExampleURLEncoded.Output + { + let requestBody: Operations.postExampleURLEncoded.Input.Body.urlEncodedFormPayload + switch input.body { + case .urlEncodedForm(let form): requestBody = form + } + print("Received a greeting with the message: '\(requestBody.message)'") + return .accepted(.init()) + } + + func getExampleMultipart(_ input: Operations.getExampleMultipart.Input) async throws + -> Operations.getExampleMultipart.Output + { + let multipartBody: MultipartBody<Operations.getExampleMultipart.Output.Ok.Body.multipartFormPayload> = [ + .greetingTemplate(.init(payload: .init(body: .init(message: "Hello, {name}!")))), + .names(.init(payload: .init(headers: .init(x_hyphen_name_hyphen_locale: "en_US"), body: "Frank"))), + .names(.init(payload: .init(body: "Not Frank"))), + ] + return .ok(.init(body: .multipartForm(multipartBody))) + } + + func postExampleMultipart(_ input: Operations.postExampleMultipart.Input) async throws + -> Operations.postExampleMultipart.Output + { + let multipartBody: MultipartBody<Operations.postExampleMultipart.Input.Body.multipartFormPayload> + switch input.body { + case .multipartForm(let form): multipartBody = form + } + for try await part in multipartBody { + switch part { + case .greetingTemplate(let template): + let message = template.payload.body.message + print("Received a template message: \(message)") + case .names(let name): + let stringName = try await String(collecting: name.payload.body, upTo: 1024) + // Multipart parts can have headers. + let locale = name.payload.headers.x_hyphen_name_hyphen_locale ?? "<nil>" + print("Received a name: '\(stringName)', header value: '\(locale)'") + case .undocumented(let part): + // Any part with a raw HTTPBody body must have its body consumed before moving on to the next part. + let bytes = try await [UInt8](collecting: part.body, upTo: 1024 * 1024) + print("Received an undocumented part with \(part.headerFields.count) headers and \(bytes.count) bytes.") + } + } + return .accepted(.init()) + } + + func getExamplePlainText(_ input: Operations.getExamplePlainText.Input) async throws + -> Operations.getExamplePlainText.Output + { + .ok( + .init( + body: .plainText( + """ + A snow log. + --- + [2023-12-24] It snowed. + [2023-12-25] It snowed even more. + """ + ) + ) + ) + } + + func postExamplePlainText(_ input: Operations.postExamplePlainText.Input) async throws + -> Operations.postExamplePlainText.Output + { + let plainText: HTTPBody + switch input.body { + case .plainText(let body): plainText = body + } + let bufferedText = try await String(collecting: plainText, upTo: 1024) + print("Received text: \(bufferedText)") + return .accepted(.init()) + } + + func getExampleRawBytes(_ input: Operations.getExampleRawBytes.Input) async throws + -> Operations.getExampleRawBytes.Output + { .ok(.init(body: .binary([0x73, 0x6e, 0x6f, 0x77, 0x0a]))) } + + func postExampleRawBytes(_ input: Operations.postExampleRawBytes.Input) async throws + -> Operations.postExampleRawBytes.Output + { + let binary: HTTPBody + switch input.body { + case .binary(let body): binary = body + } + // Processes each chunk as it comes in, avoids buffering the whole body into memory. + for try await chunk in binary { print("Received chunk: \(chunk)") } + return .accepted(.init()) + } + + func getExampleMultipleContentTypes(_ input: Operations.getExampleMultipleContentTypes.Input) async throws + -> Operations.getExampleMultipleContentTypes.Output + { + let chosenContentType = input.headers.accept.sortedByQuality().first?.contentType ?? .json
I think some comments here could help.
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,36 @@ +// swift-tools-version:5.9 +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import PackageDescription + +let package = Package( + name: "CuratedLibraryClient", + platforms: [.macOS(.v10_15), .iOS(.v13), .tvOS(.v13), .watchOS(.v6), .visionOS(.v1)], + products: [.library(name: "CuratedLibraryClient", targets: ["CuratedLibraryClient"])], + dependencies: [ + .package(url: "https://github.com/apple/swift-openapi-generator", exact: "1.0.0-alpha.1"), + .package(url: "https://github.com/apple/swift-openapi-runtime", exact: "1.0.0-alpha.1"), + .package(url: "https://github.com/apple/swift-openapi-urlsession", exact: "1.0.0-alpha.1"), + ], + targets: [ + .target( + name: "CuratedLibraryClient", + dependencies: [ + .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"), + .product(name: "OpenAPIURLSession", package: "swift-openapi-urlsession"), + ], + plugins: [.plugin(name: "OpenAPIGenerator", package: "swift-openapi-generator")] + ), .testTarget(name: "CuratedLibraryClientTests", dependencies: ["CuratedLibraryClient"]),
Oh, I hate this swift-format'ing so much.
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,57 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import XCTest +@testable import CuratedLibraryClient
Will this work without `@testable`? Might be nice to remove since the goal of this, stated in the other file, is `A hand-written Swift API for the greeting service, one that doesn't leak any generated code`. Might have to move the extension to another file.
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,4 @@ +generate: + - types + - client +accessModifier: internal
Why does this need to be `internal` for a curated library client package? Can't it be `package` still?
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,46 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import OpenAPIRuntime +import OpenAPIURLSession +import Foundation + +/// A hand-written Swift API for the greeting service, one that doesn't leak any generated code. +public struct GreetingClient { + + /// The underlying generated client to make HTTP requests to GreetingService. + private let underlyingClient: any APIProtocol + + /// An internal initializer used by other initializers and by tests. + /// - Parameter underlyingClient: The client to use to make HTTP requests. + internal init(underlyingClient: any APIProtocol) { self.underlyingClient = underlyingClient } + + /// Creates a new client for GreetingService. + public init() { + self.init( + underlyingClient: Client( + serverURL: URL(string: "https://localhost:8080/api")!, + transport: URLSessionTransport() + ) + ) + }
Seems a bit inconsistent currently. `underlyingClient` is an existential, but here we don't allow the user to provide a transport. If we're going to hardcode `URLSessionTransport` then we should make `underlyingClient` concrete. However, I'm probably in favour of accepting `any ClientTransport` here and defaulting to `URLSessionTransport()`. This feels the most like what we're trying to show too: a library package that does the API stuff, but you still bring the transport? Or, if I'm misunderstanding and we want it completely implementation detail?
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,21 @@ +REPO_URL = https://github.com/apple/swift-openapi-generator +VERSION = 1.0.0-alpha.1 +TMP_DIR = /tmp +REPO_DIR = $(TMP_DIR)/swift-openapi-generator +CLI_EXECUTABLE = $(REPO_DIR)/.build/release/swift-openapi-generator
```suggestion REPO_URL ?= https://github.com/apple/swift-openapi-generator VERSION ?= 1.0.0-alpha.1 TMP_DIR ?= /tmp REPO_DIR ?= $(TMP_DIR)/swift-openapi-generator CLI_EXECUTABLE ?= $(REPO_DIR)/.build/release/swift-openapi-generator ```
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,21 @@ +REPO_URL = https://github.com/apple/swift-openapi-generator +VERSION = 1.0.0-alpha.1 +TMP_DIR = /tmp +REPO_DIR = $(TMP_DIR)/swift-openapi-generator +CLI_EXECUTABLE = $(REPO_DIR)/.build/release/swift-openapi-generator + +$(REPO_DIR): + git clone --branch $(VERSION) $(REPO_URL) $(REPO_DIR)
```suggestion git clone --branch $(VERSION) --depth 1 $(REPO_URL) $(REPO_DIR) ```
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,36 @@ +# OpenAPI Endpoints Server + +An example project using [Swift OpenAPI Generator](https://github.com/apple/swift-openapi-generator). + +## Overview + +A server that shows setting up endpoints that serve the OpenAPI document and also a web page with the rendered documentation, respectively. It also uses generated server stubs to handle requests as the Greeting Service. + +Note that the `openapi.yaml` file is now in the `Public` directory, served by the `FileMiddleware` automatically. + +And the Sources directory of the server target contains a symlink to the file above, to avoid having two copies of the OpenAPI document that could get out of sync. + +The OpenAPI document also contains the following server definition, which allows making HTTP requests directly from the documentation viewer served at `http://localhost:8080/openapi`. + +```yaml + - url: /api + description: This server. +``` + +The tool uses the [Vapor](https://github.com/vapor/vapor) server framework to handle HTTP requests, wrapped in the [Swift OpenAPI Vapor Transport](https://github.com/swift-server/swift-openapi-vapor). + +The documentation viewer uses [swagger-ui](https://github.com/swagger-api/swagger-ui). + +The CLI starts the server on `http://localhost:8080` and you can go to `http://localhost:8080/openapi.yaml` to see the raw OpenAPI document, and to `http://localhost:8080/openapi` to see the rendered documentation. + +## Usage + +Build and run the server CLI using: + +``` +$ swift run +2023-12-01T14:14:35+0100 notice codes.vapor.application : [Vapor] Server starting on http://127.0.0.1:8080 +... +``` + +Then go to `https://localhost:8080/openapi` in your web browser.
Should we include a screenshot here (relying on Github user content to store it, not checking in), or not?
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,63 @@ +// +// ContentView.swift +// iOSAppClient +//
Missing license header.
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,63 @@ +// +// ContentView.swift +// iOSAppClient +// + +import SwiftUI +import OpenAPIRuntime +import OpenAPIURLSession + +/// A content view that can make HTTP requests to the GreetingService +/// running on localhost to fetch customized greetings. +/// +/// By default, it makes live network calls, but it can be provided +/// with `MockClient` to make mocked in-memory calls only, which is more +/// appropriate in previews and tests. +struct ContentView: View { + @State private var greeting: String = "Hello, Stranger!" + @State private var name: String = "Stranger" + let client: any APIProtocol + init(client: any APIProtocol) { self.client = client } + init() { + if let stringValue = ProcessInfo.processInfo.environment["USE_MOCK_CLIENT"], let boolValue = Bool(stringValue), + boolValue + {
Do we really need this env-var dance? I think it's probably enough to be using the mock client in the previews and the real client in the simulator?
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,8 @@ +//
Again, missing header.
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -0,0 +1,11 @@ +# Starting with an example project + +Duplicate a working example to start your project. + +## Overview + +All the examples are self-contained, so you can copy the package directory of your chosen example and use it as a starter template for your project. + +### Getting started + +TODO: Copy the contents of the Examples/README.md file here, and link to the github.com/... directory location.
Let's just link to the examples directory on Github. No point in copying its contents since the next link will take you to Github anyway (for each specific example).
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -69,6 +69,10 @@ read -ra PATHS_TO_CHECK_FOR_LICENSE <<< "$( \ ":(exclude)**/docker-compose.yaml" \ ":(exclude)Plugins/OpenAPIGenerator/PluginsShared" \ ":(exclude)Plugins/OpenAPIGeneratorCommand/PluginsShared" \ + ":(exclude)Examples/iOSAppClient/*" \
OK, this one is too broad, and the reason the Swift files were not checked.
swift-openapi-generator
github_2023
others
422
apple
simonjbeaumont
@@ -32,7 +32,7 @@ SWIFTFORMAT_BIN=${SWIFTFORMAT_BIN:-$(command -v swift-format)} || fatal "❌ SWI git -C "${REPO_ROOT}" ls-files -z '*.swift' \ | grep -z -v -e 'Tests/OpenAPIGeneratorReferenceTests/Resources' \ - -e 'Sources/swift-openapi-generator/Documentation.docc' \ + -e 'Sources/swift-openapi-generator/Documentation.docc' -e 'Generated' \
```suggestion -e 'Sources/swift-openapi-generator/Documentation.docc' \ -e 'Generated' \ ```
swift-openapi-generator
github_2023
others
440
apple
simonjbeaumont
@@ -0,0 +1,24 @@ +# Client Authentication Middleware + +In this example we'll implement a `ClientMiddleware` that injects an authentication header into the request. + +## Overview + +This example extends the [HelloWorldURLSessionClient](../HelloWorldURLSessionClient) +with a new target, `AuthenticationClientMiddleware`, which is then used when creating +the `Client`. + +NOTE: This example shows just one way of injecting authentication information in a middleware +and is purely for illustrative purposes. + +The tool uses the [URLSession](https://developer.apple.com/documentation/foundation/urlsession) API to perform the HTTP call, wrapped in the [Swift OpenAPI URLSession Transport](https://github.com/apple/swift-openapi-urlsession). + +The server can be started by running the `AuthenticationServerMiddleware` example locally. + +## Usage + +Build and run the client CLI using: + +``` +$ swift run
This needs some more. Can we make the token an env var so we can see it fail without and succeed with?
swift-openapi-generator
github_2023
others
450
apple
simonjbeaumont
@@ -9,26 +9,27 @@ Swift OpenAPI Generator generates client and server Swift code from an OpenAPI d This document outlines the API stability goals for the generator to help you avoid unintentional build errors when updating to a new version of Swift OpenAPI Generator. The components covered by these rules are: -- the name of the Swift OpenAPI Generator package plugin -- the format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool) -- the Swift OpenAPI Generator CLI tool arguments +- The name of the Swift OpenAPI Generator package plugin. +- The format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool). +- The Swift OpenAPI Generator CLI tool arguments, options, and flags. -If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied before 1.0 is released, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. +If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. -### API stability for versions >= 1.0.0 +### API stability
```suggestion ``` Can we remove these headings. It breaks the flow. This heading used to make sense as it was a pre-1.0 caveat. Now it doesn't because the whole doc is about API stability.
swift-openapi-generator
github_2023
others
450
apple
simonjbeaumont
@@ -9,26 +9,27 @@ Swift OpenAPI Generator generates client and server Swift code from an OpenAPI d This document outlines the API stability goals for the generator to help you avoid unintentional build errors when updating to a new version of Swift OpenAPI Generator. The components covered by these rules are:
```suggestion Swift OpenAPI Generator follows [Semantic Versioning 2.0.0][0] for the following, which are considered part of its API: ```
swift-openapi-generator
github_2023
others
450
apple
simonjbeaumont
@@ -9,26 +9,27 @@ Swift OpenAPI Generator generates client and server Swift code from an OpenAPI d This document outlines the API stability goals for the generator to help you avoid unintentional build errors when updating to a new version of Swift OpenAPI Generator. The components covered by these rules are: -- the name of the Swift OpenAPI Generator package plugin -- the format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool) -- the Swift OpenAPI Generator CLI tool arguments +- The name of the Swift OpenAPI Generator package plugin. +- The format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool). +- The Swift OpenAPI Generator CLI tool arguments, options, and flags. -If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied before 1.0 is released, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. +If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. -### API stability for versions >= 1.0.0 +### API stability -After the project reaches 1.0.0, we will follow [Semantic Versioning 2.0.0][0]. +Since 1.0.0, the project follows [Semantic Versioning 2.0.0][0].
Added a suggestion that this go much higher up in the doc, just before we list what's covered by SemVer. ```suggestion ```
swift-openapi-generator
github_2023
others
450
apple
simonjbeaumont
@@ -9,26 +9,27 @@ Swift OpenAPI Generator generates client and server Swift code from an OpenAPI d This document outlines the API stability goals for the generator to help you avoid unintentional build errors when updating to a new version of Swift OpenAPI Generator. The components covered by these rules are: -- the name of the Swift OpenAPI Generator package plugin -- the format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool) -- the Swift OpenAPI Generator CLI tool arguments +- The name of the Swift OpenAPI Generator package plugin. +- The format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool). +- The Swift OpenAPI Generator CLI tool arguments, options, and flags. -If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied before 1.0 is released, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. +If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. -### API stability for versions >= 1.0.0 +### API stability -After the project reaches 1.0.0, we will follow [Semantic Versioning 2.0.0][0]. +Since 1.0.0, the project follows [Semantic Versioning 2.0.0][0]. -### API stability for versions 0.y.z +### Implementation details -Swift OpenAPI Generator is being developed as an open source project. In order to accommodate feedback from the community, it does not yet have a 1.0.0 release. Until it does, we reserve the right to change the API between _minor_ versions (for example, between `0.2.0` and `0.3.0`), as described in the Semantic Version Specification[[1]][[2]]. +In contrast to the guarantees provided for the API of Swift OpenAPI Generator, as defined above, below is a list of behaviors that are _not_ considered API, and are explicitly consider an implementation detail that can change without prior warning:
```suggestion In contrast to the guarantees provided for the API of Swift OpenAPI Generator, the following list of behaviors are _not_ considered API, and can change without prior warning: ```
swift-openapi-generator
github_2023
others
450
apple
simonjbeaumont
@@ -9,26 +9,27 @@ Swift OpenAPI Generator generates client and server Swift code from an OpenAPI d This document outlines the API stability goals for the generator to help you avoid unintentional build errors when updating to a new version of Swift OpenAPI Generator. The components covered by these rules are: -- the name of the Swift OpenAPI Generator package plugin -- the format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool) -- the Swift OpenAPI Generator CLI tool arguments +- The name of the Swift OpenAPI Generator package plugin. +- The format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool). +- The Swift OpenAPI Generator CLI tool arguments, options, and flags. -If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied before 1.0 is released, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. +If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. -### API stability for versions >= 1.0.0 +### API stability -After the project reaches 1.0.0, we will follow [Semantic Versioning 2.0.0][0]. +Since 1.0.0, the project follows [Semantic Versioning 2.0.0][0]. -### API stability for versions 0.y.z +### Implementation details -Swift OpenAPI Generator is being developed as an open source project. In order to accommodate feedback from the community, it does not yet have a 1.0.0 release. Until it does, we reserve the right to change the API between _minor_ versions (for example, between `0.2.0` and `0.3.0`), as described in the Semantic Version Specification[[1]][[2]]. +In contrast to the guarantees provided for the API of Swift OpenAPI Generator, as defined above, below is a list of behaviors that are _not_ considered API, and are explicitly consider an implementation detail that can change without prior warning: -> Tip: To avoid unexpected build issues, use `.upToNextMinor(from: "0.y.z")` in your `Package.swift` when declaring a dependency on Swift OpenAPI Generator packages (including the runtime and transport libraries).
Clearly this is correct to remove. But it would be good somewhere to advise folks to use `from: 1.0.0`. We can defer that to when we add the usual getting started snippets to the README, which are missing right now.
swift-openapi-generator
github_2023
others
450
apple
simonjbeaumont
@@ -9,26 +9,27 @@ Swift OpenAPI Generator generates client and server Swift code from an OpenAPI d This document outlines the API stability goals for the generator to help you avoid unintentional build errors when updating to a new version of Swift OpenAPI Generator. The components covered by these rules are: -- the name of the Swift OpenAPI Generator package plugin -- the format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool) -- the Swift OpenAPI Generator CLI tool arguments +- The name of the Swift OpenAPI Generator package plugin. +- The format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool). +- The Swift OpenAPI Generator CLI tool arguments, options, and flags. -If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied before 1.0 is released, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. +If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. -### API stability for versions >= 1.0.0 +### API stability -After the project reaches 1.0.0, we will follow [Semantic Versioning 2.0.0][0]. +Since 1.0.0, the project follows [Semantic Versioning 2.0.0][0]. -### API stability for versions 0.y.z +### Implementation details -Swift OpenAPI Generator is being developed as an open source project. In order to accommodate feedback from the community, it does not yet have a 1.0.0 release. Until it does, we reserve the right to change the API between _minor_ versions (for example, between `0.2.0` and `0.3.0`), as described in the Semantic Version Specification[[1]][[2]]. +In contrast to the guarantees provided for the API of Swift OpenAPI Generator, as defined above, below is a list of behaviors that are _not_ considered API, and are explicitly consider an implementation detail that can change without prior warning: -> Tip: To avoid unexpected build issues, use `.upToNextMinor(from: "0.y.z")` in your `Package.swift` when declaring a dependency on Swift OpenAPI Generator packages (including the runtime and transport libraries). +- The number and names of files generated by the Swift OpenAPI Generator CLI and plugins. +- The private types and methods provided by the OpenAPIRuntime library for generated code (marked with `@_spi(Generated)`).
```suggestion - The SPI provided by the OpenAPIRuntime library used by generated code (marked with `@_spi(Generated)`). ```
swift-openapi-generator
github_2023
others
450
apple
simonjbeaumont
@@ -9,26 +9,27 @@ Swift OpenAPI Generator generates client and server Swift code from an OpenAPI d This document outlines the API stability goals for the generator to help you avoid unintentional build errors when updating to a new version of Swift OpenAPI Generator. The components covered by these rules are: -- the name of the Swift OpenAPI Generator package plugin -- the format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool) -- the Swift OpenAPI Generator CLI tool arguments +- The name of the Swift OpenAPI Generator package plugin. +- The format of the config file provided to Swift OpenAPI Generator (plugin or CLI tool). +- The Swift OpenAPI Generator CLI tool arguments, options, and flags. -If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied before 1.0 is released, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. +If you upgrade any of the components above to the next non-breaking version, your project should continue to build successfully. Check out how these rules are applied, and what a breaking change means for the generated code: <doc:API-stability-of-generated-code>. -### API stability for versions >= 1.0.0 +### API stability -After the project reaches 1.0.0, we will follow [Semantic Versioning 2.0.0][0]. +Since 1.0.0, the project follows [Semantic Versioning 2.0.0][0]. -### API stability for versions 0.y.z +### Implementation details -Swift OpenAPI Generator is being developed as an open source project. In order to accommodate feedback from the community, it does not yet have a 1.0.0 release. Until it does, we reserve the right to change the API between _minor_ versions (for example, between `0.2.0` and `0.3.0`), as described in the Semantic Version Specification[[1]][[2]]. +In contrast to the guarantees provided for the API of Swift OpenAPI Generator, as defined above, below is a list of behaviors that are _not_ considered API, and are explicitly consider an implementation detail that can change without prior warning: -> Tip: To avoid unexpected build issues, use `.upToNextMinor(from: "0.y.z")` in your `Package.swift` when declaring a dependency on Swift OpenAPI Generator packages (including the runtime and transport libraries). +- The number and names of files generated by the Swift OpenAPI Generator CLI and plugins. +- The private types and methods provided by the OpenAPIRuntime library for generated code (marked with `@_spi(Generated)`). +- The business logic of the generated code, any code that isn't part of the API of the generated code. +- The diagnostics emitted by the generator, both their severity and printed description.
This cannot be true since we have an `error`, right?
swift-openapi-generator
github_2023
others
449
apple
czechboy0
@@ -0,0 +1,88 @@ +# Tracing middleware using Swift OTel + +In this example we'll implement a `ClientMiddleware` and `ServerMiddleware` +that use `swift-otel` to emit traces for requests and responses. + +## Overview + +This example extends the [HelloWorldVaporServer](../HelloWorldVaporServer) +with a new target, `TracingMiddleware`, which is then used when creating +the `Server`. + +## Testing + +### Running the collector and visualization containers + +We'll use `Compose` We'll use [Compose](https://docs.docker.com/compose) to run
```suggestion We'll use [Compose](https://docs.docker.com/compose) to run ```
swift-openapi-generator
github_2023
others
449
apple
czechboy0
@@ -0,0 +1,48 @@ +// swift-tools-version:5.9 +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import PackageDescription + +let package = Package( + name: "TracingMiddleware", + platforms: [.macOS(.v13)], + dependencies: [ + .package(url: "https://github.com/apple/swift-openapi-generator", exact: "1.0.0-alpha.1"), + .package(url: "https://github.com/apple/swift-openapi-runtime", exact: "1.0.0-alpha.1"), + .package(url: "https://github.com/swift-server/swift-openapi-vapor", exact: "1.0.0-alpha.1"), + .package(url: "https://github.com/vapor/vapor", from: "4.87.1"), + .package(url: "https://github.com/apple/swift-distributed-tracing-extras", exact: "1.0.0-beta.1"), + .package(url: "https://github.com/slashmo/swift-otel", .upToNextMinor(from: "0.8.0")), + ], + targets: [ + .target( + name: "TracingMiddleware", + dependencies: [ + .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"), + .product(name: "OpenTelemetry", package: "swift-otel"), + .product(name: "OtlpGRPCSpanExporting", package: "swift-otel"),
```suggestion ``` I don't think these two are actually imported in the middleware?
swift-openapi-generator
github_2023
others
442
apple
simonjbeaumont
@@ -74,4 +74,11 @@ for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name --scratch-path "${SHARED_SCRATCH_PATH}" \ --cache-path "${SHARED_CACHE_PATH}" \ unedit swift-openapi-generator + + log "Deleting example ${EXAMPLE_PACKAGE_NAME} at ${EXAMPLE_COPY_DIR}" + rm -rf "${EXAMPLE_COPY_DIR}" done + +log "Deleting cache directories" +rm -rf "${SHARED_SCRATCH_PATH}" +rm -rf "${SHARED_CACHE_PATH}"
```suggestion log "Deleting temporary directory" rm -rf "${TMP_DIR}" ```
swift-openapi-generator
github_2023
others
442
apple
simonjbeaumont
@@ -47,31 +45,24 @@ for EXAMPLE_PACKAGE_PATH in $(find "${EXAMPLES_PACKAGE_PATH}" -maxdepth 2 -name log "Overriding dependency in ${EXAMPLE_PACKAGE_NAME} to use ${PACKAGE_PATH}" "${SWIFT_BIN}" package \ --package-path "${EXAMPLE_COPY_DIR}" \ - --scratch-path "${SHARED_SCRATCH_PATH}" \ - --cache-path "${SHARED_CACHE_PATH}" \ edit swift-openapi-generator \ --path "${PACKAGE_PATH}" log "Building example package: ${EXAMPLE_PACKAGE_NAME}" "${SWIFT_BIN}" build \ - --package-path "${EXAMPLE_COPY_DIR}" \ - --scratch-path "${SHARED_SCRATCH_PATH}" \ - --cache-path "${SHARED_CACHE_PATH}" + --package-path "${EXAMPLE_COPY_DIR}" log "βœ… Successfully built the example package ${EXAMPLE_PACKAGE_NAME}." if [ -d "${EXAMPLE_COPY_DIR}/Tests" ]; then log "Running tests for example package: ${EXAMPLE_PACKAGE_NAME}" "${SWIFT_BIN}" test \ - --package-path "${EXAMPLE_COPY_DIR}" \ - --scratch-path "${SHARED_SCRATCH_PATH}" \ - --cache-path "${SHARED_CACHE_PATH}" + --package-path "${EXAMPLE_COPY_DIR}" log "βœ… Passed the tests for the example package ${EXAMPLE_PACKAGE_NAME}." fi - log "Unediting dependency in ${EXAMPLE_PACKAGE_NAME}" - "${SWIFT_BIN}" package \ - --package-path "${EXAMPLE_COPY_DIR}" \ - --scratch-path "${SHARED_SCRATCH_PATH}" \ - --cache-path "${SHARED_CACHE_PATH}" \ - unedit swift-openapi-generator + log "Deleting example ${EXAMPLE_PACKAGE_NAME} at ${EXAMPLE_COPY_DIR}" + rm -rf "${EXAMPLE_COPY_DIR}" done + +log "Deleting temporary directory" +rm -rf "${TMP_DIR}"
I don't think this is necessary any more as we can see in the logs that the pipeline is run with `--rm` ```suggestion ```
swift-openapi-generator
github_2023
others
433
apple
simonjbeaumont
@@ -0,0 +1,43 @@ +// swift-tools-version:5.9 +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import PackageDescription + +let package = Package( + name: "RetryingClientMiddleware", + platforms: [.macOS(.v11), .iOS(.v14), .tvOS(.v14), .watchOS(.v7), .visionOS(.v1)],
Any reason for the platform bump?
swift-openapi-generator
github_2023
others
438
apple
czechboy0
@@ -29,22 +29,36 @@ chain. ## Testing -Run the client executable using:
Higher in this file you'll need to add that this is also a ServerMiddleware now, GitHub just doesn't allow me to comment there.
swift-openapi-generator
github_2023
others
438
apple
czechboy0
@@ -0,0 +1,46 @@ +# Logging Middleware using Swift Log + +In this example we'll implement a `ClientMiddleware` and `ServerMiddleware` +that use `swift-log` to log requests and responses. + +## Overview + +This example extends the [HelloWorldURLSessionClient](../HelloWorldURLSessionClient) +with a new target, `LoggingMiddleware`, which is then used when creating +the `Client`. + +The `LoggingMiddleware` provides two types: +- `LoggingClientMiddleware`, which implements the `OpenAPIRuntime.ClientMiddleware` protocol.
Names need updating.
swift-openapi-generator
github_2023
others
429
apple
simonjbeaumont
@@ -0,0 +1,74 @@ +@Tutorial(time: 5) { + @Intro(title: "Adding OpenAPI endpoints") {
```suggestion @Intro(title: "Adding OpenAPI and Swagger UI endpoints") { ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator.
```suggestion This guide explains walks through these two practices and describes how to migrate to a spec-driven development process to improve collaboration and consistency. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start.
```suggestion Starting with an API contract and iterating on it allows developers working on both sides of the API to be involved in the API design process from the start. Creating an OpenAPI document is no different, describing both the methods to call and the data structures of parameters and responses. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.)
```suggestion By starting with a draft of an OpenAPI document, both server and client teams can work in parallel as they write the code necessary to implement their portion of the API, gather feedback, and propose any iterations for future versions. After a stable version is released, take more care during iteration to avoid breaking changes until the next major version. For more information about supporting API stability, see <doc:API-stability-of-generated-code>. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client.
```suggestion An OpenAPI document supports client-side developers creating a mock server and start work on the client to provide feedback in parallel to server-side development. Without starting with an OpenAPI document, client-side developers are frequently forced to wait to provide input about the interface. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another.
```suggestion As a result, working from an OpenAPI specification first allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. ``` And I recommend merging this with the paragraph above, removing the empty line above
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors.
```suggestion Collaborate on the API definition, as opposed to code, to less expensively iterate on the OpenAPI document. Browse and edit OpenAPI documents using tools available in the broader OpenAPI community, with many that support syntax highlighting, autocompletion, and validation. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator.
```suggestion Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged. ``` There's nothing about this swift generator that discourages it - so that part seemed redundant.
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. +
merge these two sentences together into a paragraph
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes.
```suggestion While initially it can appear convenient, communications with client teams can quickly become confused without a formal description of the API. Additionally, as multiple teams provide feedback for an API service, there is no single point of truth for all the teams to reference, which slows down iteration. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then.
```suggestion Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle.
```suggestion A code-driven workflow prioritizes server-side development over client-side development, in contrast to spec-driven development, where they work as equal peers throughout the API lifecycle. ``` Recommend merging this up into the parargraph above
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development).
```suggestion For these reasons, use or migrate to a spec-driven development workflow. It allows all API stakeholders to work and iterate as peers. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients.
Most of this section has been arguing against against code-driven development, and this tip shifts dramatically in what it's talking about. I think it would make a lot more sense at the end of the spec-driven development section where it segues into talking about tooling available in the community. (roughly line 49 above) ```suggestion > Tip: When developing a service without having known clients, use integration tests and sample apps as your first "clients". Integration tests written against stubs generated by OpenAPI can simulate a separate team using the API, and can illustrate and feed back issues during the API design process. In addition to integration tests, prototyping a sample client app helps drive the end to end validation and usefulness in the absence of client teams. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties:
```suggestion In comparing the two possible workflows, as yourself the following questions: ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document.
```suggestion Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document. By inferring the specification from existing code, the resulting OpenAPI spec is often lossy and incomplete. Even with annotated code, It can be difficult to predict the OpenAPI output. Additionally, any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server.
```suggestion Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. ``` I think this is better as a final statement rather than trying to highlight it with a tip annotation
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase.
```suggestion This section is a step-by-step guide of that shows how to migrate an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development
This whole section and below could really be it's own individual article. If you end up wanting to reference is from elsewhere, that might be a preferable setup (information wise)
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints:
```suggestion This example starts with a [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things:
```suggestion Each request handler is responsible for three things: ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic.
```suggestion - b. Perform any logic specific to that handler. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you.
```suggestion The application-specific logic (b) is the core of the handler, while input (a) and output (c) handling is often repetitive code that the Swift OpenAPI Generator can generate for you. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this:
```suggestion To take advantage of the generator, create a new OpenAPI document with no paths in it, looking like this: ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints.
```suggestion The example above is a valid OpenAPI document that describes a service with no endpoints. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>.
```suggestion Save the initial spec to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development.
```suggestion At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. You've taken the first spec towards spec-driven development. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now.
```suggestion Migrate the first route, `GET /foo`, and leave the other two alone for now. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now. + +First, you add the definition for the route to the OpenAPI document, so it looks something like:
```suggestion First, add the definition for the route to the OpenAPI document, so it looks something like: ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now. + +First, you add the definition for the route to the OpenAPI document, so it looks something like: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: + /foo: + get: + ... (the definition of the operation, its inputs and outputs) +``` + +and comment out the first of the existing route implementations in your Vapor app:
```suggestion Comment out the first of the existing route implementations in your Vapor app: ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now. + +First, you add the definition for the route to the OpenAPI document, so it looks something like: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: + /foo: + get: + ... (the definition of the operation, its inputs and outputs) +``` + +and comment out the first of the existing route implementations in your Vapor app: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// app.get("foo") { ... a, b, c ... } // <<< just comment this out, and this route will be registered below by registerHandlers, as it is now defined by your OpenAPI document. +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // <<< this is where you now get a build error + +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +If you try to compile the above, you'll get a build error. Because now, the `APIProtocol` contains the requirement to implement the `getFoo` operation, but you're not implementing it, yet. Xcode will offer a Fix-it, and drop in a function stub that you just fill in:
```suggestion When you compile the example above, you'll get a build error because the `APIProtocol` contains the requirement to implement the `getFoo` operation, but it isn't yet implemented. Xcode will offer a Fix-it, and drop in a function stub that you can fill in: ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now. + +First, you add the definition for the route to the OpenAPI document, so it looks something like: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: + /foo: + get: + ... (the definition of the operation, its inputs and outputs) +``` + +and comment out the first of the existing route implementations in your Vapor app: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// app.get("foo") { ... a, b, c ... } // <<< just comment this out, and this route will be registered below by registerHandlers, as it is now defined by your OpenAPI document. +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // <<< this is where you now get a build error + +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +If you try to compile the above, you'll get a build error. Because now, the `APIProtocol` contains the requirement to implement the `getFoo` operation, but you're not implementing it, yet. Xcode will offer a Fix-it, and drop in a function stub that you just fill in: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// <<< now you can just delete the first original route, as you've moved the business logic below into the Handler type +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol { + func getFoo(input: Operations.getFoo.Input) async throws -> Operations.getFoo.Output { + ... b ... // <<< notice that here you just implement your business logic, but input deserialization and validation, and output serialization is handled by the generated code. + } +} +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +Now, build run, and test! + +Only one operation was moved over, but you can get confidence that it works and even deploy the service.
```suggestion Only one operation was moved over, but you test that it works and even deploy the service. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now. + +First, you add the definition for the route to the OpenAPI document, so it looks something like: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: + /foo: + get: + ... (the definition of the operation, its inputs and outputs) +``` + +and comment out the first of the existing route implementations in your Vapor app: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// app.get("foo") { ... a, b, c ... } // <<< just comment this out, and this route will be registered below by registerHandlers, as it is now defined by your OpenAPI document. +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // <<< this is where you now get a build error + +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +If you try to compile the above, you'll get a build error. Because now, the `APIProtocol` contains the requirement to implement the `getFoo` operation, but you're not implementing it, yet. Xcode will offer a Fix-it, and drop in a function stub that you just fill in: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// <<< now you can just delete the first original route, as you've moved the business logic below into the Handler type +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol { + func getFoo(input: Operations.getFoo.Input) async throws -> Operations.getFoo.Output { + ... b ... // <<< notice that here you just implement your business logic, but input deserialization and validation, and output serialization is handled by the generated code. + } +} +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +Now, build run, and test! + +Only one operation was moved over, but you can get confidence that it works and even deploy the service. + +#### Repeat for the remaining operations + +At this point, `POST /foo` and `GET /bar` are still manually implemented, but `GET /foo` is coming from your OpenAPI document and you only had to move the business logic over.
```suggestion At this point, `POST /foo` and `GET /bar` are still manually implemented, but `GET /foo` is coming from the OpenAPI document and you only had to move the business logic over. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now. + +First, you add the definition for the route to the OpenAPI document, so it looks something like: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: + /foo: + get: + ... (the definition of the operation, its inputs and outputs) +``` + +and comment out the first of the existing route implementations in your Vapor app: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// app.get("foo") { ... a, b, c ... } // <<< just comment this out, and this route will be registered below by registerHandlers, as it is now defined by your OpenAPI document. +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // <<< this is where you now get a build error + +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +If you try to compile the above, you'll get a build error. Because now, the `APIProtocol` contains the requirement to implement the `getFoo` operation, but you're not implementing it, yet. Xcode will offer a Fix-it, and drop in a function stub that you just fill in: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// <<< now you can just delete the first original route, as you've moved the business logic below into the Handler type +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol { + func getFoo(input: Operations.getFoo.Input) async throws -> Operations.getFoo.Output { + ... b ... // <<< notice that here you just implement your business logic, but input deserialization and validation, and output serialization is handled by the generated code. + } +} +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +Now, build run, and test! + +Only one operation was moved over, but you can get confidence that it works and even deploy the service. + +#### Repeat for the remaining operations + +At this point, `POST /foo` and `GET /bar` are still manually implemented, but `GET /foo` is coming from your OpenAPI document and you only had to move the business logic over. + +At your convenience, repeat this for the remaining two operations, until you have no manual operations (or feel free to keep some manual operations there, for example for serving static css/js files, those endpoints usually don't go into the OpenAPI document, which is meant mainly for the REST API).
```suggestion Repeat this for the remaining two operations, until there are no manual operations with business logic. Endpoints that provide static content, such as css or javascript files, are not usually considered part of the API, so they don't go into an OpenAPI document. ```
swift-openapi-generator
github_2023
others
420
apple
heckj
@@ -0,0 +1,259 @@ +# Practicing spec-driven API development + +Design, iterate on, and generate both client and server code from your hand-written OpenAPI document. + +## Overview + +An OpenAPI document represents a machine-readable _contract_ between a server and its clients. + +There are two high-level workflows of creating and using the OpenAPI document: + +- **Spec-driven development**: + - OpenAPI document is hand-written. + - Client and server code is generated. +- **Code-driven development**: + - Server code is hand-written. + - OpenAPI document and client code are generated. + +This guide explains why spec-driven development is the recommended practice for use with Swift OpenAPI Generator. + +### (Recommended) Spec-driven development + +Starting with an API contract, before any server or client code is written, allows both the server and client teams to be involved in the API design process from the start. + +The goal is to draft the initial OpenAPI document, then let both server and client teams work in parallel as they write the code necessary to implement their side, gather feedback, and propose the next version. This cycle never ends, however after a stable version is released, more care needs to be taken to avoid breaking changes until the next major version (learn more about API stability in <doc:API-stability-of-generated-code>.) + +Having the OpenAPI document written before the server team writes any code allows the client team to spin up a mock server that follows the proposed API, and start work on the client. + +Unblocking client teams allows for quicker iteration than a code-driven workflow, as there is less waiting of teams for one another. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β–Άβ”‚ Server Implementation β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”œβ”€β”€β”€β”€β–Άβ”‚ App Client β”‚ + β”‚ OpenAPI Document │────── β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”œβ”€β”€β”€β”€β–Άβ”‚ Web Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └────▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +Swift OpenAPI Generator generates both the client and server stub code, helping ensure that the implementation of both sides follow the agreed-upon OpenAPI document. + +Collaborating on the API definition, as opposed to code, allows inexpensive iteration on the OpenAPI document. It is "just" a YAML or JSON file, after all, made easy to browse and edit using tools available in the broader OpenAPI community, offering syntax highlighting, autocompletion, and validation in many popular text editors. + +### (Discouraged) Code-driven development + +Code-driven development, or in other words, writing server code first, and generating the OpenAPI document from it, is discouraged for use with Swift OpenAPI Generator. + +While initially it can appear convenient, as server developers start writing code without having an agreed API contract first, it quickly slows down the iteration cycle as soon as clients get involed and start proposing changes. + +``` + β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + β”Œβ”€β”€β–Άβ”‚ App Client β”‚ + β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” +β”‚ Server Implementation │──────▢│ OpenAPI Document │───┼──▢│ Web Client β”‚ +β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ + β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” + └──▢│ ... β”‚ + β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ +``` + +In code-driven development, there isn't a convenient way for clients to propose API changes in an unambiguous, machine-readable way. They would have to get access to the source code of the server, understand how it's implemented, and make changes to it in a way that produces the desired change to the OpenAPI document. + +A code-driven workflow prioritizes server developers at the cost of their clients, in contrast to spec-driven development, where the server and client developers work as equal peers throughout the API lifecycle. + +Code-driven development also doesn't allow client teams to prototype their components until the server developers wrote at least enough code to generate the OpenAPI document, further limiting parallelization and delaying important learnings, making feedback more difficult to integrate as more code has already been written by then. + +For this reason, code-driven development is discouraged for use with Swift OpenAPI Generator, and should be replaced by spec-driven development, which allows all API stakeholders to work as peers from the beginning. To learn about migrating to spec-driven incrementally, check out [this later section](#Migrate-from-code-driven-to-spec-driven-development). + +> Tip: When developing a service without having known clients yet, use integration tests and sample apps as your first "clients". The integration tests should not use any code from the server implementation, and can thus simulate a separate team trying to use the provided service API. Writing the integration tests can inform the server team of usability issues early and feed back into the API design process. In addition to integration tests, prototyping a sample client app can also help simulate the experience of client teams in the absence of real-world API clients. + +### Publish the source of truth + +Compare the workflows based on the following two properties: +1. What is the source of truth for the API? In other words, what is the representation that developers edit by hand? +2. What is the representation that the server provider publishes for the client, who consume it either through tooling or by directly reading it? + +| Workflow | Source of truth | Published | Transcoding | +|----------|-----------------|-----------|-------------| +| Spec-driven | OpenAPI doc | OpenAPI doc | None required βœ… | +| Code-driven | Code | OpenAPI doc | Can be lossy and unpredictable ❌ | + +Notice from the table above that the recommended spec-driven workflow publishes the same document that the developers of the server use to define the server's API (source of truth). + +Publishing the source of truth is preferable to relying on transcoding from code (or other representations) to an OpenAPI document, which is often lossy and difficult to predict how a given language-specific annotation affects the OpenAPI output. It also means that any feature unsupported by the transcoder cannot be represented in the generated OpenAPI document. + +> Tip: Publish the source of truth, not a representation transcoded from the source of truth. That way, your clients can open pull requests to your OpenAPI document without having to learn how your server is implemented, nor do they need access to the source code of your server. + +### Migrate from code-driven to spec-driven development + +> SeeAlso: Check out the [server development](https://developer.apple.com/wwdc23/10171?time=972) section of the WWDC session or the server tutorial (<doc:ServerSwiftPM>) before reading this section. + +This section is a step-by-step guide of migrating an example service from code-driven to spec-driven development incrementally, one operation at a time. Migrating incrementally helps reduce risk of large code changes and allows you to evaluate and improve the workflow before migrating your whole codebase. + +#### Initial state + +Let's assume you're starting with a hand-written [Vapor](https://github.com/vapor/vapor) server that has 3 endpoints: +- `GET /foo` +- `POST /foo` +- `GET /bar` + +So your existing server might look something like: + +```swift +let app = Vapor.Application() +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } +try app.run() +``` + +In each request handler, you have to do 3 things: +- a. Parse and validate inputs from a raw `Vapor.Request`. +- b. Perform your handler-specific logic. +- c. Serialize outputs into a raw `Vapor.Response`. + +The application-specific logic is (b), while (a) and (c) can be repetitive code, which Swift OpenAPI Generator can generate for you. + +#### Configure the generator plugin + +To take advantage of the generator, first create a new OpenAPI document with no paths in it, looking like this: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: {} +``` + +This is a valid OpenAPI document, one that describes a server with no endpoints. + +Save it to `Sources/MyServer/openapi.yaml` and then follow the tutorial of configuring the Swift OpenAPI Generator for a server project: <doc:ServerSwiftPM>. + +As you go through the tutorial, the important part is that you only _add_ the generated handlers _to your existing Vapor app_ instead of creating a new Vapor app. + +After this step, your code looks something like this: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +app.get("foo") { ... a, b, c ... } +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // this is where you'll implement your logic in the next step + +let transport = VaporTransport(routesBuilder: app) +// Registers your generated routes from the OpenAPI document. Right now, there are 0. +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +At this point, you have two sets of endpoints, your existing 3 ones, and 0 generated once (because your OpenAPI document is still empty). Now you can commit and push the changes, and none of your existing code should be affected. But you've already taken the first spec towards spec-driven development. + +#### Move over the first operation + +Let's migrate the first route, `GET /foo`, and leave the other two alone for now. + +First, you add the definition for the route to the OpenAPI document, so it looks something like: + +```yaml +openapi: 3.1.0 +info: + title: MyService + version: 1.0.0 +paths: + /foo: + get: + ... (the definition of the operation, its inputs and outputs) +``` + +and comment out the first of the existing route implementations in your Vapor app: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// app.get("foo") { ... a, b, c ... } // <<< just comment this out, and this route will be registered below by registerHandlers, as it is now defined by your OpenAPI document. +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol {} // <<< this is where you now get a build error + +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +If you try to compile the above, you'll get a build error. Because now, the `APIProtocol` contains the requirement to implement the `getFoo` operation, but you're not implementing it, yet. Xcode will offer a Fix-it, and drop in a function stub that you just fill in: + +```swift +let app = Vapor.Application() + +// Registers your existing routes. +// <<< now you can just delete the first original route, as you've moved the business logic below into the Handler type +app.post("foo") { ... a, b, c ... } +app.get("bar") { ... a, b, c ... } + +struct Handler: APIProtocol { + func getFoo(input: Operations.getFoo.Input) async throws -> Operations.getFoo.Output { + ... b ... // <<< notice that here you just implement your business logic, but input deserialization and validation, and output serialization is handled by the generated code. + } +} +let transport = VaporTransport(routesBuilder: app) +try handler.registerHandlers(on: transport, serverURL: ...) + +try app.run() +``` + +Now, build run, and test! + +Only one operation was moved over, but you can get confidence that it works and even deploy the service. + +#### Repeat for the remaining operations + +At this point, `POST /foo` and `GET /bar` are still manually implemented, but `GET /foo` is coming from your OpenAPI document and you only had to move the business logic over. + +At your convenience, repeat this for the remaining two operations, until you have no manual operations (or feel free to keep some manual operations there, for example for serving static css/js files, those endpoints usually don't go into the OpenAPI document, which is meant mainly for the REST API). + +#### Final state + +You should end up with something like this:
```suggestion The end result should be something like this: ```
swift-openapi-generator
github_2023
others
431
apple
czechboy0
@@ -0,0 +1,118 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import OpenAPIRuntime +import Foundation +import HTTPTypes +import OSLog + +package actor LoggingMiddleware: ClientMiddleware { + + package enum BodyLoggingPolicy { + /// Never log request or response bodies. + case never + /// Log request and response bodies that have a known length less than or equal to `maxBytes`. + case upTo(maxBytes: Int) + } + + private let logger: Logger + var bodyLoggingPolicy: BodyLoggingPolicy
Since it's an actor and the parameter comes in the initializer, might make sense to also be `private let`.
swift-openapi-generator
github_2023
others
431
apple
czechboy0
@@ -0,0 +1,118 @@ +//===----------------------------------------------------------------------===// +// +// This source file is part of the SwiftOpenAPIGenerator open source project +// +// Copyright (c) 2023 Apple Inc. and the SwiftOpenAPIGenerator project authors +// Licensed under Apache License v2.0 +// +// See LICENSE.txt for license information +// See CONTRIBUTORS.txt for the list of SwiftOpenAPIGenerator project authors +// +// SPDX-License-Identifier: Apache-2.0 +// +//===----------------------------------------------------------------------===// +import OpenAPIRuntime +import Foundation +import HTTPTypes +import OSLog + +package actor LoggingMiddleware: ClientMiddleware { + + package enum BodyLoggingPolicy { + /// Never log request or response bodies. + case never + /// Log request and response bodies that have a known length less than or equal to `maxBytes`. + case upTo(maxBytes: Int) + } + + private let logger: Logger + var bodyLoggingPolicy: BodyLoggingPolicy + + package init( + logger: Logger = defaultLogger, + bodyLoggingConfiguration: BodyLoggingPolicy = .never + ) { + self.logger = logger + self.bodyLoggingPolicy = bodyLoggingConfiguration + } + + package func intercept( + _ request: HTTPRequest, + body: HTTPBody?, + baseURL: URL, + operationID: String, + next: (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?) + ) async throws -> (HTTPResponse, HTTPBody?) { + + let (requestBodyToLog, requestBodyForNext) = try await processBodyForLogging(body) + logger.debug("Request: \(request.method, privacy: .public) \(request.path ?? "<nil>", privacy: .public) body: \(requestBodyToLog, privacy: .auto)") + + do { + let (response, responseBody) = try await next(request, requestBodyForNext, baseURL) + let (responseBodyToLog, responseBodyForNext) = try await processBodyForLogging(responseBody) + + logger.debug("Response: \(request.method, privacy: .public) \(request.path ?? "<nil>", privacy: .public) \(response.status, privacy: .public) body: \(responseBodyToLog, privacy: .auto)") + + return (response, responseBodyForNext) + } catch { + Logger().warning("Request failed. Error: \(error.localizedDescription)")
```suggestion logger.warning("Request failed. Error: \(error.localizedDescription)") ```
swift-openapi-generator
github_2023
others
431
apple
czechboy0
@@ -0,0 +1,50 @@ +# Client Logging Middleware using OSLog + +In this example we'll implement a `ClientMiddleware` that uses `OSLog` to log +requests and responses. + +## Overview + +This example extends the [HelloWorldURLSessionClient](../HelloWorldURLSessionClient) +with a new target, `LoggingClientMiddleware`, which is then used when creating +the `Client`. + +Because request and response bodies support streaming and can be arbitrarily +large, the middleware is configured with a logging policy; one of: + +- `never`: Never log request or response bodies. +- `upTo(maxBytes)`: Logs request and response bodies only if they have a known + length that is less than `maxBytes`.
```suggestion length that is less than or equal to `maxBytes`. ```
swift-openapi-generator
github_2023
others
426
apple
czechboy0
@@ -0,0 +1,95 @@ +# Use a database for persistent storage + +In this example we'll integrate persistent state into the server by adding an +integration to a database. + +## Overview + +This example extends the [HelloWorldVaporServer](../HelloWorldVaporServer/) +with a trivial API to return the number of messages it has received. + +For persistent state, it makes use of a local Postgres database to store the +messages and uses [PostgresNIO](https://github.com/vapor/postgres-nio) for the +database interaction. + +The type that provides the API handlers has been converted an actor and
```suggestion The type that provides the API handlers has been converted to an actor and ```
swift-openapi-generator
github_2023
others
426
apple
czechboy0
@@ -0,0 +1,95 @@ +# Use a database for persistent storage + +In this example we'll integrate persistent state into the server by adding an +integration to a database. + +## Overview + +This example extends the [HelloWorldVaporServer](../HelloWorldVaporServer/) +with a trivial API to return the number of messages it has received. + +For persistent state, it makes use of a local Postgres database to store the +messages and uses [PostgresNIO](https://github.com/vapor/postgres-nio) for the +database interaction. + +The type that provides the API handlers has been converted an actor and +a database connection is established in the initializer. The Postgres API +requires a logger for all queries so a logger property has also been added. + +The server uses a table called `messages` to record the messages the server +responds with. This table is created if it does not already exist in the +initializer. + +In the `getGreeting` handler, a row is inserted into the `messages` table +containing the message before returning a response. + +This example also includes two other API operations: `getCount`, which returns +the number of messages the server has provided; and `reset`, which resets the +database. + +## Testing + +### Running a local database container + +We need a database running locally to use in this exercise. We'll use Compose
```suggestion We need a database running locally to use in this exercise. We'll use [Compose](https://docs.docker.com/compose/) ```
swift-openapi-generator
github_2023
others
426
apple
czechboy0
@@ -0,0 +1,95 @@ +# Use a database for persistent storage + +In this example we'll integrate persistent state into the server by adding an +integration to a database. + +## Overview + +This example extends the [HelloWorldVaporServer](../HelloWorldVaporServer/) +with a trivial API to return the number of messages it has received. + +For persistent state, it makes use of a local Postgres database to store the +messages and uses [PostgresNIO](https://github.com/vapor/postgres-nio) for the +database interaction. + +The type that provides the API handlers has been converted an actor and +a database connection is established in the initializer. The Postgres API +requires a logger for all queries so a logger property has also been added. + +The server uses a table called `messages` to record the messages the server +responds with. This table is created if it does not already exist in the +initializer. + +In the `getGreeting` handler, a row is inserted into the `messages` table +containing the message before returning a response. + +This example also includes two other API operations: `getCount`, which returns +the number of messages the server has provided; and `reset`, which resets the +database. + +## Testing + +### Running a local database container + +We need a database running locally to use in this exercise. We'll use Compose +to run Postgres locally: + +```console +% docker compose start +... +[+] Running 1/1 + β Ώ Container postgresdatabaseserver-postgres-1 Started 0.4s +``` + +### Testing the server + +Run the server locally using the following command: + +```console +% swift run +``` + +Then, in another terminal, make requests and see the database in action.
```suggestion Then, in another Terminal window, make requests and see the database in action. ```