Coins: 18,000
Exchanges: 1,480
Market Cap: $2.359T 3.4%
24h Vol: $108.251B
Gas: 0.042 GWEI
Remove Ads
API
TABLE OF CONTENTS

How to Access Crypto Data Without an API Subscription (x402 Pay-Per-Use)

5.0
| by
Brian Lee
-

Accessing crypto data APIs often involve signing up, selecting a subscription plan, and managing an API key before you can begin making your first requests. For developers who are focused on building open-source tools, experimenting with AI agents (such as leveraging frameworks like OpenClaw), or simply testing a concept, this initial setup and commitment might feel like an added complexity.

The x402 protocol changes this. It lets you pay for each API call individually using USDC from your crypto wallet without needing an API key or subscription plans.

In this tutorial, you will learn how to fetch real-time crypto market data from the CoinGecko API using x402 pay-per-use payments. By the end, you will have:

  • Set up a wallet with USDC on Base or Solana

  • Run a Python script in Replit (no local setup needed)

  • Make 5 different x402 API requests

  • Get real-time crypto prices and market data, all paid with crypto

How to Access Crypto Data Without an API Subscription (x402 Pay-Per-Use)


What Is x402 and How Does It Work for Crypto Data APIs?

x402 is an open payment protocol developed by Coinbase that brings native payments to HTTP. Think of it as paying for API data the same way you would pay for a coffee, one request at a time.

The protocol revives HTTP status code 402 ("Payment Required"), which has been reserved in the HTTP specification since the 1990s but was never widely adopted until now. With the rise of stablecoins and programmable blockchains, x402 finally has the infrastructure it needs to work.

CoinGecko is one of the first major crypto data providers to support x402, making it possible to access real-time market data with just a wallet.

Features Regular API X402 API
Setup Sign up, get API key Just a wallet
Payment Monthly subscription Pay per request
Commitment Monthly or Annual No commitment


When x402 makes sense:

  • Building an open-source project and cannot embed your API key in a public repo

  • Testing crypto data APIs before committing to a subscription

  • AI agents making occasional, unpredictable queries (such as frameworks like OpenClaw, Clawdbot, Moltbot, and CrewAI)

  • Prefer paying with crypto over credit card

When a CoinGecko API subscription plan makes more sense:

  • Making over 10,000 requests per month (a subscription is cheaper per call)

  • Need WebSocket, historical data, or premium endpoints

  • Want dedicated support and SLAs

  • Need predictable costs for budgeting


Architecture Overview: How x402 Payments Work When Fetching Crypto Data

The x402 payment flow happens automatically within the HTTP request-response cycle. Here is what happens behind the scenes when your script makes a request.

Architecture Overview: How x402 Payments Work When Fetching Crypto Data

The x402 client library handles steps 2 through 5 automatically. Your code simply makes the request and receives the data. Each request costs $0.01 USDC, paid on either the Base or Solana network.


Prerequisites for Using CoinGecko's x402 API

Before running the scripts, make sure you have the following ready:

  1. A crypto wallet such as Coinbase Wallet, any EVM-compatible wallet, or a Solana wallet

  2. ~$1 of USDC on Base or Solana network (enough for roughly 100 test requests)

  3. Your Base or Solana wallet’s private key

  4. A free Replit account for easy cloud-based testing (Optional)

💡 Pro tip: Use a brand-new wallet with minimal funds specifically for testing. Never use a wallet containing significant assets. Your private key gives full control over the wallet's funds, so treat it like a password.

How to Fetch Crypto Market Data Using x402

This section walks through the core Python code that powers x402 API requests on the Base network. If you want to run this on the Solana network instead, see the section below on setting up x402 payments on Solana. The complete, tested code with compatiblity for both Base and Solana network is available in the GitHub repository below, but let's break down how it works step by step.

Step 1: Install Dependencies

The x402 Python SDK is the official Coinbase package that handles wallet signing and the payment flow. Install it along with the EVM and HTTP extras.

Run the install command in your terminal:

pip install -r requirements.txt

Step 2: Configure Your Environment

Store your private key as an environment variable. Never hardcode it in your script.

Step 3: Initialize the x402 Client

The client setup involves importing the x402 SDK, loading your private key, and registering the EVM signer. This is the foundation that enables automatic payment handling.

Step 4: Build the Request and Handle Payment

