Getting started with requests

Make x402 payments with a Python requests client on XRPL.

Step 1: Install dependencies

pip install requests xrpl-py x402-xrpl python-dotenv

Step 2: Set your environment variables

Create a .env file with your configuration:

RESOURCE_URL=http://localhost:8000/ai-news
XRPL_BUYER_SEED=sEd... # your wallet seed
XRPL_TESTNET_RPC_URL=https://s.altnet.rippletest.net:51234/

Step 3: Create a new requests client

import os
from dotenv import load_dotenv
from xrpl.wallet import Wallet
from x402_xrpl.clients import decode_payment_response, x402_requests

# Load environment variables
load_dotenv()

# Configuration
resource_url = os.getenv("RESOURCE_URL", "http://localhost:8000/ai-news")
buyer_seed = os.getenv("XRPL_BUYER_SEED")
rpc_url = os.getenv("XRPL_TESTNET_RPC_URL", "https://s.altnet.rippletest.net:51234/")

if not buyer_seed:
    print("Error: XRPL_BUYER_SEED not found in .env")
    exit(1)

# Initialize wallet
buyer = Wallet.from_seed(buyer_seed)
print(f"Buyer address: {buyer.classic_address}")

def main():
    # Create requests session with x402 payment handling
    session = x402_requests(
        buyer,
        rpc_url=rpc_url,
        network_filter="xrpl:1",
        scheme_filter="exact",
    )

    print(f"Making request to {resource_url}")
    
    # The session automatically handles:
    # 1. 402 Payment Required response
    # 2. Selecting payment requirements
    # 3. Making the payment on XRPL
    # 4. Retrying the request with payment proof
    response = session.get(resource_url)

    print(f"Response Status: {response.status_code}")
    print(f"Response Body: {response.text}")

    # Check for payment confirmation
    if "PAYMENT-RESPONSE" in response.headers:
        payment_info = decode_payment_response(response.headers["PAYMENT-RESPONSE"])
        print(f"Payment Transaction: {payment_info.get('transaction')}")

if __name__ == "__main__":
    main()

Step 4: Run the client

python main.py

Your client will now automatically pay for resources on the XRPL testnet!