HAR File Writer
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
- gotcha The `harfile` library is designed with the assumption of a single-threaded environment. Using it in a multi-threaded application without proper synchronization could lead to unexpected behavior or data inconsistencies in the generated HAR file.
- gotcha The `harfile` library explicitly states that 'Pages are not supported'. This means the generated HAR file will not contain the 'pages' array, which is an optional but common top-level object in the HAR specification.
- gotcha HAR files, by their nature, can contain sensitive information such as authentication tokens, cookies, and request/response bodies. Users generating HAR files should be aware of this and exercise caution when sharing these files.
Install
-
pip install harfile
Imports
- open
from harfile import open
- Request
from harfile import Request
- Response
from harfile import Response
- Timings
from harfile import Timings
Quickstart
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])