API guide

What is x402? HTTP 402 payments for APIs and AI agents

HTTP reserved status 402 for payments decades ago and then left it empty. x402 finally gives it a job: letting software pay for exactly one request, with no account in between.

On this page
  1. The x402 protocol round trip, step by step
  2. Anatomy of an HTTP 402 challenge
  3. Pay from code: a Node.js client with a spending cap
  4. Production and sandbox gateways
  5. What each call costs
  6. x402, an API key plan or MCP: pick the right door
  7. Guardrails before you give an agent a wallet
  8. Selling an API over x402: what the server must get right
  9. Why HTTP 402 sat unused for so long
  10. Questions

Key takeaways

  • x402 is an open protocol built on HTTP 402 Payment Required: the server states an exact price, the client signs a payment and retries, and the data comes back on that retry.
  • TickerLayer runs x402 in USDC on Base mainnet at https://x402.tickerlayer.com, with a Base Sepolia sandbox using test USDC at https://x402-testnet.tickerlayer.com.
  • No account or API key is needed: 41 REST resources cover stocks, forex, crypto, indices, ETFs, commodities, bond yields and market calendars, from $0.01 a call.
  • The gateway validates the route, parameters and returned data before settlement, so malformed, failed or empty responses are not charged.
  • x402 suits occasional, autonomous calls; sustained or streaming workloads cost far less on a plan with an API key.

x402 is an open payment protocol built on the HTTP status code 402 Payment Required. A client requests a resource; the server answers 402 with a machine-readable price; the client signs a stablecoin payment for exactly that amount and retries the same request with the proof attached; the server checks it, returns the data and settles. No sign-up, no API key, no invoice at the end of the month.

That shape suits AI agents, which can hold a wallet but cannot fill in a signup form. TickerLayer runs x402 in production for market data, so this guide uses real responses from https://x402.tickerlayer.com instead of a diagram of a hypothetical API. If your agent already has a TickerLayer account, the financial MCP server is usually the better door; the comparison near the end shows where each one wins.

The x402 protocol round trip, step by step

Agentx402 gatewayBase network
  1. GET /v1/stocks/quote/US:KOno API key, no accountAgent to x402 gateway
  2. 402 Payment RequiredPAYMENT-REQUIRED: exact, eip155:8453, amount 10000x402 gateway to Agent
  3. Check and signscheme, network and amount under your cap
  4. Same GET + PAYMENT-SIGNATUREsigned USDC authorization and payment identifierAgent to x402 gateway
  5. Validate and prepareroute, parameters and data checked before any charge
  6. Settle USDC transferx402 gateway to Base network
  7. ConfirmedBase network to x402 gateway
  8. 200 OK + JSONPAYMENT-RESPONSE carries the settlement resultx402 gateway to Agent
One paid call. The first two messages were captured from the production gateway on 2026-09-28; the paid leg follows the x402 version 2 exact scheme.

The first move is an ordinary GET with nothing attached. Here is the production gateway answering it:

RequestShell
curl --include 'https://x402.tickerlayer.com/v1/stocks/quote/US:KO'
Response (trimmed)HTTP
HTTP/2 402
content-type: application/json; charset=utf-8
cache-control: no-store
payment-required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIiwicmVzb3VyY2UiOnsidXJsIjoiaHR0cHM6Ly94NDAy...

{"error":"payment_required","message":"This TickerLayer resource requires an x402 payment.","endpoint":"stocks.quote"}

The JSON body is for humans reading logs. The part a client acts on is the PAYMENT-REQUIRED header: base64-encoded JSON that names the price, the network and who gets paid. The client decides whether it is willing to pay, signs a transfer authorization with its wallet, and sends the identical request again with a PAYMENT-SIGNATURE header. Only then does the gateway fetch, validate and return the data.

Anatomy of an HTTP 402 challenge

You can read a challenge without any x402 library. This pipeline pulls the header out of a response and decodes it:

