requests Client
The x402 Python package provides a session wrapper for the requests library that automatically handles x402 payment flows. When a server responds with 402 Payment Required, the session constructs a payment payload, settles it through the facilitator, and retries the request transparently.
Installation
bash
pip install requests eth-account x402 python-dotenvEnvironment Setup
Create a .env file in your project root:
RESOURCE_SERVER_URL=https://api.example.com
ENDPOINT_PATH=/api/premium/data
PRIVATE_KEY=0xYOUR_PRIVATE_KEY| Variable | Description |
|---|---|
RESOURCE_SERVER_URL | Base URL of the resource server. |
ENDPOINT_PATH | Path to the paid endpoint. |
PRIVATE_KEY | Your Ethereum-compatible private key. |
Usage
python
import os
from dotenv import load_dotenv
from eth_account import Account
from x402.client.requests import x402Session
from x402.types import decode_x_payment_response
load_dotenv()
RESOURCE_SERVER_URL = os.getenv("RESOURCE_SERVER_URL")
ENDPOINT_PATH = os.getenv("ENDPOINT_PATH")
PRIVATE_KEY = os.getenv("PRIVATE_KEY")
account = Account.from_key(PRIVATE_KEY)
def main():
session = x402Session(account=account)
url = f"{RESOURCE_SERVER_URL}{ENDPOINT_PATH}"
response = session.get(url)
print("Response:", response.json())
if "X-Payment-Response" in response.headers:
payment = decode_x_payment_response(response.headers["X-Payment-Response"])
print("Payment:", payment)
main()How It Works
x402Session(account)creates arequests.Sessionsubclass that monitors responses for402 Payment Requiredstatus codes.- When the server responds with
402, the session reads the payment requirements from the response headers. - It constructs a signed payment payload using your Ethereum account and submits it to the facilitator at
https://facilitator.svmacc.tech. - The original request is retried with the
X-Paymentheader containing the settled payment proof. - The server validates the payment and returns the resource.
Reading the Payment Response
After a successful paid request, the server includes an X-Payment-Response header. Use decode_x_payment_response to parse it:
python
if "X-Payment-Response" in response.headers:
payment = decode_x_payment_response(response.headers["X-Payment-Response"])
print("Transaction hash:", payment.tx_hash)This header contains details about the settled payment, including the on-chain transaction hash.
Notes
- Unlike the httpx client,
x402Sessionis synchronous and does not requireasync/await. - The session supports all standard
requests.Sessionfeatures, including custom headers, authentication, and connection pooling. - You must provide the full URL (base URL + endpoint path) when making requests, as
x402Sessiondoes not accept abase_urlparameter. - Payments are only triggered when the server responds with a
402status code. All other responses pass through unchanged. - Keep your private key secure. Never commit
.envfiles to version control.