The fetch_json function below makes the actual API call. The x402 client automatically detects the 402 Payment Required response, signs the USDC authorization with your wallet, and retries the request with the payment signature attached.

The manual_x402_request function is a fallback for cases where the server returns payment details in the JSON body instead of HTTP headers. This ensures compatibility with the CoinGecko x402 implementation.

Step 5: Make Your First x402 Request

Here is a complete, working example that fetches Bitcoin, Ethereum, and Solana prices using the /simple/price endpoint.

The code works by first initializing your x402 client with the wallet credentials from your .env file. When fetch_json sends the GET request to the /x402/simple/price endpoint, the CoinGecko server responds with a 402 status code and the payment terms ($0.01 USDC on Base). The X402 SDK then signs a USDC transfer authorization using your wallet's private key and retries the request with this payment proof in the headers. All of this happens in a single function call.

Notice the /x402/ segment in the URL path. This is what differentiates x402 pay-per-use endpoints from the standard CoinGecko API endpoints. The base URL https://pro-api.coingecko.com/api/v3/x402 replaces the usual https://pro-api.coingecko.com/api/v3, and the endpoint paths remain the same after that.


Which CoinGecko API Endpoints Support x402?

CoinGecko currently offers five x402-enabled endpoints. Each request costs $0.01 USDC.

Simple Price

Returns current prices, market caps, 24h volume, and price change for coins listed on CoinGecko (by coin ID).

Endpoint path: /x402/simple/price

Example output:

CoinGecko /x402/simple/price endpoint successful response example

Onchain Token Price

Returns the USD price of any token by its contract address on a specific network, powered by GeckoTerminal on-chain data.

Endpoint path: /x402/onchain/simple/networks/{network}/token_price/{contract_address}

Example output:

CoinGecko /x402/onchain/simple/networks/{network}/token_price/{contract_address} endpoint successful response example

Onchain Token Data

Returns comprehensive token details including price, supply, FDV, market cap, and top pools for a given contract address.

Endpoint path: /x402/onchain/networks/{network}/tokens/{contract_addresses}

Example output:

CoinGecko /x402/onchain/networks/{network}/tokens/{contract_addresses} endpoint successful response example

Trending Pools

Returns the currently trending liquidity pools on a specific network, sorted by trading activity over a chosen timeframe.

Endpoint path: /x402/onchain/networks/{network}/trending_pools

Example output:

CoinGecko /x402/onchain/networks/{network}/trending_pools endpoint successful response example

Search Pools

Searches for liquidity pools by token name, symbol, or contract address across networks.

Endpoint path: /x402/onchain/search/pools

Example output:

CoinGecko /x402/onchain/search/pools endpoint successful response example

To view the complete parameter documentation for all endpoints and to stay informed about the latest x402 endpoints available, please visit our x402 API documentation.

💡 Pro tip: At $0.01 per request, x402 is great for occasional use and experimentation. However, if you are making more than 10,000 requests per month, a CoinGecko API subscription plan becomes more cost-effective and includes additional features like access to all CoinGecko API endpoints (including exclusive endpoints), WebSocket access, and full historical data.

How to Quickly Test All CoinGecko x402 Endpoints

The fastest way to test all five endpoints is by importing the GitHub repository into Replit. Replit is a cloud-based IDE that requires no local setup. You just need to create a free account and you can start running Python scripts immediately in your browser. While Replit is ideal for testing and experimentation, production usage would typically run on your own infrastructure.

Step 1: Import the Repository into Replit

  1. Go to Replit and log in (or create a free account)

  2. Click "Import code or design" and then select "GitHub"
    Import code or design from Github on Replit

  3. Paste the repository URL: https://github.com/cg-brianlsh/coingecko-x402-python-v3

  4. Click “Import”

  5. Replit will automatically install the required dependencies.

In case the required dependencies have not been automatically installed yet, open the Replit Shell and run:

pip install -r requirements.txt

Step 2: Replace Your Wallet Private Key

  1. In your Replit project, copy the .env.example file and rename it as .env

  2. Replace the placeholder EVM_PRIVATE_KEY to your own Base wallet private key

Step 3: Run Your First Test

In the Replit Shell, run:

python main.py simple_price

You should see output similar to this:

CoinGecko /x402/simple/price endpoint successful response example

To run all five endpoint tests at once, use the command:

python main.py

