Declarative networking client with retry, caching, plugins, and automatic Codable decoding
.package(url: "https://github.com/philiprehberger/swift-net-kit.git", from: "0.1.0")Declarative networking client with retry, caching, plugins, and automatic Codable decoding
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")
])
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)
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"] }
}
let response = try await client.request(
GetUser(userId: "123"),
as: User.self,
retry: .default // 3 attempts, 1s delay, retries on 500/502/503/504
)
let response = try await client.request(
GetUser(userId: "123"),
as: User.self,
cache: .memory(ttl: 60) // cache for 60 seconds
)
let client = NetworkClient(
baseURL: url,
plugins: [
AuthPlugin { await getToken() },
LoggingPlugin()
]
)
| 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 |
| 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) |
| Method | Description |
|---|---|
prepare(_:) | Modify request before sending |
process(_:data:) | Process response after receiving |
swift build
swift test
💬 Bluesky · 🐦 X · 💼 LinkedIn · 🌐 Website · 📦 GitHub · ☕ Buy Me a Coffee · ❤️ GitHub Sponsors