### Example Bug Report Structure Source: https://github.com/apple/swift-openapi-runtime/blob/main/CONTRIBUTING.md This example shows the expected format for reporting a bug, including commit hash, context, steps to reproduce, and system information. ```text Commit hash: b17a8a9f0f814c01a56977680cb68d8a779c951f Context: While testing my application that uses with swift-openapi-runtime, 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. ``` -------------------------------- ### Configure act with .actrc Source: https://github.com/apple/swift-openapi-runtime/blob/main/CONTRIBUTING.md Example configuration for the '.actrc' file to set default flags for 'act', such as container architecture, remote name, and offline mode. ```bash --container-architecture=linux/amd64 --remote-name upstream --action-offline-mode ``` -------------------------------- ### Implement a Custom ClientTransport Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Implement the `ClientTransport` protocol to abstract the underlying HTTP library. This example shows a test transport for stubbing responses. ```swift import OpenAPIRuntime import HTTPTypes import Foundation // Using an existing transport (e.g., from swift-openapi-urlsession): // let transport = URLSessionTransport() // Implementing a custom test transport: struct TestTransport: ClientTransport { var stubbedStatusCode: Int = 200 var stubbedBody: String? = nil func send( _ request: HTTPRequest, body: HTTPBody?, baseURL: URL, operationID: String ) async throws -> (HTTPResponse, HTTPBody?) { let response = HTTPResponse(status: .init(code: stubbedStatusCode)) let responseBody = stubbedBody.map { HTTPBody($0) } return (response, responseBody) } } // Wire up a generated Client with the transport: let transport = TestTransport(stubbedStatusCode: 200, stubbedBody: "{\"status\":\"ok\"}") // let client = Client(serverURL: URL(string: "https://api.example.com")!, transport: transport) // let response = try await client.getStatus() ``` -------------------------------- ### Create and Consume HTTPBody in Swift Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Demonstrates creating HTTPBody from various sources like strings, Data, and AsyncStreams. Shows how to consume the body as a streaming sequence or collect it into memory as String, Data, or bytes. Supports streaming and buffered consumption with optional size limits. ```swift import OpenAPIRuntime import Foundation // Create from a string literal let body1: HTTPBody = "Hello, world!" // Create from Data let data = Data("{\"key\":\"value\"}".utf8) let body2 = HTTPBody(data) // Create from an AsyncStream (streaming, single-iteration) let body3 = HTTPBody( AsyncStream(ArraySlice.self) { continuation in continuation.yield(Array("chunk1".utf8)[...]) continuation.yield(Array("chunk2".utf8)[...]) continuation.finish() }, length: .unknown ) // Consume as a streaming async sequence for try await chunk in body3 { print("Received chunk of \(chunk.count) bytes") } // Collect the full body into memory (with a 2 MB cap) let body4 = HTTPBody("Full response text here") let text = try await String(collecting: body4, upTo: 2 * 1024 * 1024) print(text) // "Full response text here" // Collect into Data let body5 = HTTPBody(data) let collected = try await Data(collecting: body5, upTo: 1 * 1024 * 1024) // Collect into bytes let body6: HTTPBody = [72, 101, 108, 108, 111] let bytes = try await [UInt8](collecting: body6, upTo: 1024) print(String(bytes: bytes, encoding: .utf8)!) // "Hello" ``` -------------------------------- ### Configure OpenAPI Runtime Client/Server in Swift Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Shows how to create and customize the Configuration object for OpenAPI Runtime clients and servers. Covers options for date formatting (ISO 8601, Unix timestamp), JSON encoding (pretty-printing, sorted keys), and multipart boundary generation. ```swift import OpenAPIRuntime import Foundation // Default configuration: ISO 8601 dates, sorted + pretty-printed JSON let defaultConfig = Configuration() // ISO 8601 dates with fractional seconds let preciseConfig = Configuration( dateTranscoder: .iso8601WithFractionalSeconds ) // Custom date transcoder struct UnixTimestampTranscoder: DateTranscoder { func encode(_ date: Date) throws -> String { String(date.timeIntervalSince1970) } func decode(_ string: String) throws -> Date { guard let ts = Double(string) else { throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Invalid timestamp")) } return Date(timeIntervalSince1970: ts) } } let customConfig = Configuration( dateTranscoder: UnixTimestampTranscoder(), jsonEncodingOptions: [.sortedKeys], // compact, sorted output multipartBoundaryGenerator: .random ) // Use with a generated client: // let client = Client( // serverURL: URL(string: "https://api.example.com")!, // configuration: customConfig, // transport: URLSessionTransport() // ) ``` -------------------------------- ### Create and Stream Multipart Parts Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Demonstrates creating raw and typed multipart parts, building a MultipartBody from static parts, and streaming multipart parts using AsyncStream. ```swift import OpenAPIRuntime import HTTPTypes // Create a raw multipart part (e.g., a file upload field) let filePart = MultipartRawPart( headerFields: [ .contentDisposition: "form-data; name=\"file\"; filename=\"hello.txt\"", .contentType: "text/plain", ], body: HTTPBody("Hello from the file!") ) // Create a typed multipart part wrapper with a filename struct DocumentPayload: Sendable, Hashable { var data: HTTPBody } let typedPart = MultipartPart( payload: DocumentPayload(data: HTTPBody("document content")), filename: "doc.txt" ) // Build a MultipartBody from a static array of parts (as generated code would): // let body: MultipartBody = [.file(filePart), .metadata(metaPart)] // Streaming production via AsyncStream: let (stream, continuation) = AsyncStream.makeStream(of: MultipartRawPart.self) Task { continuation.yield(MultipartRawPart( headerFields: [.contentDisposition: "form-data; name=\"field1\""], body: HTTPBody("value1") )) continuation.yield(MultipartRawPart( headerFields: [.contentDisposition: "form-data; name=\"field2\""], body: HTTPBody("value2") )) continuation.finish() } let streamingBody = MultipartBody(stream) ``` ```swift // Consuming a multipart body: // for try await part in multipartBody { // switch part { // case .file(let filePart): // let content = try await String(collecting: filePart.payload.data, upTo: 1 * 1024 * 1024) // print("File content: \(content)") // case .undocumented(let raw): // print("Unknown part: \(raw.headerFields)") // } // } ``` -------------------------------- ### Run Formatting Check with act and Bind Mount Source: https://github.com/apple/swift-openapi-runtime/blob/main/CONTRIBUTING.md Execute the formatting job locally using 'act' with the '--bind' flag to mount the working directory, ensuring changes are reflected directly. ```bash % act --bind workflow_call -j soundness --input format_check_enabled=true ``` -------------------------------- ### Configuration Source: https://context7.com/apple/swift-openapi-runtime/llms.txt `Configuration` controls how dates are encoded/decoded, JSON output formatting, multipart boundary generation, and custom XML coding. Pass it to generated `Client` or `UniversalServer` initializers. ```APIDOC ## `Configuration` `Configuration` controls how dates are encoded/decoded, JSON output formatting, multipart boundary generation, and custom XML coding. Pass it to generated `Client` or `UniversalServer` initializers. ```swift import OpenAPIRuntime import Foundation // Default configuration: ISO 8601 dates, sorted + pretty-printed JSON let defaultConfig = Configuration() // ISO 8601 dates with fractional seconds let preciseConfig = Configuration( dateTranscoder: .iso8601WithFractionalSeconds ) // Custom date transcoder struct UnixTimestampTranscoder: DateTranscoder { func encode(_ date: Date) throws -> String { String(date.timeIntervalSince1970) } func decode(_ string: String) throws -> Date { guard let ts = Double(string) else { throw DecodingError.dataCorrupted(.init(codingPath: [], debugDescription: "Invalid timestamp")) } return Date(timeIntervalSince1970: ts) } } let customConfig = Configuration( dateTranscoder: UnixTimestampTranscoder(), jsonEncodingOptions: [.sortedKeys], // compact, sorted output multipartBoundaryGenerator: .random ) // Use with a generated client: // let client = Client( // serverURL: URL(string: "https://api.example.com")!, // configuration: customConfig, // transport: URLSessionTransport() // ) ``` ``` -------------------------------- ### Add swift-openapi-runtime as a Package Dependency Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Include `swift-openapi-runtime` as a dependency in your Package.swift file and add `OpenAPIRuntime` to your target's dependencies. ```swift // Package.swift let package = Package( name: "MyService", platforms: [.macOS(.v10_15), .iOS(.v13)], dependencies: [ .package(url: "https://github.com/apple/swift-openapi-runtime", from: "1.0.0"), // Also add your chosen transport, e.g.: // .package(url: "https://github.com/swift-server/swift-openapi-vapor", from: "1.0.0"), ], targets: [ .target( name: "MyService", dependencies: [ .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"), ] ), ] ) ``` -------------------------------- ### Catching and Inspecting ServerError Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Demonstrates how to catch and inspect a ServerError, useful for debugging server-side operations and determining the HTTP status to return. ```swift // Catching and inspecting a ServerError (in a test): // do { // try await server.handle(request: req, body: nil, metadata: .init()) // } catch let error as ServerError { // print("Operation: \(error.operationID)") // print("HTTP status to return: \(error.httpStatus.code)") // print("Cause: \(error.causeDescription)") // } ``` -------------------------------- ### Catching and Inspecting ClientError Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Shows how to catch and inspect a ClientError, accessing details like operation ID, request, response, and underlying cause. ```swift // Catching and inspecting a ClientError: // do { // let response = try await client.getPet(.init(path: .init(petId: 99))) // } catch let error as ClientError { // print("Operation: \(error.operationID)") // e.g. "getPet" // print("Cause: \(error.causeDescription)") // print("Request: \(error.request?.method.rawValue ?? \"none\")") // print("Response status: \(error.response?.status.code ?? 0)") // print("Underlying: \(error.underlyingError)") // } ``` -------------------------------- ### Minimal In-Memory Server Transport Implementation Source: https://context7.com/apple/swift-openapi-runtime/llms.txt A basic in-memory implementation of ServerTransport for testing purposes. It allows registering handlers and simulating request handling without a real web server. ```swift import OpenAPIRuntime import HTTPTypes // Implementing a minimal in-memory test transport: final class InMemoryServerTransport: ServerTransport { typealias Handler = @Sendable (HTTPRequest, HTTPBody?, ServerRequestMetadata) async throws -> (HTTPResponse, HTTPBody?) private var routes: [(method: HTTPRequest.Method, path: String, handler: Handler)] = [] func register( _ handler: @Sendable @escaping (HTTPRequest, HTTPBody?, ServerRequestMetadata) async throws -> (HTTPResponse, HTTPBody?), method: HTTPRequest.Method, path: String ) throws { routes.append((method: method, path: path, handler: handler)) print("Registered: \(method.rawValue) \(path)") } func handle(request: HTTPRequest, body: HTTPBody?, pathParameters: [String: Substring] = [:]) async throws -> (HTTPResponse, HTTPBody?) { let metadata = ServerRequestMetadata(pathParameters: pathParameters) guard let route = routes.first(where: { $0.method == request.method }) else { return (HTTPResponse(status: .notFound), nil) } return try await route.handler(request, body, metadata) } } ``` -------------------------------- ### Run a Specific CI Job with act Source: https://github.com/apple/swift-openapi-runtime/blob/main/CONTRIBUTING.md Execute a single job, such as 'soundness', with specific inputs like 'shell_check_enabled=true' using the 'act' tool. ```bash % act workflow_call -j soundness --input shell_check_enabled=true ``` -------------------------------- ### Printing Middleware for Server Requests Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Logs incoming request method, path, operation ID, and outgoing response status code. Useful for server-side debugging and monitoring. ```swift import OpenAPIRuntime import HTTPTypes /// Prints request and response metadata. struct PrintingMiddleware: ServerMiddleware { func intercept( _ request: HTTPRequest, body: HTTPBody?, metadata: ServerRequestMetadata, operationID: String, next: @Sendable (HTTPRequest, HTTPBody?, ServerRequestMetadata) async throws -> (HTTPResponse, HTTPBody?) ) async throws -> (HTTPResponse, HTTPBody?) { print(">>> \(request.method.rawValue) \(request.soar_pathOnly) [\(operationID)]") do { let (response, responseBody) = try await next(request, body, metadata) print("<<< \(response.status.code)") return (response, responseBody) } catch { print("!!! Error: \(error)") throw error } } } ``` -------------------------------- ### Add OpenAPIRuntime to Target Dependencies Source: https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Documentation.docc/Documentation.md Include OpenAPIRuntime as a product dependency for your target in Package.swift. ```swift .target(name: "MyTarget", dependencies: [ .product(name: "OpenAPIRuntime", package: "swift-openapi-runtime"), ]), ``` -------------------------------- ### Add Package Dependency to Package.swift Source: https://github.com/apple/swift-openapi-runtime/blob/main/Sources/OpenAPIRuntime/Documentation.docc/Documentation.md Declare the OpenAPIRuntime package as a dependency in your Package.swift file. ```swift .package(url: "https://github.com/apple/swift-openapi-runtime", from: "1.0.0"), ``` -------------------------------- ### Logging Middleware for Client Requests Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Logs the HTTP method of outgoing requests and the status code of incoming responses. Useful for debugging client interactions. ```swift import OpenAPIRuntime import HTTPTypes import Foundation /// Logs request method and response status. struct LoggingMiddleware: ClientMiddleware { func intercept( _ request: HTTPRequest, body: HTTPBody?, baseURL: URL, operationID: String, next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?) ) async throws -> (HTTPResponse, HTTPBody?) { print("→ \(request.method) \(operationID)") let (response, responseBody) = try await next(request, body, baseURL) print("← \(response.status.code)") return (response, responseBody) } } ``` -------------------------------- ### Run All CI Checks Locally with act Source: https://github.com/apple/swift-openapi-runtime/blob/main/CONTRIBUTING.md Use this command to execute all jobs defined in the pull_request workflow locally using the 'act' tool. ```bash % act pull_request ``` -------------------------------- ### Implement HTTPResponseConvertible for Custom Error Handling in Swift Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Demonstrates how to make custom error types conform to `HTTPResponseConvertible` to control their conversion into HTTP responses. This allows specific error types to map to distinct HTTP status codes and response bodies, enabling structured error handling with `ErrorHandlingMiddleware`. ```swift import OpenAPIRuntime import HTTPTypes enum AppError: Error { case notFound(id: String) case unauthorized case validationFailed(field: String, reason: String) } extension AppError: HTTPResponseConvertible { var httpStatus: HTTPResponse.Status { switch self { case .notFound: return .notFound // 404 case .unauthorized: return .unauthorized // 401 case .validationFailed: return .badRequest // 400 } } var httpBody: HTTPBody? { switch self { case .notFound(let id): return HTTPBody("{\"error\":\"Resource \(id) not found\"}") case .unauthorized: return HTTPBody("{\"error\":\"Unauthorized\"}") case .validationFailed(let field, let reason): return HTTPBody("{\"error\":\"Validation failed for '\(field)': \(reason)"}") } } var httpHeaderFields: HTTPFields { [.contentType: "application/json"] } } // Register with the middleware: // let handler = MyAPIImplementation() // try handler.registerHandlers( // on: transport, // middlewares: [ErrorHandlingMiddleware()] // ) // // Now throwing AppError.notFound(id: "42") from a handler // automatically returns: HTTP 404 {"error":"Resource 42 not found"} ``` -------------------------------- ### Dynamic JSON Containers Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Utilize OpenAPIValueContainer, OpenAPIObjectContainer, and OpenAPIArrayContainer for dynamically-typed JSON values when schemas lack fixed structures. These containers ensure only JSON-compatible Swift types are stored. ```swift import OpenAPIRuntime // OpenAPIValueContainer — holds any single JSON-compatible value let strVal: OpenAPIValueContainer = "hello" let intVal: OpenAPIValueContainer = 42 let boolVal: OpenAPIValueContainer = true let nullVal: OpenAPIValueContainer = nil // Dynamic construction with validation let dynamicVal = try OpenAPIValueContainer(unvalidatedValue: ["nested": "object"] as [String: any Sendable]) // OpenAPIObjectContainer — holds a [String: Any?] dictionary var obj = try OpenAPIObjectContainer(unvalidatedValue: [ "name": "Alice", "age": 30, "active": true, ]) obj.value["role"] = "admin" // OpenAPIArrayContainer — holds an [(Any?)] array let arr = try OpenAPIArrayContainer(unvalidatedValue: ["item1", 2, true, nil]) for item in arr.value { print(item ?? "null") } // Codable round-trip let jsonData = try JSONEncoder().encode(obj) let decoded = try JSONDecoder().decode(OpenAPIObjectContainer.self, from: jsonData) print(decoded.value["name"] as? String ?? "") ``` -------------------------------- ### HTTPBody Source: https://context7.com/apple/swift-openapi-runtime/llms.txt `HTTPBody` is the HTTP request/response body type used throughout the runtime. It wraps an async sequence of `ArraySlice` chunks, supporting both streaming and fully-buffered consumption. It can be created from strings, `Data`, byte arrays, async sequences, and `AsyncStream`. ```APIDOC ## `HTTPBody` `HTTPBody` is the HTTP request/response body type used throughout the runtime. It wraps an async sequence of `ArraySlice` chunks, supporting both streaming and fully-buffered consumption. It can be created from strings, `Data`, byte arrays, async sequences, and `AsyncStream`. ```swift import OpenAPIRuntime import Foundation // Create from a string literal let body1: HTTPBody = "Hello, world!" // Create from Data let data = Data("{\"key\":\"value\"}".utf8) let body2 = HTTPBody(data) // Create from an AsyncStream (streaming, single-iteration) let body3 = HTTPBody( AsyncStream(ArraySlice.self) { continuation in continuation.yield(Array("chunk1".utf8)[...]) continuation.yield(Array("chunk2".utf8)[...]) continuation.finish() }, length: .unknown ) // Consume as a streaming async sequence for try await chunk in body3 { print("Received chunk of \(chunk.count) bytes") } // Collect the full body into memory (with a 2 MB cap) let body4 = HTTPBody("Full response text here") let text = try await String(collecting: body4, upTo: 2 * 1024 * 1024) print(text) // "Full response text here" // Collect into Data let body5 = HTTPBody(data) let collected = try await Data(collecting: body5, upTo: 1 * 1024 * 1024) // Collect into bytes let body6: HTTPBody = [72, 101, 108, 108, 111] let bytes = try await [UInt8](collecting: body6, upTo: 1024) print(String(bytes: bytes, encoding: .utf8)!) ``` ``` -------------------------------- ### Authentication Middleware for Client Requests Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Injects a Bearer token into outgoing requests. Use when authentication is required for all client requests. ```swift import OpenAPIRuntime import HTTPTypes import Foundation /// Injects a Bearer token into every outgoing request. struct AuthenticationMiddleware: ClientMiddleware { let bearerToken: String func intercept( _ request: HTTPRequest, body: HTTPBody?, baseURL: URL, operationID: String, next: @Sendable (HTTPRequest, HTTPBody?, URL) async throws -> (HTTPResponse, HTTPBody?) ) async throws -> (HTTPResponse, HTTPBody?) { var request = request request.headerFields[.authorization] = "Bearer \(bearerToken)" return try await next(request, body, baseURL) } } ``` -------------------------------- ### Server-Sent Events (SSE) Handling Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Represent SSE events using ServerSentEvent for raw string payloads or ServerSentEventWithJSONData for typed, decodable JSON payloads. These are used with streaming response bodies for `text/event-stream` operations. ```swift import OpenAPIRuntime // Raw SSE event let rawEvent = ServerSentEvent( id: "evt-001", event: "update", data: "{\"progress\": 42}", retry: 3000 // ms before client reconnects on error ) // Typed SSE event with JSON data struct ProgressPayload: Sendable, Hashable, Codable { var progress: Int var message: String } let typedEvent = ServerSentEventWithJSONData( event: "progress", data: ProgressPayload(progress: 75, message: "Processing..."), id: "evt-002", retry: nil ) // Producing a stream of SSE events (as a server handler would): let (stream, continuation) = AsyncStream.makeStream(of: ServerSentEventWithJSONData.self) Task { for i in 1...5 { continuation.yield(ServerSentEventWithJSONData( event: "progress", data: ProgressPayload(progress: i * 20, message: "Step \(i)") )) } continuation.finish() } // The generated server serializes this stream into the SSE wire format automatically. ``` -------------------------------- ### Custom Server Error with HTTPResponseConvertible Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Defines a custom server error that conforms to HTTPResponseConvertible, allowing automatic conversion to the correct HTTP status and body. ```swift // Example: custom error with HTTPResponseConvertible surfaces correct status enum PetStoreError: Error, HTTPResponseConvertible { case petNotFound(id: Int) var httpStatus: HTTPResponse.Status { switch self { case .petNotFound: return .notFound } } var httpBody: HTTPBody? { switch self { case .petNotFound(let id): return HTTPBody("Pet \(id) not found") } } } // When PetStoreError.petNotFound(42) is thrown from a handler, // ErrorHandlingMiddleware converts it to HTTP 404 automatically. ``` -------------------------------- ### ErrorHandlingMiddleware and HTTPResponseConvertible Source: https://context7.com/apple/swift-openapi-runtime/llms.txt `ErrorHandlingMiddleware` is a built-in `ServerMiddleware` that catches errors thrown by handlers and converts them to HTTP responses. Conform your error types to `HTTPResponseConvertible` to control the status code and body; unrecognized errors produce a 500 response. ```APIDOC ## `ErrorHandlingMiddleware` and `HTTPResponseConvertible` `ErrorHandlingMiddleware` is a built-in `ServerMiddleware` that catches errors thrown by handlers and converts them to HTTP responses. Conform your error types to `HTTPResponseConvertible` to control the status code and body; unrecognized errors produce a 500 response. ```swift import OpenAPIRuntime import HTTPTypes enum AppError: Error { case notFound(id: String) case unauthorized case validationFailed(field: String, reason: String) } extension AppError: HTTPResponseConvertible { var httpStatus: HTTPResponse.Status { switch self { case .notFound: return .notFound // 404 case .unauthorized: return .unauthorized // 401 case .validationFailed: return .badRequest // 400 } } var httpBody: HTTPBody? { switch self { case .notFound(let id): return HTTPBody("{\"error\":\"Resource \(id) not found\"}") case .unauthorized: return HTTPBody("{\"error\":\"Unauthorized\"}") case .validationFailed(let field, let reason): return HTTPBody("{\"error\":\"Validation failed for '\(field)': \(reason)"}") } } var httpHeaderFields: HTTPFields { [.contentType: "application/json"] } } // Register with the middleware: // let handler = MyAPIImplementation() // try handler.registerHandlers( // on: transport, // middlewares: [ErrorHandlingMiddleware()] // ) // // Now throwing AppError.notFound(id: "42") from a handler // automatically returns: HTTP 404 {"error":"Resource 42 not found"} ``` ``` -------------------------------- ### Base64EncodedData for Binary Data Source: https://context7.com/apple/swift-openapi-runtime/llms.txt Use Base64EncodedData to wrap binary data for transparent base64 encoding/decoding in JSON payloads. It's suitable for OpenAPI `format: byte` properties. ```swift import OpenAPIRuntime import Foundation // Create from raw bytes let rawBytes: [UInt8] = [0x48, 0x65, 0x6C, 0x6C, 0x6F] // "Hello" let encoded = Base64EncodedData(rawBytes) // Encode to JSON → produces a base64 string let jsonData = try JSONEncoder().encode(encoded) print(String(data: jsonData, encoding: .utf8)!) // Decode from JSON base64 string let jsonString = "\"SGVsbG8=\"" let decoded = try JSONDecoder().decode(Base64EncodedData.self, from: Data(jsonString.utf8)) print(String(bytes: decoded.data, encoding: .utf8)!) // Use in a Codable model (as generated code would) struct FileUpload: Codable { var filename: String var content: Base64EncodedData // maps to a base64 string in JSON } let upload = FileUpload( filename: "hello.txt", content: Base64EncodedData(Array("Hello, file!".utf8)) ) let uploadJSON = try JSONEncoder().encode(upload) // {"filename":"hello.txt","content":"SGVsbG8sIGZpbGUh"} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.