What is Pay-Per-API 402?

HTTP 402 Payment Required is a status code that sits in a strange limbo. Originally defined in the early HTTP specifications, it was marked as "reserved for future use" because the web didn't have a standard way to handle micropayments at the time. For decades, developers ignored it, sticking to custom headers or separate billing APIs for paid access. Today, that code is waking up.

The modern interpretation is driven by the x402 protocol, an open standard developed by Coinbase. Instead of treating 402 as a legacy relic, x402 uses the HTTP 402 status code as a signal for machine-to-machine commerce. When an API endpoint requires payment, it returns a 402 response containing a payment request. The client—often an AI agent or automated script—pays via stablecoin and receives the data. This turns the HTTP protocol itself into a payment rail.

This shift is critical for your Pay-Per-API 402 guide because it changes how you think about access control. You aren't just checking a user's email or credit card; you are checking for a blockchain transaction. The server returns a 402 with a Payment-Required header, and the client must settle the invoice before the data is released. This creates a seamless, instant payment loop that works directly over HTTP, eliminating the friction of traditional gateways for automated systems.

Set up the x402 payment flow

The x402 protocol transforms standard HTTP requests into instant payment channels. Instead of relying on subscriptions or manual invoicing, the server attaches a price to the response, and the client pays immediately via stablecoin to access the data. This section walks you through the four core steps to implement this Pay-Per-API 402 guide flow.

Pay-Per-API 402 in
1
Configure the API endpoint and wallet
Before handling requests, you need a wallet to receive payments and an endpoint to serve the API. The x402 protocol is built into the Coinbase Developer Platform (CDP), which simplifies wallet management. Initialize your server to recognize x402-compatible headers. When a request hits your endpoint, the server must be ready to evaluate the request against your pricing logic and return the appropriate status code.
Pay-Per-API 402 in
2
Inject the price in the 402 response
When a client makes a request, your server should respond with an HTTP 402 status code. This response includes the x-pay-endpoint header, which tells the client where to send the payment, and the x-pay-price header, which specifies the cost in a specific currency or token. The protocol requires you to include the current price in every 402 response so the agent sees the updated cost before paying. This dynamic pricing allows you to adjust rates based on market conditions or compute intensity.
Pay-Per-API 402 in
3
Client signs the payment
The client, typically an AI agent or automated script, receives the 402 response. It extracts the payment details and constructs a transaction. The client signs this transaction using its private key, authorizing the transfer of the specified stablecoin amount to your wallet. This step is fully automated; the client does not need to interact with a browser or approve pop-ups. It simply executes the payment protocol defined by the headers it received.
4
Server verifies and delivers data
Once the client sends the payment, it includes a proof of payment in the headers of a subsequent request. Your server must verify this proof against the blockchain or the CDP settlement layer to ensure the transaction is valid and confirmed. If the payment is successful, the server returns the actual API data with a standard 200 OK status. If the proof is missing or invalid, the server returns the 402 response again, prompting the client to retry or adjust its payment strategy.

This flow creates a frictionless loop where payment and data delivery happen in near real-time. By leveraging the x402 protocol, you eliminate the latency of traditional payment processors and enable micro-transactions that were previously too costly to process.

Compare Pricing Models for APIs

Choosing the right billing structure dictates whether your API survives the early adoption phase or gets buried by administrative overhead. For sporadic, machine-to-machine, or AI agent workloads, the traditional subscription model creates friction that pay-per-request pricing eliminates. The HTTP 402 standard offers a third path: instant, tokenized micropayments that scale linearly with usage.

Subscriptions require developers to estimate future demand. This guesswork often leads to overpaying for unused capacity or hitting hard rate limits that break automated workflows. Seat-based pricing adds another layer of complexity, forcing you to manage user accounts and permissions just to access basic data. For an AI agent making thousands of calls per hour, these models are economically inefficient and technically cumbersome.

Pay-per-request pricing, particularly via the x402 protocol, removes the need for API keys, accounts, or monthly invoices. You pay only for what you use, down to the fraction of a cent. This aligns costs directly with value delivered. If an agent makes a call, it pays. If it doesn't, you owe nothing.

The table below breaks down how these models compare across critical operational dimensions.

Pricing ModelCost PredictabilityBilling OverheadSuitability for AI Agents
SubscriptionHigh (fixed monthly fee)Medium (account management)Low (waste on idle time)
Pay-Per-RequestVariable (usage-based)Low (no accounts)High (scales with calls)
Pay-Per-API 402Precise (per-call)None (instant settlement)Optimal (machine-to-machine native)

The shift to HTTP 402 isn't just about billing; it's about architectural simplicity. By embedding payment logic directly into the HTTP response code, you remove the need for separate payment gateways or webhook reconciliation systems. This makes it the ideal choice for the Pay-Per-API 402 guide, as it reduces the integration surface area to its absolute minimum. For developers building autonomous systems, this reduction in friction is the difference between a prototype and a production-ready service.

Choose the right infrastructure

Building a Pay-Per-API 402 system starts with picking the right tools. You need infrastructure that handles crypto payments without adding friction. The goal is to let agents or users pay and get access instantly.

Coinbase Developer Platform (CDP) is the official source for x402. Their documentation explains how to set up wallets and handle stablecoin transactions. Using CDP keeps your code aligned with the standard. It removes guesswork from the payment flow.

1
Set up a CDP wallet

Create a wallet on the Coinbase Developer Platform. This wallet receives the USDC payments. Keep the private keys secure. You will use this wallet to verify incoming transactions.

2
Integrate the x402 middleware

Use middleware that understands the 402 status code. The middleware checks the payment before serving the API response. It handles the crypto logic so you can focus on your API data.

3
Test with a sandbox

Run your API against a testnet. Send small payments to verify the flow. Check that the 402 response triggers correctly when payment is missing.

For complex setups, consider established API marketplaces. These platforms often have built-in monetization features. They can handle the heavy lifting of billing and user management. Look for providers that support instant settlement.

You also need reliable hosting. Your API must stay online to accept payments. Choose a provider with high uptime. A crashed server means lost revenue.

Pay-Per-API 402 in

Avoid common integration mistakes

Building a Pay-Per-API 402 integration seems straightforward until you hit the edge cases. Because the x402 protocol relies on real-time price signaling, small oversights can lead to failed transactions, lost revenue, or broken agent workflows. Here are the three most common pitfalls and how to fix them.

Failing to handle non-payment 402s

Not all 402 responses mean "pay now." Some indicate that payment is required but the wallet is misconfigured, or that the request is malformed. If your agent blindly retries every 402, you risk infinite loops or excessive gas fees. Always check the response headers and body for specific error codes or price updates before deciding to retry.

Incorrect price injection

The x402 protocol requires the server to include the current price in every 402 response. If your server caches prices for too long, agents may pay outdated rates, leading to underpayment or rejection. Ensure your price updates are frequent and accurate. As noted in official guides, the agent sees the updated price before paying, so your backend must reflect real-time market conditions.

Lack of idempotency

Crypto transactions are final. If your agent sends a payment request twice due to a network glitch, you might double-charge the user or lock funds unnecessarily. Implement idempotency keys in your payment requests. This ensures that even if a request is retried, the server recognizes it and processes it only once. Without this, your Pay-Per-API 402 service could become unreliable quickly.

Before launching, run through this quick checklist to ensure your integration is robust:

  • Verify price updates are real-time and not cached excessively.
  • Test wallet signatures with various edge-case inputs.
  • Ensure idempotent payment handling is in place for all endpoints.
  • Monitor gas fees to prevent transaction failures during high congestion.

Frequently asked: what to check next