Skip to content

About

requests-shaped Python client with real browser fingerprints: TLS ClientHello, HTTP/2 SETTINGS and header order from the Rust rust-curl-impersonate engine, shipped as an in-process C ABI library (339 profiles, stream, WebSocket, HTTP/3)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

 
 

Repository files navigation

requests-python

English | 简体中文

A requests-shaped Python HTTP client whose browser fingerprints are real: every request sends the chosen Chrome / Firefox / Safari / okhttp preset's TLS ClientHello, HTTP/2 SETTINGS and pseudo-header order. The fingerprint engine lives once, in Rust (rust-curl-impersonate), and ships inside this package as a C ABI shared library — no subprocess, no system libcurl-impersonate lookup, just ctypes.

import requests_core as requests

r = requests.get("https://tls.peet.ws/api/all", profile="chrome150")
echo = r.json()
print(r.status_code, r.http_version)      # 200 HTTP/2.0
print(echo["tls"]["ja4"])                 # t13d1516h2_8daaf6152771_d8a2da3f94cd

Why another client?

curl_cffi also impersonates browsers. The difference is the engine and the packaging:

requests_core curl_cffi
Language of the engine Rust (wreq + BoringSSL) C (libcurl-impersonate)
How the native code is reached in-process ctypes to one shared library per platform in-process cffi to libcurl
Presets the 48 curl-impersonate presets plus ~290 fingerprint-library records captured from real browser and runtime processes (Chromium 156–160, Firefox 158–162, Go, Java, Node, curl, …) the curl-impersonate presets
Adding a fingerprint register a JSON record at runtime (load_fingerprints), or edit the library rebuild libcurl
Wiring with other languages one C ABI (rci.h, 24 functions) read by Java, Go, Node, PHP, C#, Ruby and Dart bindings its own Python bindings only

Both are honest about limits: the Rust engine's ClientHello is BoringSSL's, so a captured extension BoringSSL cannot send is listed in the record's deviation instead of silently dropped.

Install

pip install .                      # builds a wheel with this platform's library
python3 scripts/embed_native.py    # only if requests_core/native/ is absent

A wheel carries one platform's shared library (10–12 MB); the repository vendors Linux (gnu and musl), macOS and Windows, x86_64 and aarch64, so a clone works everywhere.

Requires Python 3.8+. No Rust toolchain and no other Python dependency at runtime.

API

Module-level verbs — each opens a short-lived session:

requests_core.request(method, url, **kw)
requests_core.get / post / put / patch / delete / head / options(url, **kw)

Session — reuses connections and cookies, keeps per-session defaults:

Session(profile=..., timeout=..., verify=..., proxy=..., proxy_auth=...,
        headers=..., http1=..., follow_safe=..., base_url=..., retry=...,
        raise_for_status=..., cookies=..., max_filesize=..., interface=...,
        cert=...)

ja3="771,4865-...,..." registers a fingerprint record built from the JA3 string (its cipher ids, curve ids and extension order overlaid on chrome150) and sends that request with it; impersonate="chrome150:no" selects a preset without its own default headers, curl's --impersonate flag.

