apigenie-generator server hummingbird

Experimental · Release 0.12.0: Level 1 ✓ · Level 2 ✓ · Level 3 ✓ · Verification

Generate a Swift server package for Hummingbird 2 from an OpenAPI document.

(experimental, outside the 1.0 compatibility promise) Levels 2 and 3 of the conformance suite are wired for the generated packages but haven’t passed a run yet, so their types and methods can still change. server hummingbird says so in its --help and on the first line it prints, on the standard error. See the experimental commands.

Usage

apigenie-generator server hummingbird [...OPTIONS] INPUT_FILE

Description

The generator writes a Swift package with one library target, depending on Hummingbird. Its code is that of the server vapor packages except Server/Hummingbird.swift, the platform and the dependencies in Package.swift, and schemas named like a Hummingbird type (see Limitations). Code written against one moves to the other by changing the few lines that start the server.

File Contents
Package.swift tools version 6.0, macOS 14, the Hummingbird 2 and swift-http-types dependencies and a library product of the module
.swift-format the swift-format settings the generated code follows (swift format lint)
Sources/<Module>/Server/APIHandler.swift the APIHandler protocol, with an async method per operation, and UnimplementedHandler
Sources/<Module>/Server/Requests.swift the request struct of each operation: its parameters, its body and the credentials it was sent with
Sources/<Module>/Server/Routes.swift APIRoutes: an APIRoute per operation, which reads the request, checks it and calls the handler
Sources/<Module>/Server/Senders.swift WebhookSender and CallbackSender, for documents with webhooks or callbacks
Sources/<Module>/Server/Hummingbird.swift APIRoutes.register(on:handler:), which registers the routes with a Hummingbird router
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 requests and responses of the routes, JSON coding, parameter styles, streams, multipart bodies, validation, Nullable, CalendarDate, Indirect, JSONValue, and the transport of the senders

The module is named after the document’s title followed by Server (Carpet Express Shipping API gives CarpetExpressShippingAPIServer; APIServer when the title gives no name), unless --package-name or package names it.

A server implements APIHandler and registers it:

import CarpetExpress
import Hummingbird

struct Shipments: APIHandler {
    func getShipment(_ request: GetShipmentRequest) async throws -> GetShipmentResponse {
        guard let stored = try await store.shipment(request.shipmentID) else {
            return .notFound(Problem(type: "about:blank", title: "No such shipment", status: 404))
        }
        return .ok(body: stored.shipment, headers: GetShipmentOkHeaders(eTag: stored.eTag))
    }
    // ... a method per operation
}

let router = Router()
APIRoutes.register(on: router, handler: Shipments())
let app = Application(
    router: router,
    configuration: .init(address: .hostname("0.0.0.0", port: 8080))
)
try await app.runService()

Handler

APIHandler has a method per operation, named after its operationId, taking the operation’s request struct and returning its response enum, the same enum the Swift client returns:

func createShipment(_ request: CreateShipmentRequest) 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)
}
  • The request struct has a property per path, query, header and cookie parameter, body (an optional when the body is), and credentials, the credentials of the security requirement the request met, by scheme.
  • A case of the response enum is written with its status (the status code of ranges and default), its headers and its body, as JSON, text, bytes, a form, multipart parts or a stream of the media type the case holds.
  • A method that throws HandlerError.problem(status:title:detail:) answers that status with RFC 9457 problem details; HandlerError.notImplemented answers 501, and any other error 500.
  • UnimplementedHandler answers every operation with 501: a starting point, and a server for tests of the routes.
  • Deprecated operations say so in their documentation, but aren’t @available(*, deprecated): the routes call every method.

Routes

