FOR AGENT BUILDERS · 11 MIN READ

How Do AI Agents Pay for APIs? A Practical Walkthrough

Working JavaScript and Python code for handling an x402 402 response end to end: detecting it, picking a payment option, settling it, and retrying — plus the mistakes that trip up a first implementation.

This is the practical companion to What Is x402? — actual code for the client side: catching a 402, choosing how to pay, settling it, and retrying successfully.

The shape of the problem

Handling x402 correctly means treating 402 as an expected, structured response — not an error to catch and give up on. The response body tells you everything you need:

{
  "x402Version": 2,
  "accepts": [
    { "scheme": "exact", "network": "eip155:8453", "payTo": "0x...",
      "asset": "0x...USDC", "amount": "10000", "maxTimeoutSeconds": 120 }
  ]
}

JavaScript: a minimal client

async function callX402Resource(url, wallet) {
  let res = await fetch(url);
  if (res.status !== 402) return res; // already free, or an unrelated error

  const { accepts } = await res.json();

  // Pick the first option your wallet can actually settle — in practice,
  // filter by network (does your wallet hold funds there?) and by asset.
  const option = accepts.find((a) => wallet.supportsNetwork(a.network));
  if (!option) throw new Error('no payable option for this wallet');

  // Settling is wallet/library-specific. A facilitator-backed client
  // (see the x402 protocol guide) reduces this to a sign + submit call —
  // you are not writing raw transaction construction code here.
  const paymentSignature = await wallet.pay(option);

  res = await fetch(url, {
    headers: { 'PAYMENT-SIGNATURE': paymentSignature },
  });
  return res; // 200 with the resource, or another 402 if payment didn't verify
}

Python equivalent

import httpx

def call_x402_resource(url: str, wallet) -> httpx.Response:
    res = httpx.get(url)
    if res.status_code != 402:
        return res

    accepts = res.json()["accepts"]
    option = next((a for a in accepts if wallet.supports_network(a["network"])), None)
    if option is None:
        raise RuntimeError("no payable option for this wallet")

    payment_signature = wallet.pay(option)
    return httpx.get(url, headers={"PAYMENT-SIGNATURE": payment_signature})

Real-world details that matter

Using the MCP tool instead of raw HTTP

If your agent already speaks MCP, get_pricing on Agent Bazaar's MCP server gives you a resource's accepts[] without an extra round trip:

curl -X POST https://bazaar.saylorinnovations.com/mcp \
  -H "content-type: application/json" \
  -d '{"jsonrpc":"2.0","id":1,"method":"tools/call",
       "params":{"name":"get_pricing","arguments":{"slug":"solana-token-security-intelligence"}}}'

You still pay directly against the resource's own endpoint, not through MCP — the tool call just saves you a lookup.

Testing without spending real money

Start with the free discovery endpoints (/discovery/search costs nothing) to confirm your agent's HTTP plumbing works, then move to a low-cost resource like Solana Token Price ($0.001) to validate the full payment round trip before wiring up anything expensive.

Related guides

What Is x402? A Complete Guide to the Protocol

The full picture of x402: where the HTTP 402 status code came from, exactly what happens on the wire during a payment, the scheme and network model, and how it compares to the alternatives.

How to Build an x402 Endpoint

A complete, working walkthrough of building an x402-payable API endpoint on Cloudflare Workers: the 402 response, verifying payment, and the manifest that makes it discoverable.

x402 vs. API Keys: A Thorough Comparison

Security, UX, cost structure and operational overhead, compared directly — plus a practical migration path if you already run a key-based API.

Machine-readable

Plain-text version for agents: /guides/how-do-ai-agents-pay-for-apis.json.