One-liner cryptocurrency payments for FastAPI endpoints using the x402 protocol
fastapi-x402 is an early-stage Python project in the AI payments / x402 ecosystem. It currently has 3 GitHub stars and 3 forks.
One-liner cryptocurrency payments for FastAPI endpoints using the x402 protocol.
Transform any FastAPI endpoint into a paid API with just a single decorator. Accept stablecoin payments (USDC) on Base network with automatic settlement.
from fastapi import FastAPI
from fastapi_x402 import init_x402, pay
app = FastAPI()
init_x402(app, pay_to="0x...", facilitator_url="https://x402.org/facilitator")
@app.get("/premium-data")
@pay("$0.01") # Require 1 cent payment
async def get_premium_data():
return {"data": "This costs $0.01 to access!"}
@pay("$0.01") to any endpointpip install fastapi-x402
Create a .env file in your project root. Copy .env.example -> .env:
# Required: Your merchant wallet address
PAY_TO_ADDRESS=0x1234567890123456789012345678901234567890
# For testnet development (default)
# Uses public x402.org facilitator - no additional setup needed
# For mainnet production (requires Coinbase CDP)
# CDP_API_KEY_ID=your_cdp_api_key_id
# CDP_API_KEY_SECRET=your_cdp_api_secret
from fastapi import FastAPI
from fastapi_x402 import init_x402, pay
app = FastAPI()
# Initialize x402 (loads from .env and adds middleware automatically)
init_x402(app, network="base-sepolia") # or "base" for mainnet
@app.get("/free")
async def free_endpoint():
return {"message": "This endpoint is free!"}
@app.get("/premium")
@pay("$0.01") # Require 1 cent payment
async def premium_endpoint():
return {"data": "This cost 1 cent to access!"}
@app.get("/expensive")
@pay("$1.00") # Require $1 payment
async def expensive_endpoint():
return {"premium_data": "This is worth $1!"}
uvicorn main:app --host 0.0.0.0 --port 8000
Without payment (gets 402 response):
curl http://localhost:8000/paid-endpoint
With payment (success):
curl -H "X-PAYMENT: eyJ4NDAyVmVyc2lvbiI6..." http://localhost:8000/paid-endpoint
import { X402Client } from '@x402/client';
const client = new X402Client({
network: 'base-sepolia',
privateKey: 'your-wallet-private-key'
});
const response = await client.get('http://localhost:8000/paid-endpoint');
console.log(response.data); // Automatically handles payment
import httpx
from x402_client import X402Client # Coming soon
client = X402Client(network='base-sepolia', private_key='...')
response = await client.get('http://localhost:8000/paid-endpoint')
# Required
PAY_TO_ADDRESS=0x1234567890123456789012345678901234567890
# Optional: Network configuration
X402_NETWORK=base-sepolia # Single network
# X402_NETWORK=base,avalanche,iotex # Multiple networks
# X402_NETWORK=mainnets # All mainnets
# X402_NETWORK=testnets # All testnets
# Optional: Custom facilitator (advanced)
# FACILITATOR_URL=https://your-facilitator.com
# Required for mainnet production
# CDP_API_KEY_ID=your_coinbase_cdp_api_key_id
# CDP_API_KEY_SECRET=your_coinbase_cdp_api_secret
🧪 Testnet Development (Default)
# .env
PAY_TO_ADDRESS=0x...
X402_NETWORK=base-sepolia
# main.py
init_x402(app) # Uses public facilitator, no API keys needed
🚀 Mainnet Production
# .env
PAY_TO_ADDRESS=0x...
X402_NETWORK=base # or avalanche, iotex
CDP_API_KEY_ID=your_key_id
CDP_API_KEY_SECRET=your_secret
# main.py
init_x402(app) # Auto-detects CDP credentials for mainnet
from fastapi_x402 import init_x402
# Support all available networks
init_x402(app, network="all") # Accepts payments on Base, Avalanche, and IoTeX
# Support specific networks
init_x402(app, network=["base", "avalanche"]) # Multiple networks
# Network shortcuts
init_x402(app, network="testnets") # Base Sepolia + Avalanche Fuji
init_x402(app, network="mainnets") # Base + Avalanche + IoTeX mainnet
# Direct parameter passing (overrides .env)
init_x402(
app,
pay_to="0x...",
network="base-sepolia",
facilitator_url="https://x402.org/facilitator"
)
from fastapi_x402 import get_supported_networks_list, get_config_for_network
# List all supported networks
networks = get_supported_networks_list()
print(networks) # ['base-sepolia', 'base', 'avalanche-fuji', 'avalanche', 'iotex']
# Get configuration for a specific network
config = get_config_for_network("base")
print(config["default_asset"]["address"]) # 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913
Your API can control which networks clients can use to pay:
# Only accept Base network payments
init_x402(app, pay_to="0x...", network="base")
@pay("$0.01")
@app.get("/base-only")
def base_only():
return {"data": "Must pay with Base USDC"}
402 Response: Client MUST pay on Base network
{"accepts": [{"network": "base", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"}]}
# Accept payments from multiple networks
init_x402(app, pay_to="0x...", network=["base", "avalanche", "iotex"])
@pay("$0.01")
@app.get("/multi-choice")
def multi_choice():
return {"data": "Pay with any supported network"}
402 Response: Client can choose from multiple networks
{"accepts": [
{"network": "base", "asset": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"},
{"network": "avalanche", "asset": "0xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E"},
{"network": "iotex", "asset": "0xcdf79194c6c285077a58da47641d4dbe51f63542"}
]}
@app.get("/pay-with-avalanche")
async def avalanche_only(request: Request):
# Custom 402 response for Avalanche only
return JSONResponse(status_code=402, content={
"accepts": [{"network": "avalanche", "asset": "0xB97..."}]
})
@app.get("/premium/{network}")
def network_specific(network: str):
if network not in ["base", "avalanche"]:
raise HTTPException(400, "Network not supported")
# Endpoint accepts payment only on specified network
init_x402(app, merchant_wallet, facilitator_url=None, config=None)Initialize x402 middleware for your FastAPI app.
Parameters:
app (FastAPI): Your FastAPI application instancemerchant_wallet (str): Your wallet address to receive paymentsfacilitator_url (str, optional): Custom facilitator URLconfig (X402Config, optional): Advanced configuration@pay(amount)Decorator to require payment for an endpoint.
Parameters:
amount (str): Payment amount (e.g., "$0.01", "$1.00")Returns:
base-sepoliabaseavalanche-fujiavalancheiotexAll networks support USDC with automatic configuration:
0x036CbD53842c5426634e7929541eC2318f3dCF7e0x833589fCD6eDb6E08f4c7C32D4f71b54bdA029130x5425890298aed601595a70AB815c96711a31Bc650xB97EF9Ef8734C71904D8002F8b6Bc66Dd9c48a6E0xcdf79194c6c285077a58da47641d4dbe51f63542To accept payments on mainnet networks, you need Coinbase Developer Platform (CDP) credentials:
API Key ID and API SecretNote: Based on the recently added official Coinbase x402 Python implementation, facilitator requests use simple HTTP without authentication headers. This is only implemented in testnet there. CDP credentials be stored for future use but are currently required for facilitator API calls for using mainnet facilitator hosted on CDP.
# .env
PAY_TO_ADDRESS=0x...
CDP_API_KEY_ID=your_api_key_id_here
CDP_API_KEY_SECRET=your_api_secret_here
X402_NETWORK=base # or avalanche, iotex
# Automatically detects CDP credentials and enables mainnet
init_x402(app, network="mainnets") # Supports Base, Avalanche, IoTeX
Why CDP? Mainnet payment settlement requires authenticated access to blockchain infrastructure. CDP provides reliable, scalable blockchain access with the security needed for production applications.
Note: Based on the official Coinbase x402 Python implementation, facilitator requests currently use simple HTTP without authentication headers. CDP credentials may be stored for future use but are not currently required for facilitator API calls.
# Install dev dependencies
pip install -e .[dev]
# Run tests
pytest
# Run with coverage
pytest --cov=fastapi_x402
/examplesgit checkout -b feature/amazing-feature)git commit -m 'Add some amazing feature')git push origin feature/amazing-feature)git clone https://github.com/jordo1138/fastapi-x402.git
cd fastapi-x402
pip install -e .[dev]
pre-commit install
Check out the /examples directory for:
"Can't patch loop of type uvloop.Loop" Error If you encounter this error, disable uvloop by using standard asyncio:
# Instead of: uvicorn.run(app)
uvicorn.run(app, loop="asyncio")
Static Files Not Working Ensure you're using the latest version (≥0.1.7) which fixes Mount object compatibility.
This project is licensed under the MIT License - see the LICENSE file for details.
Ready to monetize your APIs? Install fastapi-x402 and start earning in minutes! 🚀
The living ecosystem where AI agents complete tasks through workflow loops, improve through iterative execution, are evaluated by mentor agents or humans in the loop, and turn completed work into reusable work experience and data to improve future agents.
The living ecosystem where AI agents complete tasks through workflow loops, improve through iterative execution, are evaluated by mentor agents or humans in the loop, and turn completed work into reusable work experience and data to improve future agents.
Self-healing infrastructure for AI agent payments. 90.3% auto-recovery.
The first agentic payment network: policy-controlled, gasless, and real money-ready. OmniClaw CLI + Financial Policy Engine let autonomous agents pay and earn safely at machine speed.
The A2A x402 Extension brings cryptocurrency payments to the Agent-to-Agent (A2A) protocol, enabling agents to monetize their services through on-chain payments. This extension revives the spirit of HTTP 402 "Payment Required" for the decentralized agent ecosystem.
DePIN for Vintage Hardware — Proof-of-Antiquity blockchain where old machines outmine new ones. AI-powered hardware fingerprinting, 15+ CPU architectures, Solana bridge (wRTC). $0 VC.