This will execute each test sequentially and provide a summary at the end showing how many passed, how many failed, and the total USDC spent.

Congratulations! You have successfully completed a paid x402 request using cryptocurrency. This process requires no API key or subscription, relying solely on your crypto wallet for payment.

x402 Payments on Solana Network

This guide uses Base network for payments, but the Github repo code also supports Solana. To use Solana instead, follow the steps below:

  1. Install Solana dependencies: pip install "x402[svm,httpx]"

  2. Set SOLANA_PRIVATE_KEY instead of EVM_PRIVATE_KEY in your environment variables

The code automatically detects which network to use based on which private key is provided.


Using x402 MCP to Access Crypto Market Data

Another way to set up and test the CoinGecko x402 API is to use an x402 MCP server with an AI or Large Language Model (LLM) that has tool-calling abilities, such as Claude Sonnet 4 and above.

MCP (Model Context Protocol) lets AI assistants call external tools, including making paid x402 API requests on your behalf. Instead of writing Python scripts, you can simply ask an AI assistant like Claude to fetch crypto prices, search pools, or check trending tokens, and it handles the x402 payment flow automatically behind the scenes.

First, install the x402 MCP server by following the official Coinbase x402 MCP server documentation. The setup involves cloning the x402 MCP repository, building the TypeScript packages, and configuring your AI client (e.g. Claude Desktop) to connect to the MCP server.

When configuring the MCP server, set the following environment variables to point to CoinGecko's x402 API:

  • RESOURCE_SERVER_URL: https://pro-api.coingecko.com/api/v3/x402

  • ENDPOINT_PATH: The specific CoinGecko endpoint path you want to query (e.g. /simple/price)

  • EVM_PRIVATE_KEY or SVM_PRIVATE_KEY: Your wallet private key (the same one you used in the Python setup above)

Once configured, you can ask your AI assistant natural language questions like "What is the current price of Bitcoin and Ethereum?" or "Show me the trending pools on Solana", and it will automatically make the paid x402 request and return the results. Example shown below:

CoinGecko x402 via MCP in Claude Desktop Demo


Troubleshooting CoinGecko x402 API Errors

Here are the most common issues you might run into and how to fix them.

Insufficient funds

Your wallet does not have enough USDC on the Base or Solana network. Each request costs $0.01, so make sure you have at least a few cents of USDC available. You can check your balance in your crypto wallet or a block explorer.

Invalid private key

Double-check that your EVM_PRIVATE_KEY or SOLANA_PRIVATE_KEY does not contain placeholder text, extra spaces, or newline characters. The key should be a 64-character hex string.

EVM packages not installed

This means the x402[evm] or x402[svm] extra was not included during installation. Run the following command to fix it:

pip install "x402[evm,httpx]>=0.1.0"

pip install "x402[svm,httpx]"

If the above troubleshooting tips do not resolve your issue, please refer to the official x402 documentation for more information.


Conclusion

You have just made your first pay-per-use crypto data requests using the x402 protocol. With just a wallet and a few lines of Python, you fetched real-time prices, searched for trending pools, and queried on-chain token data from the CoinGecko API.

x402 is ideal for experimentation, open-source projects, or AI agents with occasional data needs. For production applications with consistent usage, CoinGecko's API subscription plans offer better value, more endpoints, and dedicated support.

You can quickly get started by cloning the complete source code for this tutorial, which is available in this GitHub repo.

If you enjoyed this article, be sure to check out others like how to build crypto apps with AI and how to do crypto research using Model Context Protocols (MCP).

CoinGecko's Content Editorial Guidelines
CoinGecko’s content aims to demystify the crypto industry. While certain posts you see may be sponsored, we strive to uphold the highest standards of editorial quality and integrity, and do not publish any content that has not been vetted by our editors.
Learn more
Want to be the first to know about upcoming airdrops?
Subscribe to the CoinGecko Daily Newsletter!
Join 600,000+ crypto enthusiasts, traders, and degens in getting the latest crypto news, articles, videos, and reports by subscribing to our FREE newsletter.
Tell us how much you like this article!
Vote count: 4
Brian Lee
Brian Lee
Brian is a Growth Marketer at CoinGecko, helping developers, traders, and crypto businesses discover and use CoinGecko API to build, track, and scale smarter with real-time crypto market data.

More Articles

