How an Agent Pays a Per-Request API with x402 and USDC on Base
x402 turns HTTP 402 Payment Required into a machine-readable price. Here is switch402's real 402 response and the code an agent uses to pay it and get the page.
Steps
- Call without payment. POST https://api.switch402.com/v1/scrape with {"url": "..."}. The API answers HTTP 402 with the payment terms in the JSON body and in a base64 PAYMENT-REQUIRED header.
- Read the terms. accepts[0] says: scheme exact, network eip155:8453 (Base), asset USDC, amount 8000 (6 decimals = $0.008), maxTimeoutSeconds 60.
- Sign and retry. An x402 client signs a USDC transfer authorization for that amount and repeats the request with the payment header.
- Get the result. The payment is verified, the page is fetched, and the payment settles only after content comes back. If every provider fails you get a 502 and pay nothing.
Code
switch402 402 response (body, trimmed; payee shown as a placeholder)
HTTP/2 402
content-type: application/json
payment-required: <base64 of the same JSON>
{
"x402Version": 2,
"error": "Payment required",
"resource": { "url": "https://api.switch402.com/v1/scrape", "mimeType": "application/json" },
"accepts": [{
"scheme": "exact",
"network": "eip155:8453",
"amount": "8000",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"payTo": "<payee address from the live response>",
"maxTimeoutSeconds": 60,
"extra": { "name": "USD Coin", "version": "2" }
}]
}See it yourself (free, nothing is paid)
curl -i -X POST https://api.switch402.com/v1/scrape \
-H 'Content-Type: application/json' -H 'User-Agent: my-agent/1.0' \
-d '{"url":"https://example.com"}'JavaScript: pay and retry automatically
// npm i @x402/fetch @x402/evm viem
import { wrapFetchWithPaymentFromConfig } from '@x402/fetch'
import { ExactEvmScheme } from '@x402/evm'
import { privateKeyToAccount } from 'viem/accounts'
const account = privateKeyToAccount(process.env.AGENT_KEY)
const fetchWithPayment = wrapFetchWithPaymentFromConfig(fetch, {
schemes: [{ network: 'eip155:8453', client: new ExactEvmScheme(account) }],
})
const res = await fetchWithPayment('https://api.switch402.com/v1/scrape', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'User-Agent': 'my-agent/1.0' },
body: JSON.stringify({ url: 'https://example.com' }),
})
console.log(res.status, (await res.json()).markdown)You pay only for the pages you actually fetch: $0.008 per standard page on /v1/scrape, $0.003 per lite call on /v1/scrape/lite, in USDC on Base and charged only on success. No subscription or unused credits; optional prepaid packs and a $10 monthly plan.
FAQ
- What does amount 8000 mean?
- USDC has 6 decimals, so 8000 units is $0.008. The lite endpoint asks 3000 ($0.003).
- When is the payment taken?
- switch402 verifies the payment first and settles it only after content comes back. If every provider fails you get a 502 and are not charged.
- Which networks are accepted?
- Base (eip155:8453) in USDC, as listed in the live 402 response.