HAR File Writer

0.4.0 · active · verified Sun Apr 12

harfile is a zero-dependency Python library designed for writing HTTP Archive (HAR) files. It provides a straightforward way to construct HAR-compliant logs of HTTP requests and responses programmatically. The library is currently at version 0.4.0 and maintains a stable API for its core functionality.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a HAR file by adding HTTP entries. It shows examples of writing to a physical file and an in-memory string buffer, including basic request and response details.

import datetime
import io
from harfile import open, Request, Response, Timings

# Example 1: Write to a file
with open("example.har") as har_file:
    har_file.add_entry(
        startedDateTime=datetime.datetime.now(datetime.timezone.utc),
        time=42,
        request=Request(
            method="GET",
            url="http://example.com",
            httpVersion="HTTP/1.1",
        ),
        response=Response(
            status=200,
            statusText="OK",
            httpVersion="HTTP/1.1",
        ),
        timings=Timings(
            send=0,
            wait=0,
            receive=0,
        ),
    )

# Example 2: Write to a string buffer
buffer = io.StringIO()
with open(buffer) as har_buffer:
    har_buffer.add_entry(
        startedDateTime=datetime.datetime.now(datetime.timezone.utc),
        time=100,
        request=Request(
            method="POST",
            url="http://api.example.com/data",
            httpVersion="HTTP/1.1",
            headers=[{"name": "Content-Type", "value": "application/json"}],
            postData={
                "mimeType": "application/json",
                "text": "{\"key\": \"value\"}"
            }
        ),
        response=Response(
            status=201,
            statusText="Created",
            httpVersion="HTTP/1.1",
            content={
                "mimeType": "application/json",
                "text": "{\"status\": \"success\"}"
            }
        ),
        timings=Timings(
            send=5,
            wait=50,
            receive=45,
        ),
    )

print("HAR file 'example.har' created.")
print("HAR content written to string buffer (first 200 chars):\n", buffer.getvalue()[:200])

view raw JSON →