httpx Client
The x402 Python package provides an async HTTP client built on httpx that automatically handles x402 payment flows. When a server responds with 402 Payment Required, the client constructs a payment payload, settles it through the facilitator, and retries the request transparently.
Installation
bash
pip install httpx 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
import asyncio
from dotenv import load_dotenv
from eth_account import Account
from x402.client.httpx import x402HttpxClient
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)
async def main():
async with x402HttpxClient(account=account, base_url=RESOURCE_SERVER_URL) as client:
response = await client.get(ENDPOINT_PATH)
content = await response.aread()
print("Response:", content.decode())
if "X-Payment-Response" in response.headers:
payment = decode_x_payment_response(response.headers["X-Payment-Response"])
print("Payment:", payment)
asyncio.run(main())How It Works
x402HttpxClient(account, base_url)creates an async HTTP client that monitors responses for402 Payment Requiredstatus codes.- When the server responds with
402, the client 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
- The client is used as an async context manager (
async with). This ensures connections are properly cleaned up. - The
base_urlparameter sets the root URL for all requests, so you only need to pass the endpoint path toclient.get(). - 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.