• 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.

NetworkLogger.swift
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 fragment
request.queryStringthe URL query, split on & and percent-decoded
request.cookiesthe Cookie headers
request.postDatathe body as text, or form params, when it is UTF-8 text
response.contentplain text for UTF-8 text, base64 with encoding otherwise
response.cookiesSet-Cookie headers, Expires converted to ISO 8601
response.redirectURLthe Location header
bodySizethe byte count, or -1 when a Content-Encoding hides it
headersSize-1: the bytes on the wire depend on the HTTP stack
entry.timethe sum of the timings, as HAR 1.2 requires

Features

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)

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.

17HAR 1.2 objects, each a Codable, Hashable, Sendable value type
0dependencies for HARKit; FoundationEssentials on Linux, no FoundationNetworking
4CI builds on every change: Linux on Swift 6.0, 6.1 and 6.2, and macOS, plus API-breakage, DocC and architecture checks
1.35×faster entry building in 0.1.1, with a fifth fewer allocations
Benchmark (p50, Apple silicon)0.1.00.1.1
Build an entry from a request and its response25.9 µs19.2 µs
Build a request (query string, cookies, JSON body)9.5 µs8.1 µs
Build a response (two Set-Cookie headers, JSON body)15.9 µs10.9 µs
Encode a 1000-entry log to JSON59.7 ms58.4 ms
Decode a 1000-entry log71.8 ms70.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.

Package.swift
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 for URLRequest, HTTPURLResponse and URLSessionTaskTransactionMetrics. Re-exports HARKit.
  • API reference on the Swift Package Index; guide, missing-data advice and specification notes in the README.