interface="enp5s0" binds outbound sockets to a NIC (curl's CURLOPT_INTERFACE); cert="client.p12" (or cert=("client.p12", "passphrase")) presents a client certificate for mTLS, curl's CURLOPT_SSLCERT/CURLOPT_SSLKEY.

  • One session per thread. Every engine call blocks the calling thread and a handle is not thread-safe.
  • Per request: headers, body, data (dict/pairs → form-encoded), json, files (multipart, binary-safe), params, cookies, auth (Basic), allow_redirects, retry, raise_for_status, timeout, stream, max_filesize, referer, accept_encoding, default_encoding, discard_cookies, content_callback, max_redirects, http_version, proxies/proxy/proxy_auth, verify, interface, cert, impersonate, ja3, default_headers, akamai (a handle option: the h2 shape, settings|window_update|pseudo_order), extra_fp, multipart (CurlMime), quote, base_url, http3. The full curl_cffi name — all 32 parameters — is accepted. Redirects are followed by default; allow_redirects=False stops at the first response, follow_safe=True also refuses redirects to private addresses.
  • Session(verify=False) is curl's -k: the certificate chain and hostname are not checked; everything else, including the TLS ClientHello, is unchanged.
  • session.websocket(url) returns a WebSocket with send_text / send_bytes, recv() (a {"kind","body","body_is_text"} frame) and close(). The upgrade carries the profile's ClientHello and the preset's WebSocket headers, because it goes through the same emulated client.
  • stream=True reads the body through the engine's chunk callback, so large responses are consumed incrementally instead of as one JSON document.
  • profile is any name from requests_core.profiles(): the 48 presets (chrome150, firefox155, safari260, okhttp5, tor145, …) plus the fingerprint-library records (chrome160, go1.23, …). Default chrome150. profile_info(name) reports family, platform, fidelity, deviation and whether HTTP/3 is available.
  • load_fingerprints(document) registers records for this process — a bare record, a list, or {"fingerprints": [...]}.
  • http3_get(profile, addr, host, path) sends one GET over QUIC.
  • cookies is a session cookie jar (Session(cookies=...), or a curl_cffi.requests.Cookies / requests jar); a per-request cookies= overlays it.
  • max_filesize is curl's option of the same name: "2K", "3M" or a byte count. A response above it raises ResponseError.
  • A per-request timeout goes through rci_request_with_options, so the Response also carries elapsed_ms, elapsed, download_size, primary_ip and primary_port.
  • Session.cookie_jar() returns the engine's jar with each cookie's attributes (name, value, domain, path, secure, http_only, expires); Session.options() reports the handle's settings.
  • Response exposes status_code, http_version, url, headers (case-insensitive), text, content, json(), iter_content(), iter_lines(), raise_for_status(), ok, cookies, redirects. A non-UTF-8 body comes back as bytes through content; text raises for it.

Form encoding, multipart, Basic auth and cookies are assembled in Python (requests_core/_encode.py), the way curl_cffi does it, so they work without a wider ABI.

Command line

python -m requests_core https://tls.peet.ws/api/all
python -m requests_core -X POST -H 'Content-Type: application/json' -d '{"a":1}' https://httpbin.org/post
python -m requests_core --json -v https://tls.peet.ws/api/all
python -m requests_core --profiles | head
python -m requests_core --profile-info firefox155
python -m requests_core -k --timeout 5 https://self-signed.badssl.com/

requests-core is installed as a console script too. A failed request exits 1 with the typed error on stderr; -v prints the HTTP version, timing, peer address and body/header sizes.

Errors

Errors are typed and carry curl's error code, like curl_cffi:

situation class .code
refused / reset connection ConnectionError 7
unresolvable host DNSError 6
timeout Timeout 28
certificate / handshake SSLError 35 / 60
redirect limit TooManyRedirects 47
bare host, no scheme MissingSchema 3
unsupported scheme InvalidSchema 1
stopped by Session.terminate() TerminatedError 42
unknown profile ImpersonateError (with close matches listed) —

Every one subclasses RequestException, which subclasses the package's original RciError, so an existing except RciError keeps working.

requests_core.exceptions.advice(error) returns a one-line fix ("raise timeout= or use timeout=(connect, read)"), and the CLI prints it after the error. A certificate failure is told apart from a refused socket by a single verify-off retry on the same URL, so a self-signed host raises SSLError with code 60.

Handy helpers

with requests_core.Session() as s:
    s.download("https://example.com/logo.png", "logo.png")   # fetch and save
    r = s.get("https://tls.peet.ws/api/all")
    print(r.info())          # status, timing, peer, sizes as one dict
    r.show()                 # print the status line and body, return self
    r.save("body.json")      # write the body only

trust_env=True (the default) honours http_proxy/https_proxy/all_proxy and no_proxy per request; trust_env=False ignores them entirely. verify= takes True, False, or a CA bundle path (also read from REQUESTS_CA_BUNDLE / CURL_CA_BUNDLE).

params keeps repeated keys ([("a", 1), ("a", 2)] → a=1&a=2), cookies from a response can seed a new Session, and set_default_profile("firefox155") switches what the module-level verbs start from.

How the native library is loaded

Each OS's own dynamic linker, through the standard library — not a subprocess and not an external CLI binary:

OS File Loader
Linux librust_curl_impersonate_ffi.so glibc dlopen
macOS librust_curl_impersonate_ffi.dylib dyld
Windows rust_curl_impersonate_ffi.dll LoadLibrary

ctypes.CDLL(path) calls CPython's _ctypes extension, which calls that loader and maps the library into the interpreter's address space (on Linux it appears in /proc/self/maps after the load). tests/test_requests_core.py asserts both that the loader is an in-process ctypes.CDLL and that the package contains no subprocess/exec call.

Limits of the C ABI

Surfaced rather than papered over:

  • One handle per thread. Every call blocks.
  • A binary body cannot carry per-request headers. The ABI has two request calls: one takes a length-delimited byte body without headers, the other a string body with headers. The wrapper raises ValueError instead of dropping one side; set a Content-Type on the Session instead.
  • Streaming is incremental, not lazy. stream=True decodes the body as it arrives but collects it into the Response before returning, so iter_content on a live socket is not what this does yet.
  • ja3= and akamai= are accepted (handle-level: the cipher/curve lists and the h2 shape). extra_fp has no parameter of its own — register a fingerprint record with load_fingerprints instead — and perk= raises, because the engine has no PERK parser.

Built case by case from the engine's own contract

The engine publishes two machine-readable files, vendored next to the library:

  • abi-lock.json — all 24 rci_* functions with their exact C signatures and the ABI version each arrived in;
  • abi-shapes.json — the frozen key set of every structured JSON return.

At load time requests_core/_contract.py checks the ctypes layer against both: every locked function must be bound, every signature must match the lock's spelling (char * vs const char * is the ownership rule, so it counts), and every JSON return must carry exactly the frozen keys. A function the engine adds but this binding has not bound fails at load, with the name in the message. tests/test_contract.py also asserts every public entry point maps onto a locked function, so the Python surface cannot drift from the ABI that the Java, Go, Node, PHP, C#, Ruby and Dart bindings read too.

Upgrading the vendored library

The package pins one engine release in requests_core/native/MANIFEST.json (tag, ABI version, sha256 of every vendored file).

Task Command Network
Upgrade to the newest release python3 scripts/embed_native.py GitHub release download (no API token)
Upgrade to a specific tag python3 scripts/embed_native.py --tag v0.4.0 same
Vendor from a local Rust build python3 scripts/embed_native.py --from-dir ~/.../rust-curl-impersonate none
Vendor from downloaded archives python3 scripts/embed_native.py --from-archives <dir> --tag v0.3.0 none
Show pinned tag / ABI python3 scripts/native_versions.py status none
CI gate: files unchanged, host ABI ≥ manifest python3 scripts/native_versions.py check none

Every archive is verified against the release's SHA256SUMS before it is unpacked, and the newest tag is read from the /releases/latest redirect so no API token is needed. Compatibility follows the upstream contract: ABI 3 keeps ABI 2's signatures and only adds functions, so the binding accepts any library >= 2; an older one raises on load with the exact version.

Layout

requests_core/
  __init__.py       public requests-shaped API, Session, WebSocket, Response
  _ffi.py           ctypes binding; signatures parsed from the shipped rci.h
  _contract.py      runtime check against abi-lock.json / abi-shapes.json
  _encode.py        form, multipart, Basic auth, Cookie header
  _response.py      Response object
  _structures.py    case-insensitive headers
  native/<triple>/  library + rci.h
  native/MANIFEST.json      pinned tag, ABI, sha256 of every vendored file
scripts/embed_native.py     refresh native/ from a release, local build or archives
scripts/native_versions.py  manifest refresh / check / status
scripts/api_audit.py        native functions vs the public Python surface
tests/                      offline pytest suite against a local server
example/                    runnable examples

Develop

python3 scripts/embed_native.py --target x86_64-unknown-linux-gnu   # vendor host
python3 -m pytest tests -q                                          # offline
REQUESTS_CORE_LIVE=1 python3 -m pytest tests -q                     # + public JA4 check
python3 scripts/api_audit.py                                        # surface alignment

History

This repository began as a fork of wangluozhe/requests-go, a Go-engine wrapper. That Go code is gone; the current tree is a full rewrite on top of requests_core and its vendored rust-curl-impersonate library.

License: MIT.

About

requests-shaped Python client with real browser fingerprints: TLS ClientHello, HTTP/2 SETTINGS and header order from the Rust rust-curl-impersonate engine, shipped as an in-process C ABI library (339 profiles, stream, WebSocket, HTTP/3)

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages