square-codeBuilding a Pay-Per-Request Blockchain API with x402 + 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 codearrow-up-right 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

  1. Frank adds "payment required" to his API endpoints

  2. His client requests a protected resource,

  3. The server responds with 402 Payment Required along with payment details.

  4. The client signs a payment authorisation

  5. He/she retries the request and receives the data.

All of this happens in seconds, without traditional payment infrastructure.

Traditional API monetization requires
With x402

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:

  1. 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.

circle-exclamation
  1. 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.

circle-exclamation
  1. Facilitators:

The facilitator is an optional but recommended service that verifies and settles payment between clients and servers.

Architecture Overview

spinner

Key Components Explained:

Component
Role
SDK to Use

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

  1. AI Agent Economy β€” AI agents paying for web searches, API calls, or compute resources

  2. Pay-Per-Article News β€” Read individual articles without monthly subscriptions

  3. Blockchain Data Services β€” Pay-per-query for on-chain analytics

  4. Premium API Access β€” Charge for rate-limited or enhanced API endpoints

  5. 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:

Endpoint
Price
Description

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

A. Project Setup

Step 1: Create Project Directories

Step 2: Initialize Server Package

Step 3: Install Dependencies

Dependency Overview:

Package
Purpose

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:

circle-info

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:

  1. Connect your wallet

  2. Select any of the endpoints you want to access

  3. Sign the request

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

Result of the latest block number

Troubleshooting

  1. "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:

  1. CORS Errors: This means the server not configured for x402 headers. Ensure CORS middleware includes x402 headers:

  1. "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

  1. "Facilitator Connectivity Issues"

If the default facilitator is down, you can try:

  1. Wallet Signing Problems

If MetaMask shows an error during signing:

  1. Check network β€” Ensure you're on Base Sepolia (Chain ID 84532)

  2. 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?