Before the handler runs, the route of an operation:

  1. checks the security requirements: the request needs the credentials of one alternative, or it gets 401;
  2. reads the path, query, header and cookie parameters in their style and explode mode (simple, label and matrix path parameters, form, spaceDelimited, pipeDelimited and deepObject query parameters; JSON for parameters described with content), and checks them against their schemas;
  3. reads the body by its Content-Type: JSON, application/x-www-form-urlencoded, multipart/form-data, JSON Lines and JSON text sequences, text and bytes, including media type ranges such as image/*. A body of another media type gets 415, a missing required body 400.

A request that breaks the document gets 400 with problem details whose errors list the JSON pointers of the values that break it, also of a parameter that can’t be read as its schema’s type (/query/limit for ?limit=abc); pretty-printed here, and the order of the keys varies:

{
  "type": "about:blank",
  "title": "Bad Request",
  "status": 400,
  "detail": "/path/shipmentId: must match the pattern ^shp_[0-9A-Za-z]{24}$",
  "errors": [
    { "pointer": "/path/shipmentId", "detail": "must match the pattern ^shp_[0-9A-Za-z]{24}$" }
  ]
}

The routes are registered below the path of the first server of the operation or its path item, else of the document’s first server (/v2/shipments for https://api.carpetexpress.example/v2). APIRoutes.all(_:) returns them, and APIRoutes.register(_:on:) registers them with other prefixes:

let routes = APIRoutes.all(Shipments()).map { route in
    var moved = route
    moved.prefix = "/api"
    return moved
}
let router = Router()
router.add(middleware: APIKeyCheck())
APIRoutes.register(routes, on: router)

register takes a Router of any RequestContext, and the routes run its middleware. Request bodies are collected before the routes read them, up to maxBodySize bytes (10 MB by default); a larger body gets 413 from Hummingbird.

Streams

A response of text/event-stream, application/jsonl or application/json-seq holds an AsyncThrowingStream of its items, typed by the media type’s itemSchema (OpenAPI 3.2; x-itemSchema in 3.0 and 3.1 documents), and the route writes each item as it comes:

let events = AsyncThrowingStream<ServerSentEvent<TrackingEvent>, any Error> { continuation in
    // yield the events as they happen
}
return .ok(.eventStream(events))

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 read as JSON; other parts as text, a part per item of arrays.

Security

The route of an operation gives the request the credentials of the first alternative of its security requirements whose schemes all have some; checking them is up to the handler:

Scheme Credential in request.credentials
apiKey in a header, the query or a cookie the key
http basic username:password
http bearer, oauth2, openIdConnect the bearer token
mutualTLS an empty string: the server doesn’t check client certificates, so the TLS layer in front of it must require them (the generator warns)

An operation with security: [] gets no credentials; an empty alternative lets requests without credentials through.

Webhooks and callbacks

WebhookSender has a method per webhook of the document and CallbackSender one per callback of the operations. A method is named after the request’s operationId, else its x-apigenie.codegen.action-name, else the webhook, or the operation and the callback (createShipmentStatusChanged). Each takes the URL the receiver gave, the request’s body and its parameters, and returns the request’s response enum:

let sender = WebhookSender()
let response = try await sender.onShipmentStatusChanged(
    to: subscription.url,
    body: event,
    carpetExpressSignature: signature
)

The senders send through an HTTPTransport, URLSessionTransport by default, and check request bodies against their schemas (validatesRequests). The credentials of the security requirements of webhooks and callbacks are up to the transport.

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).
  • Hummingbird 2.0 or later, and swift-http-types 1.0 or later.
  • macOS 14 or later, or Linux.

Features

Feature Support
Authentication schemes partial: the credentials of API keys, HTTP basic and bearer, OAuth 2 and OpenID Connect tokens reach the handler, which checks them
Streaming yes: server-sent events, JSON Lines and JSON text sequences are written as the items come
Pagination no
File upload yes: multipart bodies and binary bodies
Enums yes; values the document doesn’t list get 400
Discriminators yes, with mapping and defaultMapping
Nullable yes: Nullable<T>? tells missing, null and set values apart
Errors yes: a case per documented status, RFC 9457 problem details for invalid requests
Retries no: the senders send each request once; an HTTPTransport of your own can retry
Webhooks and callbacks yes: typed senders

Type mapping

The types are those of the Swift client, except enums, which have no unknown case: a server rejects values the document doesn’t list. Bodies are checked against their schemas as they are decoded.

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, a webhook or a callback (or its path item) leaves it 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.server_hummingbird.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 Server.

–package-version

Ignored: Swift packages take their versions from Git tags.

-p, –property NAME=VALUE

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

Configuration

version: '1.0'
commands:
  generate:
    server_hummingbird:
      package: CarpetExpress
      exclude_tags: [internal]
Option Type Default Description
package string the document’s title followed by Server 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, webhooks and callbacks marked x-internal: true.
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.

Limitations

  • What the conformance fixture doesn’t cover is listed under Verification; links are out of scope there.
  • The routes don’t check credentials, only that a request has them: the handler decides whether they are valid. HTTP schemes other than basic and bearer get a warning, and the operations requiring them answer 401.
  • Requests are checked as the Swift client’s validate() checks bodies: patterns Swift’s Regex can’t compile, unevaluatedProperties other than false, and formats other than email, uri, uuid, date, date-time, ipv4 and ipv6 aren’t checked, and such values reach the handler. if/then/else and dependentSchemas are checked 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 macOS before 15.
  • Response bodies aren’t checked against their schemas.
  • 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, the server and the Hummingbird types the adapter uses (Data, Error, APIHandler, APIRoutes, ServerRequest, Request, Response, Router, …) are reserved: schemas with these names get types with Model after their names, e.g. ResponseModel.
  • 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); bundle documents referencing other files with apigenie bundle.

Verification

The codegen conformance suite 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.

This target's support tier is Experimental. It isn't run at every level yet. It is outside the 1.0 compatibility promise: its options and the shape of its output can change, or it can go away, in a minor release.

ResultsLevel 1Level 2Level 3
Release 0.12.0✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yet✓ pass (Swift version 6.0.3 (swift-6.0.3-RELEASE))✓ 70 of 77 operations pass, 2 known failures (swift)
Development version✓ snapshots of 3.2, 3.1, 3.0, 2.0; 3.2: 39 supported, 0 not yetruns before a releaseruns before a release, 2 known failures
Was this helpful?