Back to OSS
Swift Package 通信 / サーバー

swift-api-server

Vapor を抽象化し、アプリケーションコードをフレームワーク実装から独立させるサーバー層

Swift
servervaporbackend

APIServer

English | 日本語

An abstraction layer over the Vapor web framework. Keeps application code independent of Vapor-specific implementations.

Swift 6.0+ macOS 14+ License

Features

  • Vapor Abstraction: Application code doesn't depend directly on Vapor
  • Protocol-Based Design: Easy to test and extensible for the future
  • APIContract Integration: Type-safe routing via APIService
  • Middleware System: CORS, authentication, and error handling included
  • Sendable Compliant: Supports Swift 6's strict concurrency

Quick Start

import APIServer

// Create a server (async initialization)
let server = try await Server.create()

// Register routes — closures are automatically JSON-encoded
server.get("health") {
    ["status": "healthy"]
}

// Add middleware
server.use(CORSServerMiddleware())
server.useErrorMiddleware()

// Start the server
try await server.run()

Installation

Swift Package Manager

Add to your Package.swift:

dependencies: [
    .package(url: "https://github.com/no-problem-dev/swift-api-server.git", from: "1.0.0")
]

Add to your target:

.target(
    name: "YourTarget",
    dependencies: [
        .product(name: "APIServer", package: "swift-api-server")
    ]
)

Core Components

ServerApplication

Protocol definition for server applications:

public protocol ServerApplication: Sendable {
    associatedtype Routes: APIServer.Routes
    var environment: ServerEnvironment { get }
    var logger: ServerLogger { get }
    var routes: Routes { get }

    func use(_ middleware: any ServerMiddleware)
    func run() async throws
    func shutdown() async throws
}

The concrete implementation returned by Server.create() is VaporServerApplication.

ServerEnvironment

Environment configuration abstraction. Auto-detected from the SWIFT_ENV or VAPOR_ENV environment variable:

let environment = ServerEnvironment.detect() // reads SWIFT_ENV or VAPOR_ENV

switch environment {
case .development:
    // Development settings
case .testing:
    // Testing settings
case .production:
    // Production settings
}

Routing

Direct routes or APIService-based routing:

// Direct route registration
server.get("health") {
    ["status": "healthy"]
}

// Route group
let v1 = server.group("api", "v1")
v1.get("status") { ["version": "1.0"] }

// APIService-based routing
let service = MyAPIService()
MyAPIGroup.registerAll(server.routes.mount(service))

Middleware

Middleware How to Add Purpose
CORSServerMiddleware server.use(CORSServerMiddleware()) CORS header configuration
Authentication server.useAuth(provider) Bearer token authentication
Error handling server.useErrorMiddleware() Convert errors to JSON responses
// CORS configuration
server.use(CORSServerMiddleware(configuration: .custom(
    allowedOrigins: ["https://example.com"],
    allowedMethods: [.get, .post, .put, .delete],
    allowedHeaders: ["Content-Type", "Authorization"],
    allowCredentials: true
)))

// Authentication
server.useAuth(MyAuthProvider())  // MyAuthProvider: AuthenticationProvider

// Error handling
server.useErrorMiddleware()

HTTPStatus

Common HTTP status codes:

Status Description
.ok (200) Success
.created (201) Created
.noContent (204) No Content
.badRequest (400) Bad Request
.unauthorized (401) Unauthorized
.forbidden (403) Forbidden
.notFound (404) Not Found
.internalServerError (500) Internal Server Error

Design Philosophy

This library is designed based on the following principles:

  1. Dependency Hiding: Vapor is hidden in the Internal/ directory and doesn't appear in the public API
  2. Protocol First: All abstractions are defined as Swift protocols
  3. Sendable Compliance: All public types adopt Sendable
  4. Factory Pattern: Dependency injection via Server.create()

See DESIGN.md for detailed design documentation.

Dependencies

Package Purpose
swift-api-contract Contract-based API definition
vapor Internal implementation (not exposed in public API)

Documentation

Detailed API documentation is available at GitHub Pages.

License

MIT License — See LICENSE for details.

同じカテゴリの OSS — 通信 / サーバー

swift-api-client

Swift Package

async/await 対応の軽量 HTTP クライアント。型安全な API 通信を Swift で

Swift
· 通信 / サーバー
http-clientasync-awaitnetworking

swift-api-contract

Swift Package

Swift マクロで型安全な API 契約を定義する

Swift
· 通信 / サーバー
swift-macroapitype-safe

swift-firebase-server

Swift Package

サーバーサイド Swift 向けの Firestore REST API クライアント

Swift
· 通信 / サーバー
firebasefirestoreserver

swift-http-transport

Swift Package

URLSession をプロトコル背後に隠し、リトライ / レート制限 / SSE を一元化する通信基盤

Swift
· 通信 / サーバー
httpurlsessionsse

swift-persistence

Swift Package

KeyValue / Secure / Document / Registry を束ねるプロトコル指向の永続化抽象レイヤー

Swift
· 通信 / サーバー
persistencekeyvaluestorage

© 2026 Kyoichi Taniguchi. All rights reserved.