Decode the challengeShell
curl -s -D - -o /dev/null 'https://x402.tickerlayer.com/v1/stocks/quote/US:KO' \
  | awk 'tolower($1)=="payment-required:" {print $2}' \
  | tr -d '\r' | base64 --decode | python3 -m json.tool

Decoded PAYMENT-REQUIRED for a stock quote

{
  "x402Version": 2,1
  "error": "Payment required",
  "resource": {
    "url": "https://x402.tickerlayer.com/v1/stocks/quote/US:KO",
    "mimeType": "application/json"
  },
  "accepts": [{2
    "scheme": "exact",3
    "network": "eip155:8453",4
    "amount": "10000",5
    "asset": "0x8335...2913",6
    "payTo": "0x7Dc9...0dAC",
    "maxTimeoutSeconds": 60,
    "extra": { "name": "USD Coin", "version": "2" }
  }],
  "extensions": {
    "payment-identifier": { "info": { "required": true } }7
  }
}
  1. x402VersionProtocol version 2. Refuse versions your client was not built for.
  2. acceptsThe ways this resource can be paid. Pick one whose scheme and network you expect and ignore the rest.
  3. schemeexact: pay precisely amount, no more and no less.
  4. networkA chain ID: eip155:8453 is Base mainnet. The sandbox answers eip155:84532, Base Sepolia.
  5. amountAtomic units of USDC, which has six decimals: 10000 is $0.01.
  6. assetThe USDC token contract on that network; payTo is the receiving address. Both shortened here.
  7. payment-identifierRequired. The client attaches a unique ID so a retried request returns the stored response instead of paying twice.
Decoded from the production gateway on 2026-09-28, trimmed. The live challenge for your exact request, not this page, is the authoritative price.

price in USD = amount ÷ 1,000,000

amount
Atomic units from the challenge, a string of digits.
1,000,000
USDC has six decimals, so one dollar is a million units.
10000 ÷ 1,000,000 = $0.01. A spending cap of $0.10 is 100,000 units, the limit the client below enforces.

The full header also carries discovery metadata: the route template (/v1/stocks/quote/:symbol), the path parameters of this request, a JSON Schema for the input and an example of the output. An agent or a marketplace can list and describe the resource from the challenge alone, without reading documentation first.

Pay from code: a Node.js client with a spending cap

The x402 client libraries handle signing and the retry. Your job is to decide what the client may pay. This is the example from the x402 page, pointed at US:KO: it accepts only the exact scheme on the configured network, refuses anything above 100,000 units ($0.10), and attaches a payment identifier before signing.

paid-quote.mjsJavaScript
// npm install @x402/fetch @x402/evm @x402/extensions viem
import { wrapFetchWithPayment, x402Client } from "@x402/fetch";
import { ExactEvmScheme } from "@x402/evm/exact/client";
import {
  appendPaymentIdentifierToExtensions,
  generatePaymentId,
} from "@x402/extensions/payment-identifier";
import { privateKeyToAccount } from "viem/accounts";

const baseUrl = process.env.X402_BASE_URL ?? "https://x402.tickerlayer.com";
const network = process.env.X402_NETWORK ?? "eip155:8453";
const privateKey = process.env.X402_AGENT_PRIVATE_KEY;
if (!privateKey) throw new Error("X402_AGENT_PRIVATE_KEY is required");

const account = privateKeyToAccount(privateKey);
const client = new x402Client((version, requirements) => {
  if (version !== 2) throw new Error("Unsupported x402 version");
  const selected = requirements.find((requirement) => {
    const amount = BigInt(requirement.amount);
    return requirement.scheme === "exact" &&
      requirement.network === network && amount > 0n && amount <= 100_000n;
  });
  if (!selected) throw new Error("No approved payment requirement");
  return selected;
});

client.register(network, new ExactEvmScheme(account));
const paymentId = generatePaymentId("tl_agent_");
client.onBeforePaymentCreation(async ({ paymentRequired }) => {
  if (!paymentRequired.extensions) throw new Error("Payment ID not declared");
  appendPaymentIdentifierToExtensions(paymentRequired.extensions, paymentId);
});

