Building Agent-Native APIs with x402 Micropayments
Most APIs today are built for human developers. The signup flow, API key management, and subscription billing all assume a person is on the other end — someone who can click through an onboarding flow, enter a credit card number, and rotate credentials when needed.
AI agents can do none of this. And as agents become primary consumers of API services, the friction built into traditional API design becomes a fundamental architectural problem.
x402 v2 is the most elegant solution to this problem I've encountered. This post explains the pattern and how to implement it.
What makes an API "agent-native"
An agent-native API has four properties:
- Zero setup — no account creation, no API keys, no human onboarding
- Machine-discoverable — the API surface is described in a format agents can parse and act on autonomously
- Pay-per-use — billing is per-call, not subscription-based, so agents don't accumulate idle costs
- Programmatic auth — authentication happens via a protocol an agent can execute, not a browser flow
Traditional APIs satisfy none of these. x402 v2 satisfies all four.
How x402 v2 works
x402 uses HTTP 402 ("Payment Required") as a machine-readable payment request. The server includes a PAYMENT-REQUIRED header with a base64-encoded JSON envelope describing exactly what payment is needed:
{
"x402Version": 2,
"error": "Payment required",
"resource": { "url": "https://docpull.ai/extract" },
"accepts": [{
"scheme": "exact",
"network": "eip155:8453",
"amount": "1000",
"asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
"payTo": "0x...",
"maxTimeoutSeconds": 300
}]
}
An x402-compatible client receives this, settles the payment on-chain via the CDP facilitator, and retries the request with proof of payment in the X-PAYMENT header. The server verifies and fulfills.
The full flow:
No human touches this flow. An agent with a funded wallet can execute it autonomously in under a second.
Building an x402 server with Express
Here's the minimal pattern for adding x402 to an Express API using the official packages:
import express from "express";
import { paymentMiddleware, x402ResourceServer } from "@x402/express";
import { HTTPFacilitatorClient } from "@x402/core/server";
import { ExactEvmScheme } from "@x402/evm/exact/server";
import { facilitator } from "@coinbase/x402";
const app = express();
app.use(express.json());
// Set up CDP facilitator (reads CDP_API_KEY_ID / CDP_API_KEY_SECRET from env)
const facilitatorClient = new HTTPFacilitatorClient(facilitator);
const server = new x402ResourceServer(facilitatorClient)
.register("eip155:*", new ExactEvmScheme());
// Apply payment middleware before route handlers
app.use(paymentMiddleware({
"POST /api/your-endpoint": {
accepts: [{
scheme: "exact",
price: "$0.001",
network: "eip155:8453",
payTo: process.env.WALLET_ADDRESS,
asset: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", // USDC on Base
maxTimeoutSeconds: 300,
}],
},
}, server));
// Your actual route handler
app.post("/api/your-endpoint", (req, res) => {
// Payment verified — fulfil the request
res.json({ result: "success" });
});
That's the complete server-side implementation. The middleware intercepts requests, issues 402 responses to unpaid callers, and verifies payment proofs from paid callers before passing to your handler.
Making your API discoverable
Agent-native APIs need to be discoverable by agents. x402 v2 includes a Bazaar extension that registers your API with the CDP discovery index when the first payment is processed:
import {
bazaarResourceServerExtension,
declareDiscoveryExtension,
} from "@x402/extensions/bazaar";
server.registerExtension(bazaarResourceServerExtension);
// Add to your route config
const routeConfig = {
"POST /api/your-endpoint": {
accepts: [/* ... */],
extensions: {
...declareDiscoveryExtension({
bodyType: "json",
output: {
example: { result: "success" },
schema: { properties: { result: { type: "string" } } }
}
})
}
}
};
After the first payment, your API appears in the CDP Bazaar. Agents querying for services in your category will discover it autonomously.
The bigger picture
x402 enables something that wasn't possible before: an open marketplace of API services where agents are first-class consumers. An agent can:
- Identify a task it needs to complete (e.g., "extract this PDF")
- Query the CDP Bazaar for services that match the capability
- Evaluate options by price and description
- Pay and call the selected service
- Incorporate the result into its reasoning
No human sets up accounts. No API keys are provisioned. No billing dashboards are monitored. The entire pipeline runs autonomously.
Key design principles for agent-native APIs
- Free probe endpoints — let agents check cost before committing. docpull's
/probeendpoint lets agents check page count and price for free - Structured errors — return JSON error objects with codes. Agents can't parse HTML error pages
- Rate limit headers — return
X-RateLimit-*headers so agents can self-throttle - OpenAPI spec — publish a machine-readable spec at
/openapi.jsonso agents understand your surface - llms.txt — publish a plain-text description at
/llms.txtso agents can understand your product without crawling HTML
docpull implements all of these. The complete source is open at github.com/docpull/docpull.