How to Build a Pay-Per-Request Blockchain API With x402 and GetBlock
Build a pay-per-request blockchain data API using the x402 protocol and GetBlock's node infrastructure.
Overview
The x402 protocol is an open payment method that enables developers and service providers to charge/sell their APIs and content via HTTP without requiring third-party integrations, credential setup, or gas fees.
The x402 protocol brings the HTTP 402 "Payment Required" status code to life. Originally reserved in the HTTP specification for future use with digital payments, x402 finally implements this vision, enabling micropayments to be made directly over HTTP.
How it works
Frank adds "payment required" to his API endpoints
His client requests a protected resource,
The server responds with
402 Payment Requiredalong with payment details.The client signs a payment authorisation
He/she retries the request and receives the data.
All of this happens in seconds, without traditional payment infrastructure.
User registration and account management
No accounts needed β The wallet is the identity
API key generation and rotation
No API keys β Payment is the authentication
Payment processing integration (e.gStripe, PayPal)
Global access β Anyone with USDC can use your API
Subscription tiers and billing cycles
Instant micropayments β Charge per request
Fraud prevention and rate limiting
Built-in rate limiting β Users only call what they pay for
Transaction or gas fee
Gasless fee
Components of x402
The x402 ecosystem consists of three main components, which are:
Client Side:
This is the interface e.g frontend, that users interact with, which initiates a request to access a paid resource. It handles the payment requirements, prepare payment payload and resubmits the request with payment.
Clients do not need to manage accounts, credentials, or session tokens beyond their crypto wallet. All interactions are stateless and occur over standard HTTP requests.
Server Side:
The server is the resource provider enforcing payment for access to its services, such as API services, content providers, or any HTTP-accessible resource requiring monetization. It defines payment requirements, verifies payment payloads, settles transactions, and provides the resources.
Servers do not need to manage client identities or maintain session state. Verification and settlement are handled per request.
Facilitators:
The facilitator is an optional but recommended service that verifies and settles payment between clients and servers.
Architecture Overview
Key Components Explained:
Client (dApp)
Browser app with wallet connection. Uses @x402/fetch to handle payments automatically.
Server (Express)
Your API server. Uses @x402/express middleware to protect routes and define prices.
Facilitator
Third-party service that verifies payment signatures and settles USDC transfers.
https://x402.org/facilitator
https://facilitator.payai.network
Who is x402 For?
API Developers β Monetize your APIs without managing subscriptions or API keys
AI Agents β Enable autonomous systems to pay for resources programmatically
Content Creators β Charge per article, image, or download
Data Providers β Sell real-time data feeds with per-request pricing
Blockchain Services β Offer RPC access, indexing, or analytics with micropayments
Real-Life Use Cases
AI Agent Economy β AI agents paying for web searches, API calls, or compute resources
Pay-Per-Article News β Read individual articles without monthly subscriptions
Blockchain Data Services β Pay-per-query for on-chain analytics
Premium API Access β Charge for rate-limited or enhanced API endpoints
Decentralized CDN β Pay nodes for bandwidth and storage per request
What You're Building
In this guide, you'll build a complete pay-per-request blockchain data API:
Backend: Express.js server with x402 payment middleware
Frontend: Vanilla JavaScript dApp with MetaMask integration
Data Source: GetBlock's Ethereum node API
Payment: USDC on Base Sepolia testnet
Endpoints you'll create:
GET /api/eth/block/latest
$0.001 USDC
Get the latest Ethereum block number
GET /api/eth/gas
$0.001 USDC
Get the current gas price
Prerequisites
Node.js 18+
MetaMask wallet
Base Sepolia USDC (from Circle Faucet)
GetBlock API key (free tier available)
Basic knowledge of JavaScript/Express
A. Project Setup
Step 1: Create Project Directories
Step 2: Initialize Server Package
Step 3: Install Dependencies
Dependency Overview:
Web server framework
Cross-origin resource sharing
HTTP client for GetBlock API
Environment variable management
x402 core utilities (Resource Server, Facilitator Client)
EVM blockchain support (Base, Ethereum)
Express middleware for payment protection
Step 4: Configure package.json
Update server/package.json:
Folder Structure
Create the following project structure:
Backend: Express Server with x402
Step 1: Environment Configuration
Create server/.env:
Replace 0xYourWalletAddressHere with your actual MetaMask wallet address. This is where you'll receive USDC payments.
Step 2: Create the Server
Create server/server.js and add the following code:
Frontend: Vanilla JS dApp
Create client/index.html and add the following code:
Running the Application
Step 1: Start the Server
You should see:
Step 2: Access the Frontend
Open your browser and navigate to:
Your frontend should look like this:

Connect your wallet
Select any of the endpoints you want to access
Sign the request

The payment is then verified, scroll down to see the result

Troubleshooting
"Failed to create payment payload: Address undefined": This means the wallet client was not properly initialized. Make sure you're using
getAddress()to normalize the address:
CORS Errors: This means the server not configured for x402 headers. Ensure CORS middleware includes x402 headers:
"Facilitator does not support scheme": This mean the facilitator is unreachable or doesn't support your network. To resolve this:
i. Check internet connection
ii. Try an alternative facilitator: https://facilitator.payai.network
iii. Verify you're using the correct network ID: eip155:84532
"Facilitator Connectivity Issues"
If the default facilitator is down, you can try:
Wallet Signing Problems
If MetaMask shows an error during signing:
Check network β Ensure you're on Base Sepolia (Chain ID 84532)
Check balance β Ensure you have enough USDC for the request
Debug Mode
Enable the debug log by clicking "Toggle Debug Log" at the bottom of the page. This shows:
Connection steps
Network switching
Signing requests
API responses
Error details
Resources
Conclusion
In this guide, you learnt what x402 is all about, including its use cases, components, architecture diagram etc. You also learnt how to set up the project and built a complete pay-per-request blockchain data API using x402 and GetBlock.
Last updated
Was this helpful?