# apigenie-generator client swift

Source: https://apigenie.pl/docs/reference/generator/client-swift
Part of the reference of [apigenie-generator](https://apigenie.pl/docs/reference/generator.md).
Its other pages: [Conformance results](https://apigenie.pl/docs/reference/generator/conformance.md), [docs](https://apigenie.pl/docs/reference/generator/docs.md), [data](https://apigenie.pl/docs/reference/generator/data.md), [schema zod](https://apigenie.pl/docs/reference/generator/schema-zod.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir.md), [client fetch](https://apigenie.pl/docs/reference/generator/client-fetch.md), [client go](https://apigenie.pl/docs/reference/generator/client-go.md), [client java](https://apigenie.pl/docs/reference/generator/client-java.md), [client python](https://apigenie.pl/docs/reference/generator/client-python.md), [client rust](https://apigenie.pl/docs/reference/generator/client-rust.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet.md), [server axum](https://apigenie.pl/docs/reference/generator/server-axum.md), [server express](https://apigenie.pl/docs/reference/generator/server-express.md), [server fastapi](https://apigenie.pl/docs/reference/generator/server-fastapi.md), [server go](https://apigenie.pl/docs/reference/generator/server-go.md), [server hummingbird](https://apigenie.pl/docs/reference/generator/server-hummingbird.md), [server mcp](https://apigenie.pl/docs/reference/generator/server-mcp.md), [server orpc](https://apigenie.pl/docs/reference/generator/server-orpc.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring.md), [server vapor](https://apigenie.pl/docs/reference/generator/server-vapor.md), [client csharp](https://apigenie.pl/docs/reference/generator/client-csharp-asyncapi.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-asyncapi.md), [client go](https://apigenie.pl/docs/reference/generator/client-go-asyncapi.md), [client java](https://apigenie.pl/docs/reference/generator/client-java-asyncapi.md), [client kafkajs](https://apigenie.pl/docs/reference/generator/client-kafkajs.md), [client python](https://apigenie.pl/docs/reference/generator/client-python-asyncapi.md), [client ws](https://apigenie.pl/docs/reference/generator/client-ws.md), [server aspnet](https://apigenie.pl/docs/reference/generator/server-aspnet-asyncapi.md), [server faststream](https://apigenie.pl/docs/reference/generator/server-faststream.md), [server go](https://apigenie.pl/docs/reference/generator/server-go-asyncapi.md), [server kafkajs](https://apigenie.pl/docs/reference/generator/server-kafkajs.md), [server phoenix](https://apigenie.pl/docs/reference/generator/server-phoenix-asyncapi.md), [server spring](https://apigenie.pl/docs/reference/generator/server-spring-asyncapi.md), [server ws](https://apigenie.pl/docs/reference/generator/server-ws.md), [client elixir](https://apigenie.pl/docs/reference/generator/client-elixir-protobuf.md), [server elixir-grpc](https://apigenie.pl/docs/reference/generator/server-elixir-grpc.md), [server absinthe](https://apigenie.pl/docs/reference/generator/server-absinthe.md).

[Experimental](/docs/reference/generator/conformance#tiers) · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · [Verification](#verification)

Generate a Swift package calling the operations of an OpenAPI document, for iOS, macOS, tvOS,
watchOS and Linux apps.

> **(experimental, outside the 1.0 compatibility promise)** The generated code isn't yet built and
> run against a live API by the conformance suite, so its types and methods can still change.
> `client swift` says so in its `--help` and on the first line it prints, on the standard error.
> See the [experimental commands](/docs/reference/cli#experimental-commands).

## Usage

```sh
apigenie-generator client swift [...OPTIONS] INPUT_FILE
```

## Description

The generator writes a Swift package with one library target. Its code uses Foundation only: the
package has no dependencies.

| File | Contents |
| ---- | -------- |
| `Package.swift` | tools version 6.0, the platforms (iOS 16, macOS 13, tvOS 16, watchOS 9) and a library product of the module |
| `.swift-format` | the swift-format settings the generated code follows (`swift format lint`) |
| `Sources/<Module>/Client.swift` | `Server`, `Credentials` and `Client`, with an async method per operation |
| `Sources/<Module>/Operations.swift` | per operation, the enum of its responses, the structs of their headers and the enums of bodies of several media types |
| `Sources/<Module>/Models.swift` | the types of the component schemas the operations use, and of their inline schemas |
| `Sources/<Module>/Runtime/*.swift` | the transport, requests and errors, JSON coding, parameter styles, streams, multipart bodies, validation, `Nullable`, `CalendarDate`, `Indirect`, `JSONValue` |

The module is named after the document's title followed by `Client` (`Carpet Express Shipping
API` gives `CarpetExpressShippingAPIClient`; `APIClient` when the title gives no name), unless
`--package-name` or `package` names it.

```swift
let client = Client(server: .production, credentials: .apiKey(apiKey))
switch try await client.getShipment(shipmentID: "shp_123") {
case .ok(let body, let headers):
    print(body, headers.eTag)
case .notFound(let problem):
    print(problem.title)
case .notModified:
    break
}
```

### Methods

Every operation is a method of `Client`, named after its `operationId`. Its arguments are the
path parameters, the body (`body:`, `nil` by default when optional), the required query, header
and cookie parameters, then the optional ones defaulting to `nil`, in document order. It returns
the operation's response enum, with a case per documented status:

```swift
public func createShipment(
    body: ShipmentCreate,
    idempotencyKey: UUID? = nil,
    prefer: CreateShipmentPrefer? = nil,
    xRequestID: String? = nil
) async throws -> CreateShipmentResponse

public enum CreateShipmentResponse: Sendable {
    /// `201`: Shipment booked.
    case created(body: Shipment, headers: CreateShipmentCreatedHeaders)
    /// `400`: The request could not be parsed.
    case badRequest(Problem)
    // ... 202, 401, 403, 409, 422, 429
    /// `5XX`: A carrier or Carpet Express itself is unavailable.
    case serverError(statusCode: Int, body: Problem, headers: CreateShipmentServerErrorHeaders)
}
```

- A case holds the body of its status and, when the response declares headers, a struct of them;
  ranges (`5XX`) and `default` also hold the status code. A status with several media types holds
  an enum of them (`.pdf(Data)`, `.json(LabelEnvelope)`), chosen by the response's
  `Content-Type`.
- A status the document doesn't list throws `ClientError.undocumentedStatus` with the status, the
  headers and the body; a body or header that can't be read throws `ClientError.invalidResponse`,
  and a request that can't be written (a null required path parameter, an invalid URL) throws
  `ClientError.invalidParameter`.
- A request body of several media types is an enum with a case per media type
  (`UpdateShipmentRequestBody.mergePatchJSON(ShipmentPatch)`).
- JSON bodies are checked against their schemas before they are sent while
  `client.validatesRequests` is `true` (the default, `validate_requests`): a body that breaks one
  throws `ClientError.invalidRequest` with the constraints it breaks. `validatesResponses`
  (`validate_responses`) checks response bodies the same way.
- Parameters are written in their style and `explode` mode: `simple`, `label` and `matrix` path
  parameters, `form`, `spaceDelimited`, `pipeDelimited` and `deepObject` query parameters,
  `allowReserved`, headers and cookies. Parameters described with `content` are sent as JSON.
- Methods set `Accept` to the media types of the documented responses.
- Operations marked `x-internal: true` (on the operation or its path) are left out, unless
  `internal_operations` is set. Deprecated operations are marked `@available(*, deprecated)`.

### Streams

`text/event-stream`, `application/jsonl` and `application/json-seq` responses are
`AsyncThrowingStream`s of their items, typed by the media type's `itemSchema` (OpenAPI 3.2;
`x-itemSchema` in 3.0 and 3.1 documents):

```swift
if case .ok(.eventStream(let events)) = try await client.getTrackingEvents(shipmentID: id) {
    for try await event in events {
        print(event.id ?? "", event.data)
    }
}
```

- Server-sent events are `ServerSentEvent` values whose `data` is decoded as the `contentSchema`
  of the `itemSchema`'s `data` property, or kept as a `String`.
- On Apple platforms the items arrive as the server sends them (`URLSession.bytes(for:)`). On
  Linux, whose Foundation has no `bytes(for:)`, `URLSessionTransport` reads the whole body first.
- JSON Lines and JSON text sequence request bodies are arrays of their items.

### Multipart bodies

`multipart/form-data` bodies of object schemas are structs with a property per part. Binary parts
(`format: binary`, or `contentMediaType` in 3.1 and 3.2) are `MultipartFile` values (data, file
name and media type), arrays of them `[MultipartFile]`. Object parts, and parts whose encoding has
a JSON `contentType`, are sent as JSON; other parts as text, a part per item of arrays.

### Servers

`Server` has a static property per server of the document, named after its `name` or
`description` (`.production`, `.sandbox`; `server1` when neither gives a name), with the default
values of its variables. `Client` sends to the first one unless `server:` says otherwise; without
servers in the document, `server:` is required. `Server(url:)` makes any other. Operations with
servers of their own (on the operation or its path) are sent there unless `usesOperationServers`
is `false`, e.g. for a test server or a proxy.

### Security

`Credentials` has a property per security scheme of the document, and a function making
credentials of that scheme alone:

| Scheme | Property | Sent as |
| ------ | -------- | ------- |
| `apiKey` in a header, the query or a cookie | `String?` | the header, query parameter or cookie |
| `http` `basic` | `BasicCredentials?` | `Authorization: Basic ...` |
| `http` `bearer` | `String?` | `Authorization: Bearer ...` |
| `oauth2`, `openIdConnect` | `TokenProvider?`, an async closure returning the access token | `Authorization: Bearer ...` |
| `mutualTLS` | `Bool`, set when the transport presents the certificate | `URLSessionTransport(clientCertificate:)` (Apple platforms) |

A request gets the credentials of the first alternative of its operation's security
requirements whose schemes all have credentials; without one, the method throws
`ClientError.missingCredentials`. An operation with `security: []` gets none.

### Transport

`Client` sends requests through an `HTTPTransport` (one `async throws` method, `send(_:)`),
`URLSessionTransport` by default. A transport of your own can add retries, logging or a test
double.

## Stability

Experimental, since 0.12.0.

## What you depend on

- Swift 6.0 or later, in the Swift 6 language mode (strict concurrency).
- Swift Package Manager (`swift build`), which reads `Package.swift` (tools version 6.0).
- Foundation, and FoundationNetworking on Linux. No package dependencies.
- iOS 16, macOS 13, tvOS 16 or watchOS 9 on Apple platforms.

## Features

| Feature | Support |
| ------- | ------- |
| Authentication schemes | yes: API keys, HTTP basic and bearer, OAuth 2 and OpenID Connect tokens, mutual TLS |
| Streaming | partial: server-sent events, JSON Lines and JSON text sequences arrive as sent on Apple platforms; on Linux the body is read whole first |
| Pagination | no |
| File upload | yes: multipart bodies and binary bodies |
| Enums | yes, with `unknown(String)` for values the document doesn't list |
| Discriminators | yes, with `mapping` and `defaultMapping` |
| Nullable | yes: `Nullable<T>?` tells missing, null and set values apart |
| Errors | yes: a case per documented status, typed `ClientError`s |
| Retries | no: an `HTTPTransport` of your own can retry |

## Type mapping

| Schema | Swift |
| ------ | ----- |
| object | `public struct` that is `Codable`, `Hashable`, `Sendable` and `Validatable`, with a memberwise initializer |
| optional property | `T?`, left out when encoding `nil` |
| optional nullable property | `Nullable<T>?`: `nil` when missing, `.null` when null |
| required nullable property | `T?`, written as `null` |
| string or integer enum | an enum with a case per value and `unknown(String)` (`unknown(Int)`), or without it with `unknown_enum_cases: false` |
| `oneOf`, `anyOf` | an `indirect enum` with a case per variant; with a discriminator, the variant its property selects, else the first variant the value decodes as |
| `allOf` | the properties merged into one struct |
| `prefixItems` | a struct with a property per position (`item0`, `item1`), coded as an array |
| `additionalProperties`, `patternProperties` | `[String: V]`, or `additionalProperties` of the struct |
| `integer` | `Int`; `Int8` … `Int64`, `UInt` … `UInt64` by `format`; `Int64` for `double-int`, `unixtime` |
| `number` | `Double`, `Float`, `Decimal` (`format: decimal`, `decimal128`) |
| `date-time`, `date`, `uuid`, `uri` and `url` | `Date`, `CalendarDate`, `UUID`, `URL` |
| `byte`, `binary` | `Data` |
| any value | `JSONValue` |
| recursive struct | the property held through `@Indirect` |

Every struct, union and tuple has `validate()`, which checks lengths, patterns, numeric limits,
item counts, unique items, `const`, `enum`, formats, `if`/`then`/`else`, `dependentRequired`,
`dependentSchemas` and the `oneOf`/`anyOf` groups of required properties, and throws a
`ValidationError` listing the constraints a value breaks with JSON pointers to them.

## Extensions

| Extension | Effect |
| --------- | ------ |
| `x-swift-name` | name of the type of a schema, or of the property of a property |
| `x-enum-varnames`, `x-enumNames` | names of the enum cases |
| `x-enum-descriptions` | documentation of the enum cases |
| `x-apigenie.codegen.name` | name of the type of a component schema, when it has no `x-swift-name` |
| `x-apigenie.codegen.action-name` | name of the method of an operation without an `operationId` (with the default `action_naming`) |
| `x-apigenie.codegen.disabled` | `true` on an operation or its path item leaves the operation out |
| `x-internal` | `true` on an operation or its path item leaves the operation out, unless `internal_operations` is set |
| `x-defaultMapping` | `defaultMapping` of a discriminator in OpenAPI 3.0 and 3.1 documents |
| `x-itemSchema` | `itemSchema` of a media type in OpenAPI 3.0 and 3.1 documents |

## Options

### -c, --config

Path to the configuration file to use. See the "Configuration" section for more information.

### --overlay OVERLAY

Path to an OpenAPI Overlay (1.0 to 1.2) applied to the input before generating, e.g. one setting the
extensions of the "Extensions" section. Can be repeated: the overlays apply in order, after those
listed under `commands.generate.client_swift.overlay` in the configuration file.

### --strict

Makes an overlay action whose target selects nothing an error (exit status 2, nothing is generated)
instead of a warning.

### --no-config

Doesn't look for `apigenie.yaml` (or `.apigenie.yaml`) in the current directory and its parents up
to the root of the repository.

### --json

Prints one JSON document on the standard output (`formatVersion`, `command`, `exitStatus`,
`messages`) instead of the messages.

### -o, --output

Directory where the package is generated.

### --package-name

Name of the Swift module, its library product and the package. Defaults to the document's title
followed by `Client`.

### --package-version

Ignored: Swift packages take their versions from Git tags.

### -p, --property NAME=VALUE

Sets a generator option (see below), e.g. `-p validate_responses=true`. Options given on the
command line take precedence over the configuration file. Lists are comma-separated
(`-p include_tags=shipments,rates`).

## Configuration

```yaml
version: '1.0'
commands:
  generate:
    client_swift:
      package: CarpetExpress
      validate_responses: true
      exclude_tags: [internal]
```

| Option | Type | Default | Description |
| ------ | ---- | ------- | ----------- |
| `package` | string | the document's title followed by `Client` | Name of the module, its library product and the package; also set by `--package-name`. |
| `include_tags` | list of strings | | Generates only the operations with one of these tags. |
| `exclude_tags` | list of strings | | Skips the operations with one of these tags. |
| `skip_prune` | boolean | `false` | Keeps the component schemas that no generated operation uses. |
| `internal_operations` | boolean | `false` | Also generates the operations marked `x-internal: true`. |
| `validate_requests` | boolean | `true` | The default of `Client.validatesRequests`: request bodies are checked before they are sent. |
| `validate_responses` | boolean | `false` | The default of `Client.validatesResponses`: response bodies are checked. |
| `unknown_enum_cases` | boolean | `true` | Enums get an `unknown` case for values the document doesn't list. |
| `initialisms` | list of strings | | Words written in one case in identifiers, besides `ID`, `URL`, `HTTP`, `JSON` and the other common initialisms. |
| `action_naming` | list of `id`, `extension`, `url` | `id, extension, url` | Where method names come from, in order of preference. |

## Exit status

0 when the package was generated; 2 when the options, the configuration, an overlay or the input
document can't be used (with `--strict`, also when an overlay action selects nothing). See
[`apigenie-generator`](/docs/reference/generator).

## Limitations

- What the conformance fixture doesn't cover is listed under [Verification](#verification);
  callbacks, webhooks and links are out of scope there.
- `validate()` skips patterns Swift's `Regex` can't compile and `unevaluatedProperties` other
  than `false`. It checks `if`/`then`/`else` and `dependentSchemas` only when their schemas use
  `required` and the `const` and `enum` of properties.
- `format: decimal` numbers are decoded by `JSONDecoder`, which reads them through `Double` on
  Apple platforms before macOS 15 and iOS 18.
- A `oneOf` without a discriminator decodes as its first variant that decodes, even when another
  one matches too.
- Types of the standard library, Foundation, the runtime and the client (`Data`, `Error`,
  `ValidationError`, `Client`, `Credentials`, `Server`, ...) are reserved: schemas with these names
  get types with `Model` after their names, e.g. `ErrorModel`.
- The input must be an OpenAPI 3.0, 3.1 or 3.2 document or a Swagger 2.0 document (see
  [Swagger 2.0 input](/docs/reference/generator#swagger-20-input)); bundle documents referencing
  other files with `apigenie bundle`.

## Verification

The [codegen conformance suite](/docs/reference/generator#conformance-checks) runs this target on the Carpet Express OpenAPI fixture. Level 1 compares the output with its snapshots and checks each feature, Level 2 runs the language's type checker and linter, and Level 3 runs the generated code in contract tests against the fixture. [All targets](/docs/reference/generator/conformance#openapi).

This target's support tier is [Experimental](/docs/reference/generator/conformance#tiers). It isn't run at every level yet. It is outside the [1.0 compatibility promise](/docs/reference/cli/compatibility): its options and the shape of its output can change, or it can go away, in a minor release.

| Results | Level 1 | Level 2 | Level 3 |
| --- | --- | --- | --- |
| Release 0.12.0 | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | ✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE)) | ✓ 37 of 37 operations pass (swift) |
| Development version | ✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 37 supported, 0 not yet | runs before a release | runs before a release |
