### Run Server Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/shared-types-client-server-example/README.md Build and run the server module of the example project. Ensure the server is running before executing the client. ```console % swift run hello-world-server Build complete! ... info HummingBird : [HummingbirdCore] Server started and listening on 127.0.0.1:8080 ``` -------------------------------- ### Run Client Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/shared-types-client-server-example/README.md Build and run the client module of the example project. This client interacts with the running server. ```console % swift run hello-world-client Build complete! +------------------+ |+------------------+| ||Hello, Stranger!|| |+------------------+| +------------------+ ``` -------------------------------- ### Clone and Run Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/README.md Instructions for cloning the repository and running a specific example locally using Swift Package Manager. ```console % git clone https://github.com/apple/swift-openapi-generator % cd swift-openapi-generator/Examples % swift run --package-path hello-world-urlsession-client-example ``` -------------------------------- ### Initial Vapor App Setup with Manual Routes Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Articles/Practicing-spec-driven-API-development.md This Swift code shows the initial Vapor application setup before migrating routes. Existing routes are registered manually, and the first route ('GET /foo') is commented out to prepare for OpenAPI integration. ```swift let app = try await Vapor.Application.make() // 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 await app.execute() ``` -------------------------------- ### Producing a Multipart Body (Initial Example) Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0009.md An initial example demonstrating how to construct a `MultipartBody` for a client sending a multipart request or a server sending a multipart response. ```swift let multipartBody: OpenAPIRuntime.MultipartBody = ... let response = try await client.uploadPhoto(body: multipartBody) // ... ``` -------------------------------- ### Example OpenAPI Document Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Swift-OpenAPI-Generator.md This is an example OpenAPI 3.1.0 document defining a GreetingService with a GET /greet endpoint. ```yaml openapi: '3.1.0' info: title: GreetingService version: 1.0.0 servers: - url: https://example.com/api description: Example service deployment. paths: /greet: get: operationId: getGreeting parameters: - name: name required: false in: query description: The name used in the returned greeting. schema: type: string responses: '200': description: A success response with a greeting. content: application/json: schema: $ref: '#/components/schemas/Greeting' components: schemas: Greeting: type: object description: A value with the greeting contents. properties: message: type: string description: The string representation of the greeting. required: - message ``` -------------------------------- ### Build and run the server Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/hello-world-hummingbird-server-example/README.md Execute the server CLI to start the Hummingbird service on the local machine. ```console % swift run 2023-12-01T14:14:35+0100 info HummingBird : [HummingbirdCore] Server started and listening on 127.0.0.1:8080 ... ``` -------------------------------- ### Start Tracing Infrastructure Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/tracing-middleware-example/README.md Use Docker Compose to launch the tracing collector and visualization containers. ```console % docker compose -f docker/docker-compose.yaml up [+] Running 4/4 ⠿ Network tracingmiddleware_exporter Created 0.1s ⠿ Container tracingmiddleware-jaeger-1 Created 0.3s ⠿ Container tracingmiddleware-zipkin-1 Created 0.4s ⠿ Container tracingmiddleware-otel-collector-1 Created 0.2s ... ``` -------------------------------- ### act Configuration File Example Source: https://github.com/apple/swift-openapi-generator/blob/main/CONTRIBUTING.md Example content for an '.actrc' file to configure default flags for the 'act' tool, such as container architecture, remote name, and offline mode. ```bash --container-architecture=linux/amd64 --remote-name upstream --action-offline-mode ``` -------------------------------- ### OpenAPI 3.1.0 Specification Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server-openapi-endpoints.console.2.txt This is an example of an OpenAPI 3.1.0 specification file. It defines API information, server URLs, and paths, including an example for a 'getGreeting' operation. ```yaml openapi: '3.1.0' info: title: GreetingService version: 1.0.0 servers: - url: https://example.com/api description: Example service deployment. paths: /greet: get: operationId: getGreeting parameters: - name: name ``` -------------------------------- ### Example Bug Report Structure Source: https://github.com/apple/swift-openapi-generator/blob/main/CONTRIBUTING.md An example of how to structure a bug report, including commit hash, context, reproduction steps, and system information. ```text Commit hash: b17a8a9f0f814c01a56977680cb68d8a779c951f Context: While testing my application that uses with swift-openapi-generator, I noticed that ... Steps to reproduce: 1. ... 2. ... 3. ... 4. ... $ swift --version Swift version 4.0.2 (swift-4.0.2-RELEASE) Target: x86_64-unknown-linux-gnu Operating system: Ubuntu Linux 16.04 64-bit $ uname -a Linux beefy.machine 4.4.0-101-generic #124-Ubuntu SMP Fri Nov 10 18:29:59 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux My system has IPv6 disabled. ``` -------------------------------- ### Build and Run Server CLI Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/event-streams-server-example/README.md Instructions to build and run the server application using Swift Package Manager. The output shows the server starting on the default address. ```console % swift run 2023-12-01T14:14:35+0100 notice codes.vapor.application : [Vapor] Server starting on http://127.0.0.1:8080 ... ``` -------------------------------- ### Start local database container Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/postgres-database-example/README.md Use Docker Compose to initiate the local Postgres database instance. ```console % docker compose start ... [+] Running 1/1 ⠿ Container postgresdatabaseserver-postgres-1 Started 0.4s ``` -------------------------------- ### Example API Call with Curl Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Articles/API-stability-of-generated-code.md This example demonstrates how to make an API call using curl to a hypothetical endpoint, including query parameters and receiving a JSON response. ```console % curl http://example.com/api/hello/Maria?greeting=Howdy { "message": "Howdy, Maria!" } ``` -------------------------------- ### Build and Run Client CLI Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/bidirectional-event-streams-client-example/README.md Use this command to build and execute the client command-line interface for the bidirectional event streams example. ```console swift run ``` -------------------------------- ### Client CLI Usage Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/retrying-middleware-example/README.md Shows the expected output when running the client CLI with the retrying middleware enabled. Demonstrates retry attempts and final response. ```text % swift run Attempt 1 Retrying with code 500 Attempt 2 Returning the received response, either because of success or ran out of attempts. Hello, Stranger! ``` -------------------------------- ### Initial OpenAPI Document Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Articles/Practicing-spec-driven-API-development.md A minimal valid OpenAPI document with no paths, used as a starting point for migration. ```yaml openapi: 3.1.0 info: title: MyService version: 1.0.0 paths: {} ``` -------------------------------- ### Create and Consume MultipartBody Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0009.md Examples for initializing MultipartBody from arrays, async sequences, or streams, and consuming it as an async sequence. ```swift let body: MultipartBody = [ .myCaseA(...), .myCaseB(...), ] ``` ```swift let producingSequence = ... // an AsyncSequence of MyPartType let body = MultipartBody( producingSequence, iterationBehavior: .single // or .multiple ) ``` ```swift let (stream, continuation) = AsyncStream.makeStream(of: MyPartType.self) // Pass the continuation to another task that produces the parts asynchronously. Task { continuation.yield(.myCaseA(...)) // ... later continuation.yield(.myCaseB(...)) continuation.finish() } let body = MultipartBody(stream) ``` ```swift let multipartBody: MultipartBody = ... for try await part in multipartBody { switch part { case .myCaseA(let myCaseAValue): // Handle myCaseAValue. case .myCaseB(let myCaseBValue): // Handle myCaseBValue, which is a raw type with a streaming part body. // // Option 1: Process the part body bytes in chunks. for try await bodyChunk in myCaseBValue.body { // Handle bodyChunk. } // Option 2: Accumulate the body into a byte array. // (For other convenience initializers, check out ``HTTPBody``. let fullPartBody = try await [UInt8](collecting: myCaseBValue.body, upTo: 1024) // ... } } ``` -------------------------------- ### Initial Vapor Server State Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Articles/Practicing-spec-driven-API-development.md The starting point for a Vapor application with manually defined routes. ```swift let app = try await Vapor.Application.make() app.get("foo") { ... a, b, c ... } app.post("foo") { ... a, b, c ... } app.get("bar") { ... a, b, c ... } try await app.execute() ``` -------------------------------- ### GET /greet Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0007.md Retrieves a personalized greeting. ```APIDOC ## GET /greet ### Description Retrieves a personalized greeting. ### Method GET ### Endpoint /greet ### Parameters #### Query Parameters - **name** (string) - Optional - A name used in the returned greeting. ### Response #### Success Response (200) - **message** (string) - The greeting message. #### Response Example ```json { "message": "Hello, World!" } ``` ``` -------------------------------- ### Example Curl Request for Authentication Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/auth-server-middleware-example/README.md This command demonstrates how to make a curl request to the server with an Authorization header to test the authentication middleware. ```bash % curl -H 'Authorization: token_for_Frank' 'http://localhost:8080/api/greet?name=Jane' { "message" : "Hello, Jane! (Requested by: Frank)" } ``` -------------------------------- ### Perform API call via terminal Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0007.md Example of a curl command to interact with the greeting API. ```console % curl 'localhost:8080/api/greet?name=Maria' { "message" : "Hello, Maria" } ``` -------------------------------- ### Test API Endpoint with curl Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/event-streams-server-example/README.md This command-line example demonstrates how to interact with the server's API endpoint for greetings, which returns a stream of JSON objects. ```console % curl -N http://127.0.0.1:8080/api/greetings\?name\=CLI\&count\=3 {"message":"Hey, CLI!"} {"message":"Hello, CLI!"} {"message":"Greetings, CLI!"} ``` -------------------------------- ### Client-side Accept Header Invocation Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0003.md Example of setting the accept header on a client request to specify content type preferences. ```swift let response = try await client.getStats(.init( headers: .init(accept: [ .init(contentType: .json), .init(contentType: .plainText, quality: 0.5) ]) )) ``` -------------------------------- ### Interact with Server API Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/various-content-types-server-example/README.md Example of how to interact with the server's API using curl to fetch JSON data. This demonstrates a typical client request to the server. ```console % curl http://localhost:8080/api/exampleJSON { "message" : "Hello, Stranger!" } ``` -------------------------------- ### Type-Safe API Usage Examples Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0012.md Demonstrates how to use the generated type-safe URL builder and how the compiler catches invalid enum values. ```swift let url = try Servers.Server1.url() // ✅ compiles let url = try Servers.Server1.url(environment: .default) // ✅ compiles let url = try Servers.Server1.url(environment: .staging) // ✅ compiles let url = try Servers.Server1.url(environment: .stg) // ❌ compiler error, 'stg' not defined on the enum ``` -------------------------------- ### Run CI Job with Bind Mount using act Source: https://github.com/apple/swift-openapi-generator/blob/main/CONTRIBUTING.md Execute a CI job locally with 'act' using a bind mount for the working directory, allowing changes to be reflected directly. This example runs the 'formatting' job. ```bash % act --bind workflow_call -j soundness --input format_check_enabled=true ``` -------------------------------- ### Server URL Definition Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0007.md Provides a method to construct a URL for the example server. Throws an error if the URL is invalid. ```swift /// Server URLs defined in the OpenAPI document. public enum Servers { /// Example public static func server1() throws -> URL { try URL(validatingOpenAPIServerURL: "https://example.com/api") } } ``` -------------------------------- ### Example OpenAPI Generator Configuration with Filtering Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0008.md Illustrates how to configure Swift OpenAPI Generator to filter operations by tags. This configuration is placed in 'openapi-generator-config.yaml'. ```yaml # openapi-generator-config.yaml generate: - types - client filter: tags: - issues ``` -------------------------------- ### Runtime Validation Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0012.md This Swift code demonstrates how an adopter might currently use a generated server URL function, relying on runtime checks for validation. An invalid environment string like 'stg' would only be caught during execution. ```swift let serverURL = try Servers.server1(environment: "stg") // might be a valid environment, might not ``` -------------------------------- ### Example log output from log stream Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/logging-middleware-oslog-example/README.md Observe the logged request and response details, including the HTTP method, status code, and body content (if within the logging policy limits). This output confirms the middleware is functioning as expected. ```console % log stream --debug --info --style compact --predicate subsystem == 'com.apple.swift-openapi' Filtering the log data using "subsystem == "com.apple.swift-openapi"" Timestamp Ty Process[PID:TID] 2023-12-07 17:09:20.256 Db HelloWorldURLSessionClient[32556:bdad678] [com.apple.swift-openapi:logging-middleware] Request: GET /greet body: 2023-12-07 17:09:20.429 Db HelloWorldURLSessionClient[32556:bdad67a] [com.apple.swift-openapi:logging-middleware] Response: GET /greet 200 body: { "message" : "Hello, Stranger!" } ^C ``` -------------------------------- ### Run Docker Compose Application Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/metrics-middleware-example/README.md Build and run the Docker Compose application to start the API server and Prometheus. Keep this terminal open to maintain the running services. ```console % docker compose up [+] Building 12/122 ... [+] Running 2/0 ⠿ Container metricsmiddleware-prometheus-1 Created 0.0s ⠿ Container metricsmiddleware-api-1 Created 0.0s ... metricsmiddleware-api-1 | 2023-06-08T14:34:24+0000 notice codes.vapor.application : [Vapor] Server starting on http://0.0.0.0:8080 ... metricsmiddleware-prometheus-1 | ts=2023-06-08T14:34:24.914Z caller=web.go:562 level=info component=web msg="Start listening for connections" address=0.0.0.0:9090 ... ``` -------------------------------- ### Define Acceptable Content Types in OpenAPI Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0003.md Example OpenAPI specification defining multiple content types for a GET operation. ```yaml /stats: get: operationId: getStats responses: '200': description: A successful response with stats. content: application/json: schema: ... text/plain: {} ``` -------------------------------- ### Configure and build integration tests Source: https://github.com/apple/swift-openapi-generator/blob/main/IntegrationTest/README.md Use these commands to clone the repository, link a local runtime checkout, and build the project. ```console % git clone https://github.com/apple/swift-openapi-generator % cd swift-openapi-generator/IntegrationTests % swift package edit swift-openapi-runtime path/to/checkout/of/swift-openapi-runtime % swift build ``` -------------------------------- ### Unfiltered OpenAPI Document Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0008.md An example of an unfiltered OpenAPI 3.1.0 document, including definitions for tags, paths, operations, schemas, and responses. ```yaml # unfiltered OpenAPI document openapi: 3.1.0 info: title: ExampleService version: 1.0.0 tags: - name: t paths: /things/a: get: operationId: getA tags: - t responses: 200: $ref: '#/components/responses/A' delete: operationId: deleteA responses: 200: $ref: '#/components/responses/Empty' /things/b: get: operationId: getB responses: 200: $ref: '#/components/responses/B' components: schemas: A: type: string B: $ref: '#/components/schemas/A' responses: A: description: success content: application/json: schema: $ref: '#/components/schemas/A' B: description: success content: application/json: schema: $ref: '#/components/schemas/B' Empty: description: success ``` -------------------------------- ### Run Command-Line Client Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/command-line-client-example/README.md Build and execute the command-line client to interact with the Greeting Service. Ensure the server is running locally on http://localhost:8080. ```console % swift run CommandLineClient greet --name CLI Hello, CLI! ``` -------------------------------- ### Run client CLI with authentication token Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/auth-client-middleware-example/README.md Build and run the client CLI with a valid authentication token to see a successful response. This demonstrates the basic usage of the client with authentication. ```console % swift run HelloWorldURLSessionClient token_for_Frank Hello, Stranger! (Requested by: Frank) ``` -------------------------------- ### Generated AcceptableContentType Enum Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0003.md An example of a generated `AcceptableContentType` enum for the `getStats` operation. It conforms to `AcceptableProtocol` and handles `json`, `plainText`, and other custom string values. ```swift @frozen public enum AcceptableContentType: AcceptableProtocol { case json case plainText case other(String) public init?(rawValue: String) { switch rawValue.lowercased() { case "application/json": self = .json case "text/plain": self = .plainText default: self = .other(rawValue) } } public var rawValue: String { switch self { case let .other(string): return string case .json: return "application/json" case .plainText: return "text/plain" } } public static var allCases: [Self] { [.json, .plainText] } ``` -------------------------------- ### Build the project Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/type-overrides-example/README.md Execute the build command to compile the Swift project. ```console % swift build Build complete! ``` -------------------------------- ### Build and run the server CLI Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/bidirectional-event-streams-server-example/README.md Execute the server application using the Swift package manager. ```console % swift run 2024-07-04T08:56:23+0200 info Hummingbird : [HummingbirdCore] Server started and listening on 127.0.0.1:8080 ... ``` -------------------------------- ### Initialize Swift Package Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.console.1.2.txt Initialize a new Swift executable package within the specified directory. This sets up the basic project structure. ```bash swift package --package-path GreetingService init --type executable ``` -------------------------------- ### OpenAPI Multipart Encoding Object Example Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0009.md This example demonstrates how to use the 'encoding' object within a multipart/form-data schema to specify content types and custom headers for different parts of the request. ```yaml multipart/form-data: schema: type: object properties: metadata: $ref: '#/components/schemas/PhotoMetadata' contents: type: string contentEncoding: binary required: - metadata - contents encoding: metadata: headers: x-sender-id: schema: type: string contents: contentType: image/jpeg ``` -------------------------------- ### GET /stats Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0004.md Retrieves the current list of statistical items. ```APIDOC ## GET /stats ### Description Retrieves a collection of statistical items. ### Method GET ### Endpoint /stats ### Response #### Success Response (200) - **StatItems** (array) - A list of statistical objects containing name and value. ``` -------------------------------- ### Represent binary payload Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0004.md Example of a binary representation for stats data. ```text 0010101001011000 ``` -------------------------------- ### Run the client CLI Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/hello-world-urlsession-client-example/README.md Execute the built client application to interact with the Greeting Service. ```console % swift run Hello, Stranger! ``` -------------------------------- ### Create and Initialize Swift Package Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.console.2.1.txt Creates a new directory and initializes a Swift executable package within it. ```shell % mkdir GreetingServiceClient ``` ```shell % swift package --package-path GreetingServiceClient init --type executable ``` -------------------------------- ### Represent text-based payload Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0004.md Example of a text-based representation for stats data. ```text CatCount_42_DogCount_24 ``` -------------------------------- ### Represent JSON payload Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0004.md Example of a structured JSON payload for the StatItems schema. ```json [{"name":"CatCount","value":42},{"name":"DogCount","value":24}] ``` -------------------------------- ### Instantiate a Client with a Transport Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0005.md Demonstrates the standard pattern for initializing a generated client using a concrete transport implementation. ```swift // Instantiate a concrete transport implementation. let transport: any ClientTransport = ... // any client transport // Instantiate the generated client by providing it with the transport. let client = Client(transport: transport) // Make API calls let response = try await client.getStats(...) ... ``` -------------------------------- ### GET /greet Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0007.md Retrieves a greeting message. This endpoint is generated from the OpenAPI definition. ```APIDOC ## GET /greet ### Description Retrieves a greeting message. ### Method GET ### Endpoint /greet ### Parameters #### Query Parameters - **accept** (AcceptableContentType) - Optional - The content type accepted for the response. ### Request Example ```json { "example": "No request body for GET request" } ``` ### Response #### Success Response (200) - **body** (Operations.getGreeting.Output.Ok.Body) - The HTTP response body containing the greeting. #### Response Example ```json { "example": "{\"message\": \"Hello, World!\"}" } ``` #### Error Response - **undocumented** (statusCode: Int, OpenAPIRuntime.UndocumentedPayload) - Handles undocumented status codes. ``` -------------------------------- ### Example of a reference cycle Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Development/Supporting-recursive-types.md A representation of a recursive reference cycle where type B is identified for boxing. ```text A -> B -> C -> B ``` -------------------------------- ### Run Proxy Server Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/streaming-chatgpt-proxy/README.md Build and run the proxy server. Ensure the OPENAI_TOKEN environment variable is set. ```console % swift run ProxyServer 2025-01-30T09:12:23+0000 notice codes.vapor.application : [Vapor] Server starting on http://127.0.0.1:8080 ... ``` -------------------------------- ### View OpenAPI Generator CLI Help Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Articles/Manually-invoking-the-generator-CLI.md Run this command to display the usage documentation for the swift-openapi-generator CLI, including all available options and subcommands. ```bash swift run swift-openapi-generator --help ``` -------------------------------- ### GET /greet Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0007.md Retrieves a greeting message, optionally personalized with a name provided in the query parameters. ```APIDOC ## GET /greet ### Description Retrieves a greeting message. The response can be personalized by providing a name in the query parameters. ### Method GET ### Endpoint /greet ### Parameters #### Query Parameters - **name** (String) - Optional - A name used in the returned greeting. ### Response #### Success Response (200) - **body** (Greeting) - The greeting message object containing the message string. #### Response Example { "message": "Hello, World!" } ``` -------------------------------- ### Create Project Directory Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.console.1.2.txt Use this command to create a new directory for your Swift project. ```bash mkdir GreetingService ``` -------------------------------- ### Run Client CLI Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/streaming-chatgpt-proxy/README.md Run the client CLI to interact with the proxy server. Provide a prompt as an argument. The output includes the client's input and the AI-generated response. ```console % swift run ClientCLI "That team with the Bull logo" Build of product 'ClientCLI' complete! (7.24s) 🧑‍💼: That one with the bull logo --- 🤖: **"Charge Ahead, Chicago Bulls!"** (Verse 1) Red and black, we’re on the prowl, Chicago Bulls, hear us growl! From the Windy City, we take the lead, Charging forward with lightning speed! (Chorus) B-U-L-L-S, Bulls! Bulls! Bulls! We’re the team that never dulls! Hoops and hustle, heart and soul, Chicago Bulls, we’re on a roll! ... ``` -------------------------------- ### Query the metrics endpoint Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/metrics-middleware-example/README.md Retrieve Prometheus metrics from the server by making a GET request to the /metrics endpoint. ```console % curl "localhost:8080/metrics" # TYPE http_requests_total counter http_requests_total{method="GET",path="/metrics",status="200"} 1 http_requests_total{method="GET",path="//api/greet",status="200"} 7 # TYPE http_request_duration_seconds histogram http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="0.005"} 5 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="0.01"} 6 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="0.025"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="0.05"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="0.1"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="0.25"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="0.5"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="1.0"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="2.5"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="5.0"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="10.0"} 7 http_request_duration_seconds_bucket{method="GET",path="//api/greet",status="200",le="+Inf"} 7 http_request_duration_seconds_sum{method="GET",path="//api/greet",status="200"} 0.025902709 http_request_duration_seconds_count{method="GET",path="//api/greet",status="200"} 7 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="0.005"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="0.01"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="0.025"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="0.05"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="0.1"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="0.25"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="0.5"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="1.0"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="2.5"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="5.0"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="10.0"} 1 http_request_duration_seconds_bucket{method="GET",path="/metrics",status="200",le="+Inf"} 1 http_request_duration_seconds_sum{method="GET",path="/metrics",status="200"} 0.001705458 http_request_duration_seconds_count{method="GET",path="/metrics",status="200"} 1 # TYPE HelloWorldServer.getGreeting.200 counter HelloWorldServer.getGreeting.200 7 ``` -------------------------------- ### Use the Curated Client API Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/curated-client-library-example/README.md Initialize the client and invoke the greeting method to retrieve a message. ```swift import CuratedLibraryClient let client = GreetingClient() let message = try await client.getGreeting(name: "Frank") print("Received the greeting message: \(message)") ``` -------------------------------- ### Server Output and API Response Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.console.1.2.txt Observe the server startup message and the JSON response from the API. This confirms the server is running and the API is functioning as expected. ```text 2023-12-12T09:06:32+0100 notice codes.vapor.application : [Vapor] Server starting on http://127.0.0.1:8080 { "message" : "Hello, Jane" } ``` -------------------------------- ### Open Package Definition Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/server.console.1.2.txt Open the Package.swift file to review or modify your project's dependencies and configuration. ```bash open GreetingService/Package.swift ``` -------------------------------- ### Run Vapor Server Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Tutorials/_Resources/client.console.1.2.txt Execute the Vapor server using Swift Package Manager. Ensure the server is built and running before sending requests. ```bash swift run HelloWorldVaporServer ``` -------------------------------- ### Stats Service OpenAPI Document Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0004.md Defines the API structure for the Stats service, including GET and POST operations and the StatItems schema. ```yaml openapi: 3.0.3 info: title: Stats service version: 1.0.0 paths: /stats: get: operationId: getStats responses: '200': description: A successful response. content: application/json: schema: $ref: '#/components/schemas/StatItems' text/plain: {} application/octet-stream: {} post: operationId: postStats requestBody: required: true content: application/json: schema: $ref: '#/components/schemas/StatItems' text/plain: {} application/octet-stream: {} responses: '202': description: Successfully submitted. components: schemas: StatItem: type: object properties: name: type: string value: type: integer required: [name, value] StatItems: type: array items: $ref: '#/components/schemas/StatItem' ``` -------------------------------- ### Invoke API operations with input parameters Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0007.md Demonstrates the verbose syntax required for calling operations with input parameters before the shorthand API implementation. ```swift // before (with parameters) _ = try await client.getGreeting(Operations.getGreeting.Input( query: Operations.getGreeting.Input.Query(name: "Maria") )) // before (with parameters, shorthand) _ = try await client.getGreeting(.init(query: .init(name: "Maria"))) // before (no parameters, shorthand) _ = try await client.getGreeting(.init())) ``` -------------------------------- ### Define an OpenAPI Service Document Source: https://github.com/apple/swift-openapi-generator/blob/main/README.md A sample OpenAPI 3.1.0 document defining a greeting service with a GET endpoint and a JSON schema component. ```yaml openapi: '3.1.0' info: title: GreetingService version: 1.0.0 servers: - url: https://example.com/api description: Example service deployment. paths: /greet: get: operationId: getGreeting parameters: - name: name required: false in: query description: The name used in the returned greeting. schema: type: string responses: '200': description: A success response with a greeting. content: application/json: schema: $ref: '#/components/schemas/Greeting' components: schemas: Greeting: type: object description: A value with the greeting contents. properties: message: type: string description: The string representation of the greeting. required: - message ``` -------------------------------- ### Run project tests Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/hello-world-hummingbird-server-example/README.md Execute the test suite to verify the Handler implementation against the APIProtocol. ```console % swift test ``` -------------------------------- ### Send Requests to API Server Source: https://github.com/apple/swift-openapi-generator/blob/main/Examples/metrics-middleware-example/README.md Send requests to the API server to generate metrics that can be scraped by Prometheus. This example sends names to the /api/greet endpoint. ```console % % echo "Juan Mei Tom Bill Anne Ravi Maria" | xargs -n1 -I% curl "localhost:8080/api/greet?name=%" { "message" : "Hello, Juan!" } { "message" : "Hello, Mei!" } { "message" : "Hello, Tom!" } { "message" : "Hello, Bill!" } { "message" : "Hello, Anne!" } { "message" : "Hello, Ravi!" } { "message" : "Hello, Maria!" } ``` -------------------------------- ### Handle API operation output Source: https://github.com/apple/swift-openapi-generator/blob/main/Sources/swift-openapi-generator/Documentation.docc/Proposals/SOAR-0007.md Demonstrates the verbose switch-case pattern required to handle operation outputs before the shorthand API implementation. ```swift // before switch try await client.getGreeting() { case .ok(let response): switch response.body { case .json(let body): print(body.message) } case .undocumented(statusCode: _, _): throw UnexpectedResponseError() } ```