To run from the x402 repo instead: clone coinbase/x402, then from the python examples root follow the requests example, copy .env-local to .env, and run the example.
This example loads your env, creates a sync x402 client (x402ClientSync), registers the EVM and/or SVM payment schemes, uses x402_requests(client) as a context manager to get a session, makes a GET request, and logs the response body and payment settlement from the response headers.
Copy
"""x402 requests client example - sync HTTP with automatic payment handling."""import osimport sysfrom dotenv import load_dotenvfrom eth_account import Accountfrom x402 import x402ClientSyncfrom x402.http import x402HTTPClientSyncfrom x402.http.clients import x402_requestsfrom x402.mechanisms.evm import EthAccountSignerfrom x402.mechanisms.evm.exact.register import register_exact_evm_clientfrom x402.mechanisms.svm import KeypairSignerfrom x402.mechanisms.svm.exact.register import register_exact_svm_client# Load environment variablesload_dotenv()def validate_environment() -> tuple[str | None, str | None, str, str]: """Validate required environment variables. Returns: Tuple of (evm_private_key, svm_private_key, base_url, endpoint_path). Raises: SystemExit: If required environment variables are missing. """ evm_private_key = os.getenv("EVM_PRIVATE_KEY") svm_private_key = os.getenv("SVM_PRIVATE_KEY") base_url = os.getenv("RESOURCE_SERVER_URL") endpoint_path = os.getenv("ENDPOINT_PATH") missing = [] if not evm_private_key and not svm_private_key: missing.append("EVM_PRIVATE_KEY or SVM_PRIVATE_KEY") if not base_url: missing.append("RESOURCE_SERVER_URL") if not endpoint_path: missing.append("ENDPOINT_PATH") if missing: print(f"Error: Missing required environment variables: {', '.join(missing)}") print("Please copy .env-local to .env and fill in the values.") sys.exit(1) return evm_private_key, svm_private_key, base_url, endpoint_pathdef main() -> None: """Main entry point demonstrating requests with x402 payments.""" # Validate environment evm_private_key, svm_private_key, base_url, endpoint_path = validate_environment() # Create x402 client (sync variant for requests) client = x402ClientSync() # Register EVM payment scheme if private key provided if evm_private_key: account = Account.from_key(evm_private_key) register_exact_evm_client(client, EthAccountSigner(account)) print(f"Initialized EVM account: {account.address}") # Register SVM payment scheme if private key provided if svm_private_key: svm_signer = KeypairSigner.from_base58(svm_private_key) register_exact_svm_client(client, svm_signer) print(f"Initialized SVM account: {svm_signer.address}") # Create HTTP client helper for payment response extraction (sync) http_client = x402HTTPClientSync(client) # Build full URL url = f"{base_url}{endpoint_path}" print(f"Making request to: {url}\n") # Make request using context manager for proper cleanup with x402_requests(client) as session: response = session.get(url) print(f"Response status: {response.status_code}") print(f"Response body: {response.text}") # Extract and print payment response if present if response.ok: try: settle_response = http_client.get_payment_settle_response( lambda name: response.headers.get(name) ) print( f"\nPayment response: {settle_response.model_dump_json(indent=2)}" ) except ValueError: print("\nNo payment response header found") else: print(f"\nRequest failed (status: {response.status_code})")if __name__ == "__main__": main()
You can test payments against a local server by running the fastapi example or the flask example from the x402 repository.Just set your environment variables to match your local server, install the dependencies, and run the examples.
You can also test your client against PayAI’s live Echo Merchant for free. You will receive a full refund of any tokens that you send, and PayAI will pay for the network fees.