URLRequestComponents exposes a lightweight, typed way to build URLRequest.
Build requests with typed headers, typed bodies, and small syntax sugar around URLQueryItem, string literals, multipart parts, and URLSession.
import Foundation
import URLRequestComponents
struct MessagePayload: Encodable, Sendable {
let title: String
let body: String
}
let messageRequest = try URLRequestComponents(
method: .post,
scheme: .https,
host: "api.example.com",
port: 8443,
path: "v1/messages",
fragment: "details",
queryItems: [
URLQueryItem(name: "locale", value: "en"),
URLQueryItem(
name: "redirect",
url: URL(string: "myapp://tracks/42?source=share")!
)
],
headers: [
.accept(.json),
.authorization("Bearer token")
],
body: try .json(MessagePayload(title: "Hello", body: "World"))
).asURLRequest()
print(messageRequest.httpMethod ?? "")
// POST
print(messageRequest.value(forHTTPHeaderField: "Content-Type") ?? "")
// application/jsonimport Foundation
import URLRequestComponents
let searchRequest = try URLRequestComponents(
method: .post,
scheme: .https,
host: "api.example.com",
path: "search",
headers: [.accept(.json)],
body: .formURLEncoded(
items: URLQueryItem(name: "query", value: "Taylor Swift"),
URLQueryItem(name: "limit", value: "10")
)
).asURLRequest()
let pingRequest = try URLRequestComponents(
method: .post,
scheme: .https,
host: "api.example.com",
path: "ping",
body: "alive"
).asURLRequest()
print(searchRequest.value(forHTTPHeaderField: "Content-Type") ?? "")
// application/x-www-form-urlencoded
print(String(data: pingRequest.httpBody ?? Data(), encoding: .utf8) ?? "")
// aliveimport Foundation
import URLRequestComponents
let uploadRequest = try URLRequestComponents(
method: .post,
scheme: .https,
host: "api.example.com",
path: "upload",
body: .multipart([
.formField(name: "title", value: "Cover Art"),
.file(name: "cover", fileURL: coverURL)
])
).asURLRequest()
let tracksRequest = URLRequestComponents(
method: .get,
scheme: .https,
host: "api.example.com",
path: "v1/tracks"
)
let (data, response) = try await URLSession.shared.data(request: tracksRequest)
print(uploadRequest.value(forHTTPHeaderField: "Content-Type") ?? "")
// multipart/form-data; boundary=...
print(response.statusCode)
print(data.count)Add the package to your Package.swift dependencies:
.package(url: "https://github.com/inekipelov/swift-url-request-components.git", from: "0.1.0")