- Notifications
You must be signed in to change notification settings - Fork146
Generate Swift client and server code from an OpenAPI document.
License
apple/swift-openapi-generator
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
Generate Swift client and server code from an OpenAPI document.
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.
- 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 ofexample projects.
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 thestep-by-step tutorials.
The generatedClient
type provides a method for each HTTP operation defined in the OpenAPI document1 and can be used with any HTTP library that provides an implementation ofClientTransport
.
import OpenAPIURLSessionimport Foundationletclient=Client( serverURL:URL(string:"http://localhost:8080/api")!, transport:URLSessionTransport())letresponse=tryawait client.getGreeting()print(try response.ok.body.json.message)
To implement a server, define a type that conforms to the generatedAPIProtocol
, providing a method for each HTTP operation defined in the OpenAPI document1.
The server can be used with any web framework that provides an implementation ofServerTransport
, which allows you to register your API handlers with the HTTP server.
import OpenAPIRuntimeimport OpenAPIVaporimport VaporstructHandler:APIProtocol{func getGreeting(_ input:Operations.GetGreeting.Input)asyncthrows->Operations.GetGreeting.Output{letname= input.query.name??"Stranger"return.ok(.init(body:.json(.init(message:"Hello,\(name)!"))))}}@mainstructHelloWorldVaporServer{staticfunc main()asyncthrows{letapp=tryawaitApplication.make()lettransport=VaporTransport(routesBuilder: app)lethandler=Handler()try handler.registerHandlers(on: transport, serverURL:URL(string:"/api")!)tryawait app.execute()}}
The Swift OpenAPI Generator project is split across multiple repositories to enable extensibility and minimize dependencies in your project.
Repository | Description |
---|---|
apple/swift-openapi-generator | Swift package plugin and CLI |
apple/swift-openapi-runtime | Runtime library used by the generated code |
apple/swift-openapi-urlsession | ClientTransport usingURLSession |
swift-server/swift-openapi-async-http-client | ClientTransport usingAsyncHTTPClient |
swift-server/swift-openapi-vapor | ServerTransport usingVapor |
swift-server/swift-openapi-hummingbird | ServerTransport usingHummingbird |
swift-server/swift-openapi-lambda | ServerTransport usingAWS Lambda |
Generator versions | Supported OpenAPI versions | Minimum Swift version |
---|---|---|
1.0.0 ...main | 3.0, 3.1 | 5.9 |
See alsoSupported OpenAPI features.
The generator is used during development and is supported on macOS, Linux, and Windows.
The generated code, runtime library, and transports are supported on moreplatforms, listed below.
Component | macOS | Linux, Windows | iOS | tvOS | watchOS | visionOS |
---|---|---|---|---|---|---|
Generator plugin and CLI | ✅ 10.15+ | ✅ | ✖️ | ✖️ | ✖️ | ✖️ |
Generated code and runtime library | ✅ 10.15+ | ✅ | ✅ 13+ | ✅ 13+ | ✅ 6+ | ✅ 1+ |
Note
When using Visual Studio Code or other editors that rely onSourceKit-LSP, the editor may not correctly recognize generated code within the same module. As a workaround, consider creating a separate target for code generation and then importing it into your main module. For more details, see the discussion inswiftlang/sourcekit-lsp#665.
To get started, check out thedocumentation, which containsstep-by-step tutorials.
You can also experiment withexample projects that useSwift OpenAPI Generator and integrate with other packages in the ecosystem.
Or if you prefer to watch a video, check outMeet Swift OpenAPIGenerator from WWDC23.
Footnotes
- ↩↩2
Example OpenAPI document (click to expand)
openapi: '3.1.0'info: title: GreetingService version: 1.0.0servers: - url: https://example.com/api description: Example service deployment.paths: /greet: get: operationId: getGreeting parameters: - name: name required: false in: query description: The name used in the returned greeting. schema: type: string responses: '200': description: A success response with a greeting. content: application/json: schema: $ref: '#/components/schemas/Greeting'components: schemas: Greeting: type: object description: A value with the greeting contents. properties: message: type: string description: The string representation of the greeting. required: - message
About
Generate Swift client and server code from an OpenAPI document.
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Uh oh!
There was an error while loading.Please reload this page.