const paidFetch = wrapFetchWithPayment(fetch, client);
const response = await paidFetch(baseUrl + "/v1/stocks/quote/US:KO");
if (!response.ok) throw new Error(`x402 request failed: ${response.status}`);
console.log(await response.json());

Point it at the sandbox first: set X402_BASE_URL=https://x402-testnet.tickerlayer.com and X402_NETWORK=eip155:84532, fund a throwaway wallet with test USDC, and the same code pays with play money. A successful call prints the same JSON shape the REST quote endpoint returns:

Response body shape (captured from GET /stocks/quote/US:KO)JSON
{"symbol":"US:KO","bid":88.11,"ask":88.3,"bid_size":400,"ask_size":200,"timestamp":1790590887491}

Production and sandbox gateways

FeatureProductionSandbox
Originx402.tickerlayer.comx402-testnet.tickerlayer.com
NetworkBase mainnet, eip155:8453Base Sepolia, eip155:84532
Payment assetUSDCtest USDC
Real money
Resources4141
Public /ready and /catalog
Account or API key
Same paths, same prices, separate networks. Switch the gateway and the network together, never one without the other.

Both gateways publish /ready for health and /catalog for every resource with its price policy. A readiness result describes the gateway at the moment you checked; it is not a promise of uninterrupted availability, and it does not replace reading the 402 challenge before you pay.

What each call costs

  • 41REST resources
  • $0.01lightest call
  • 25items max in a bulk status call
  • 0accounts or API keys
ResourcePathPrice per call
Quote, last trade, previous bar/v1/{asset}/quote, /trade/last, /agg/{symbol}/prev$0.01
Snapshot, symbol list/v1/{asset}/snapshot, /symbols$0.02
Historical bars, up to 100/v1/{asset}/agg/{symbol}/{multiplier}/{timespan}/{from}/{to}$0.03
Historical bars, up to 500 (default)same$0.05
Historical bars, up to 1,000same$0.10
Bond yield/v1/bond/last/{CC:TENOR}$0.01
Market status, sessions/v1/markets/status, /sessions$0.01
Market holidays/v1/markets/holidays$0.02
Bulk market status/v1/markets/status/bulk$0.01 + $0.002 per extra item
From the production /catalog on 2026-09-28. `{asset}` is stocks, forex, crypto, indices, etfs or commodities; stocks use `MARKET:BASE` symbols such as `US:KO`.

Settlement happens only after the gateway has prepared a valid response. Bad parameters, upstream failures, invalid JSON and empty data stop before any charge, and a retry that reuses the same payment identifier gets the stored response rather than a second bill. Using that identifier for a different request is rejected.

x402, an API key plan or MCP: pick the right door

The deciding comparison is cost at volume. 250,000 quote calls through x402 cost $2,500. An Individual crypto plan includes 250,000 REST calls a month for $49, and the free tier includes 3,000 REST requests a month with no card. x402 wins when calls are rare, bursty or made by software that has a wallet and no account; a plan wins the moment usage is steady. And if the agent is a chat assistant you use yourself, connecting Claude through MCP with a key or an OAuth sign-in is simpler than giving it a wallet.

Featurex402API key planMCP server
Account neededyes, key or OAuth
How you payUSDC per callMonthly plan or free tierSame plan as REST
WebSocket streamingyes, on paid plans
Surface41 REST resourcesFull REST and WebSocket10 read-only tools
Best forOccasional autonomous callsApps and steady workloadsAI clients with typed tools
The data behind all three is the same aggregation. See [pricing](/pricing) for plans.

Whichever door you use, the same engineering applies: the gateway enforces per-endpoint rate limits, so an agent that fans out needs 429 handling with backoff, and it needs to understand the fields it buys. The market data API guide explains quotes, snapshots, bars and timestamp semantics.

Guardrails before you give an agent a wallet

