- HAR 1.2
- Swift 6
- Apple platforms & Linux
- No dependencies
- MIT
Your app's traffic,
as a HAR file.
Build an HTTP Archive entry from each request and its response, collect them in a log, and write the file that every browser's network panel, Charles, Proxyman and HAR viewer opens. swift-har never touches the network: it works with whatever HTTP client you already use.
import HARKitURLSession
let entry = HAR.Entry(
startedDateTime: start, // you know when you sent it
request: try HAR.Request(sentRequest, httpVersion: "h2"),
response: HAR.Response(httpResponse, body: body, httpVersion: "h2"),
timings: try HAR.Timings(send: 0.4, wait: 85.4, receive: 3.1)
)
let log = HAR.Log(creator: .init(name: "MyApp", version: "1.0"), entries: [entry])
let har = try HAR.Archive(log: log).jsonData(prettyPrinted: true)
// Open it in Safari, Chrome, Firefox, Charles or Proxyman.
What is HAR
The format every network inspector speaks.
HAR 1.2 is the JSON file browsers export from their network panel: every request, response, header, cookie, body and timing of a session. Attach one to a bug report, replay it in a debugging proxy, or diff two of them in a test. Writing a correct one by hand means repeating the query string, cookies, sizes and total time in exactly the shape the specification asks for. swift-har derives those fields from what you pass in:
request.urlthe URL without its fragmentrequest.queryStringthe URL query, split on & and percent-decodedrequest.cookiesthe Cookie headersrequest.postDatathe body as text, or form params, when it is UTF-8 textresponse.contentplain text for UTF-8 text, base64 with encoding otherwiseresponse.cookiesSet-Cookie headers, Expires converted to ISO 8601response.redirectURLthe Location headerbodySizethe byte count, or -1 when a Content-Encoding hides itheadersSize-1: the bytes on the wire depend on the HTTP stackentry.timethe sum of the timings, as HAR 1.2 requiresFeatures
Correct HAR files, without the bookkeeping.
A small API that follows the specification closely, writes down every choice it leaves open, and refuses to make up the data it was not given.
Every HAR 1.2 object, typed
One Codable, Hashable, Sendable value type per object, from log to timings. Mutually exclusive fields are enums, so text and params can never both be set.
Honest about missing data
The library never reads the clock, invents timings or guesses a body. Unknown sizes are -1 and unknown optional fields are left out, as the specification prescribes. You supply what only you know.
Builders that do the tedious part
Pass a method, URL, headers and body. You get the query string, request and Set-Cookie cookies (RFC 6265 parsing), post data or base64 content, redirect URL and sizes.
Reads what other tools write
Decoding is lenient: a byte order mark, custom _fields and the out-of-spec values browsers and proxies produce load fine. Writing is deterministic, with sorted keys.
Works with any HTTP client
HARKit takes plain values, so it works with URLSession, AsyncHTTPClient, Alamofire or your own stack. HARKitURLSession adds converters for URLRequest, HTTPURLResponse and task metrics.
Small, Swift 6, Linux-ready
No dependencies. HARKit imports FoundationEssentials where it exists, so on Linux it links neither full Foundation nor FoundationNetworking. Strict concurrency throughout.
Code tour
A few lines per exchange.
These snippets come from the README, which the test suite compiles and runs, so they stay correct.
Describe one exchange with plain values. The builders derive the fields HAR repeats.
import HARKit
let request = HAR.Request(
method: "POST",
url: URL(string: "https://api.example.com/pets?limit=10#top")!,
httpVersion: "HTTP/1.1",
headers: [
HAR.Header(name: "Content-Type", value: "application/json"),
HAR.Header(name: "Cookie", value: "session=abc123"),
],
body: Data(#"{"name":"Rex"}"#.utf8)
)
let response = HAR.Response(
status: 201,
statusText: "Created",
httpVersion: "HTTP/1.1",
headers: [
HAR.Header(name: "Content-Type", value: "application/json"),
HAR.Header(name: "Set-Cookie", value: "theme=dark; Path=/; HttpOnly"),
],
body: Data(#"{"id":42}"#.utf8)
)
let timings = try HAR.Timings(dns: -1, connect: -1, send: 1.2, wait: 85.4, receive: 3.1)
let entry = HAR.Entry(startedDateTime: requestStart, request: request, response: response, timings: timings)Collect entries in a log and serialize it. The same archive always gives the same bytes.
let log = HAR.Log(creator: HAR.Creator(name: "MyApp", version: "1.0"), entries: [entry])
let data = try HAR.Archive(log: log).jsonData(prettyPrinted: true)
// Write `data` to a file named with a `.har` extension.Load a HAR file exported by a browser or a proxy.
let archive = try HAR.Archive(json: data)
for entry in archive.log.entries {
print(entry.request.method, entry.request.url, entry.response.status, entry.time)
}Turn a finished URLSessionTask and its metrics into an entry.
import HARKitURLSession
/// Call from `urlSession(_:task:didFinishCollecting:)` with the body you received.
func harEntry(task: URLSessionTask, body: Data, metrics: URLSessionTaskMetrics) throws -> HAR.Entry? {
guard let sent = task.currentRequest ?? task.originalRequest,
let received = task.response as? HTTPURLResponse,
let transaction = metrics.transactionMetrics.last,
let timings = HAR.Timings(transaction)
else { return nil }
let httpVersion = transaction.networkProtocolName ?? ""
return HAR.Entry(
startedDateTime: transaction.fetchStartDate ?? metrics.taskInterval.start,
request: try HAR.Request(sent, httpVersion: httpVersion),
response: HAR.Response(received, body: body, httpVersion: httpVersion),
timings: timings
)
}When you do not know a value, the types make you say so rather than guess.
// Nothing measured? Say so instead of inventing numbers.
let unmeasured = try HAR.Timings(send: 0, wait: 0, receive: 0, comment: "Timings were not measured")
// The request failed: write the placeholder browsers use, and say why.
let failed = HAR.Response(
status: 0, statusText: "", httpVersion: "",
content: HAR.Content(size: 0, mimeType: ""),
comment: "The request timed out"
)Built for
Anywhere you want to see the traffic.
In-app network debuggers
Let testers export a session from a debug menu and open it in Safari's or Chrome's network panel, with headers, bodies and a timing waterfall.
Bug reports and support
Attach the exact requests and responses to a crash report or a ticket. Redact Authorization headers and bodies before building entries, and the rest is the real thing.
Tests and CI artifacts
Record what an integration test sent and received as a HAR file next to the failure, or decode a recorded file to drive a mock server. Models are Hashable, so whole entries compare in one #expect.
Servers and command-line tools
Log outgoing calls from a Vapor or Hummingbird service, or a script, on Linux. HARKit needs only FoundationEssentials there.
Quality and speed
Checked against the specification. Measured on every change.
Codable, Hashable, Sendable value typeHARKit; FoundationEssentials on Linux, no FoundationNetworking| Benchmark (p50, Apple silicon) | 0.1.0 | 0.1.1 |
|---|---|---|
| Build an entry from a request and its response | 25.9 µs | 19.2 µs |
| Build a request (query string, cookies, JSON body) | 9.5 µs | 8.1 µs |
| Build a response (two Set-Cookie headers, JSON body) | 15.9 µs | 10.9 µs |
| Encode a 1000-entry log to JSON | 59.7 ms | 58.4 ms |
| Decode a 1000-entry log | 71.8 ms | 70.5 ms |
Benchmarks use package-benchmark and live in the repository: swift package --package-path Benchmarks benchmark. Details in docs/performance.md.
Install
Add it to your package.
dependencies: [
.package(url: "https://github.com/mackoj/swift-har.git", from: "0.1.1"),
],
targets: [
.target(name: "MyApp", dependencies: [
.product(name: "HARKit", package: "swift-har"),
// or, to convert URLRequest, HTTPURLResponse and task metrics:
.product(name: "HARKitURLSession", package: "swift-har"),
]),
]
- Swift 6.0+ on Linux, macOS 13+, iOS 16+, tvOS 16+, watchOS 9+ and visionOS 1+.
HARKit: models, builders from plain values, and JSON. No dependencies.HARKitURLSession: converters forURLRequest,HTTPURLResponseandURLSessionTaskTransactionMetrics. Re-exportsHARKit.- API reference on the Swift Package Index; guide, missing-data advice and specification notes in the README.