Contents

philiprehberger/swift-net-kit

Declarative networking client with retry, caching, plugins, and automatic Codable decoding

Requirements

  • Swift >= 6.0
  • macOS 13+ / iOS 16+ / tvOS 16+ / watchOS 9+

Installation

Add to your Package.swift:

dependencies: [
    .package(url: "https://github.com/philiprehberger/swift-net-kit.git", from: "0.1.0")
]

Then add "NetKit" to your target dependencies:

.target(name: "YourTarget", dependencies: [
    .product(name: "NetKit", package: "swift-net-kit")
])

Usage

import NetKit

// Define an endpoint
struct GetUser: Endpoint {
    let userId: String
    var path: String { "/users/\(userId)" }
    var method: HTTPMethod { .get }
}

// Make a request
let client = NetworkClient(baseURL: URL(string: "https://api.example.com")!)
let response = try await client.request(GetUser(userId: "123"), as: User.self)
print(response.data.name)

POST with Body

struct CreateUser: Endpoint {
    let name: String
    var path: String { "/users" }
    var method: HTTPMethod { .post }
    var body: Data? { try? JSONEncoder().encode(["name": name]) }
    var headers: [String: String] { ["Content-Type": "application/json"] }
}

Retry Policy

let response = try await client.request(
    GetUser(userId: "123"),
    as: User.self,
    retry: .default  // 3 attempts, 1s delay, retries on 500/502/503/504
)

Caching

let response = try await client.request(
    GetUser(userId: "123"),
    as: User.self,
    cache: .memory(ttl: 60)  // cache for 60 seconds
)

Plugins

let client = NetworkClient(
    baseURL: url,
    plugins: [
        AuthPlugin { await getToken() },
        LoggingPlugin()
    ]
)

API

NetworkClient

| Method | Description | |--------|-------------| | init(baseURL:plugins:session:) | Create a client with base URL and plugins | | request(:as:retry:cache:) | Request with Codable decoding | | request(:) | Request returning raw Data | | upload(:to:contentType:) | Upload data to an endpoint | | download(:) | Download raw data |

Endpoint

| Property | Description | |----------|-------------| | path | URL path component | | method | HTTP method | | headers | Request headers (default: empty) | | queryItems | URL query parameters (default: empty) | | body | Request body data (default: nil) |

NetworkPlugin

| Method | Description | |--------|-------------| | prepare(:) | Modify request before sending | | process(:data:) | Process response after receiving |

Development

swift build
swift test

Support

💬 Bluesky · 🐦 X · 💼 LinkedIn · 🌐 Website · 📦 GitHub · ☕ Buy Me a Coffee · ❤️ GitHub Sponsors

License

MIT

Package Metadata

Repository: philiprehberger/swift-net-kit

Default branch: main

README: README.md