In an agent, x402 belongs inside a tool your code owns, not in the model. The model asks for data; the tool reads the challenge, applies your policy and pays or refuses:

  1. Model requests dataThe agent calls your paid_get tool with a path such as /v1/forex/quote/EURUSD.
  2. Tool reads the priceThe unpaid request returns 402; the tool decodes the amount and network.
  3. Policy decidesScheme, network, per-call cap and the remaining daily budget are checked in code.
  4. Pay, cache, returnThe tool pays, stores the response and hands the JSON back to the model.

Agentic payments checklist

  • Build against the sandbox with a test-only wallet, then switch gateway and network together.
  • Fund a dedicated server-side wallet with a small balance; never reuse a treasury wallet.
  • Accept only scheme exact on the network you configured and reject every other requirement.
  • Cap the per-call amount in code; the example stops at 100,000 units, which is $0.10.
  • Keep a daily spend budget in your code, outside the model. The agent asks; the code pays.
  • Attach a payment identifier so retries return the stored response instead of paying twice.
  • Log the resource URL, amount and settlement result for every paid call.

The same principle runs through the AI trading bot tutorial: a model can propose, but deterministic code decides what actually happens, whether that is a paper order or a payment.

Selling an API over x402: what the server must get right

From the seller side, API monetization with x402 looks simple: return 402, verify, settle. The details decide whether buyers trust it. These are the choices the TickerLayer gateway makes, and they are a reasonable bar for any paid API:

  • Price per route, not per account. A quote and a 1,000-bar history do not cost the same to serve, so the price scales with the work, and a bulk request prices each extra item.
  • Prepare first, settle second. Fetch and validate the data before taking the money. An empty or malformed response should never be billed.
  • Idempotent retries. Networks drop responses. Binding a payment identifier to one canonical request lets a client retry safely and get the stored answer.
  • A separate sandbox. Test money on a test network, same paths and prices, so integrations are proven before real funds move.
  • Public readiness and catalog. Buyers, and their agents, should be able to see what is for sale and whether the gateway is healthy before they sign anything.

Why HTTP 402 sat unused for so long

HTTP/1.1 listed 402 as "reserved for future use" and never said what a payment should look like. Card payments need accounts and cost more to process than a one-cent request is worth, so APIs built monetization around keys and monthly plans instead. Stablecoins on low-fee networks made a one-cent transfer practical, and x402 standardized the headers around it.

Nothing in the protocol is specific to market data. Any HTTP API can price a route this way, which is why x402 keeps coming up in API monetization and agentic payments discussions. What a data API adds is the validation step: a buyer should only pay for a response that is correct and complete, and a gateway that settles before checking the data gets that backwards. TickerLayer data stays derived and indicative whichever way you pay; see the market data disclaimer.

Questions

What is x402?

x402 is an open protocol for paying per HTTP request. The server answers 402 Payment Required with an exact price, the client signs a stablecoin payment and retries, and the server returns the data.

What does HTTP 402 Payment Required mean?

It is the HTTP status code reserved for payments. Under x402 it carries a PAYMENT-REQUIRED header describing the scheme, network, asset and amount the client must pay to get the resource.

Do I need an account or API key to use x402?

No. On the TickerLayer x402 gateway the payment authorization replaces account and API-key authentication for the paid resource.

How much does an x402 market data call cost?

Quotes, last trades, previous bars, bond yields and market status cost $0.01 per call. Snapshots, symbol lists and holidays cost $0.02, and historical bars cost $0.03 to $0.10 depending on how many bars you request.

Does x402 support WebSocket streaming?

No. The TickerLayer x402 surface is REST only. Streaming needs a standard plan with an API key.

Am I charged if an x402 request fails?

No. The gateway validates the route, parameters and returned data before settlement, and malformed, failed, oversized or empty-data responses are not settled.

Keep reading

Ready to integrate?

Start with the free tier, explore the docs, and connect via REST or WebSocket in minutes.