New Portfolio
Icon & name
Select Currency
Suggested Currencies
USD
US Dollar
IDR
Indonesian Rupiah
TWD
New Taiwan Dollar
EUR
Euro
KRW
South Korean Won
JPY
Japanese Yen
RUB
Russian Ruble
CNY
Chinese Yuan
Fiat Currencies
AED
United Arab Emirates Dirham
ARS
Argentine Peso
AUD
Australian Dollar
BDT
Bangladeshi Taka
BHD
Bahraini Dinar
BMD
Bermudian Dollar
BRL
Brazil Real
CAD
Canadian Dollar
CHF
Swiss Franc
CLP
Chilean Peso
CZK
Czech Koruna
DKK
Danish Krone
GBP
British Pound Sterling
GEL
Georgian Lari
HKD
Hong Kong Dollar
HUF
Hungarian Forint
ILS
Israeli New Shekel
INR
Indian Rupee
KWD
Kuwaiti Dinar
LKR
Sri Lankan Rupee
MMK
Burmese Kyat
MXN
Mexican Peso
MYR
Malaysian Ringgit
NGN
Nigerian Naira
NOK
Norwegian Krone
NZD
New Zealand Dollar
PHP
Philippine Peso
PKR
Pakistani Rupee
PLN
Polish Zloty
SAR
Saudi Riyal
SEK
Swedish Krona
SGD
Singapore Dollar
THB
Thai Baht
TRY
Turkish Lira
UAH
Ukrainian hryvnia
VEF
Venezuelan bolívar fuerte
VND
Vietnamese đồng
ZAR
South African Rand
XDR
IMF Special Drawing Rights
Cryptocurrencies
BTC
Bitcoin
ETH
Ether
LTC
Litecoin
BCH
Bitcoin Cash
BNB
Binance Coin
EOS
EOS
XRP
XRP
XLM
Lumens
LINK
Chainlink
DOT
Polkadot
YFI
Yearn.finance
SOL
Solana
Bitcoin Units
BITS
Bits
SATS
Satoshi
Commodities
XAG
Silver - Troy Ounce
XAU
Gold - Troy Ounce
Select Language
Popular Languages
EN
English
RU
Русский
DE
Deutsch
PL
język polski
ES
Español
VI
Tiếng việt
FR
Français
PT-BR
Português
All Languages
AR
العربية
BG
български
CS
čeština
DA
dansk
EL
Ελληνικά
FI
suomen kieli
HE
עִבְרִית
HI
हिंदी
HR
hrvatski
HU
Magyar nyelv
ID
Bahasa Indonesia
IT
Italiano
JA
日本語
KO
한국어
LT
lietuvių kalba
NL
Nederlands
NO
norsk
RO
Limba română
SK
slovenský jazyk
SL
slovenski jezik
SV
Svenska
TH
ภาษาไทย
TR
Türkçe
UK
украї́нська мо́ва
ZH
简体中文
ZH-TW
繁體中文
Welcome to CoinGecko
Welcome back!
Login or Sign up in seconds
or
Sign in with . Not you?
Forgot your password?
Didn't receive confirmation instructions?
Resend confirmation instructions
Password must contain at least 8 characters including 1 uppercase letter, 1 lowercase letter, 1 number, and 1 special character
By continuing, you acknowledge that you've read and agree fully to our Terms of Service and Privacy Policy.
Get Price Alerts with CoinGecko App
Forgot your password?
You will receive an email with instructions on how to reset your password in a few minutes.
Resend confirmation instructions
You will receive an email with instructions for how to confirm your email address in a few minutes.
Get the CoinGecko app.
Scan this QR code to download the app now App QR Code Or check it out in the app stores
Add NFT
Track wallet address
Paste
We only display assets from supported networks.
Ethereum Mainnet
Base Mainnet
BNB Smart Chain
Arbitrum
Avalanche
Fantom
Flare
Gnosis
Linea
Optimism
Polygon
Polygon zkEVM
Scroll
Stellar
Story
Syscoin
Telos
X Layer
Xai
Read-only access
We only fetch public data. No private keys, no signing, and we can't make any changes to your wallet.
Create Portfolio
Select icon
💎
🔥
👀
🚀
💰
🦍
🌱
💩
🌙
🪂
💚
CoinGecko
Better on the app
Real-time price alerts and a faster, smoother experience.
You’ve reached the limit.
Guest portfolios are limited to 10 coins. Sign up or log in to keep the coins listed below.