- Makes the initial request (if using Fetch) or intercepts the initial request (if using Axios/HTTPX/Requests)
- If a 402 response is received, parses the payment requirements
- Verifies the payment amount is within the allowed maximum
- Creates a payment header using the provided wallet client
- Retries the request with the payment header
Prerequisites
Before you begin, ensure you have:- A crypto wallet with USDC (any EVM-compatible wallet, e.g., CDP Wallet, AgentKit)
- Node.js and npm, or Python and pip
- A service that requires payment via x402
We have pre-configured examples available in our repo, including examples for fetch, Axios, and MCP.
1. Install Dependencies
Install x402-axios or x402-fetch:
2. Create a Wallet Client
Create a wallet client using CDP’s Server Wallet (recommended) or a standalone wallet library (viem for Node.js or eth-account for Python).CDP Server Wallet (Recommended)
First, create an account at cdp.coinbase.com and get the following API keys from the portal to store as environment variables:Standalone Wallet Libraries
If you prefer to use your own wallet, you can use standalone libraries:Install the required package:Then instantiate the wallet account:
3. Make Paid Requests Automatically
You can automatically handle 402 Payment Required responses and complete payment flows using the x402 helper packages.You can use either
x402-fetch
or x402-axios
:x402-fetch extends the native Features:
fetch
API to handle 402 responses and payment headers for you. Full example here- Automatically handles 402 Payment Required responses
- Verifies payment and generates payment headers
- Retries the request with proof of payment
- Supports all standard fetch options
4. Discover Available Services (Optional)
Instead of hardcoding endpoints, you can use the x402 Bazaar to dynamically discover available services. This is especially powerful for building autonomous agents that can find and use new capabilities. See the full example here for Python and Node.js.Learn more about service discovery in the x402 Bazaar documentation, including how to filter services, understand their schemas, and build agents that can autonomously discover new capabilities.
5. Error Handling
Clients will throw errors if:- The request configuration is missing
- A payment has already been attempted for the request
- There is an error creating the payment header
Summary
- Install an x402 client package
- Create a wallet client
- Use the provided wrapper/interceptor to make paid API requests
- (Optional) Use the x402 Bazaar to discover services dynamically
- Payment flows are handled automatically for you
References:
- x402-fetch npm docs
- x402-axios npm docs
- x402 PyPi page
- x402 Bazaar documentation - Discover available services