๐ The fast, Pythonic way to build x402 servers and clients. Supports x402Instant.
fastx402 is an early-stage Python project in the AI payments / x402 ecosystem, focused on crypto, fastapi, payments, python. It currently has 0 GitHub stars and 0 forks, and sits alongside related tools like agent-commerce-framework, crewai-x402, agenti, pay-kit, mpp-sdk, sardis.
FastAPI integration for x402 HTTP-native payments using stablecoins. This library enables Python backend servers to protect API endpoints with payment requirements using HTTP 402 responses and EIP-712 signature verification.
pip install fastx402
Create a .env file:
X402_MERCHANT_ADDRESS=0xYourMerchantAddress
X402_CHAIN_ID=8453
X402_CURRENCY=USDC
from fastapi import FastAPI
from fastx402 import payment_required
app = FastAPI()
@app.get("/free")
def free_route():
return {"msg": "no charge"}
@app.get("/paid")
@payment_required(price="0.01", currency="USDC", chain_id="8453")
def paid_route():
return {"msg": "you paid!"}
uvicorn main:app --reload
X402Server - Core server class for payment challenge management:
X-PAYMENT headers@payment_required Decorator - FastAPI route decorator:
X-PAYMENT header on incoming requestsX402Client - Async httpx-based client:
X-PAYMENT headersX402Session - Requests library wrapper:
requests.Session for synchronous HTTP requestsX402HttpxClient - httpx wrapper (sync/async):
The x402 payment flow follows these steps:
X-PAYMENT header containing signatureeth-account libraryInstant Mode (default):
Embedded Mode:
Note: Mode is configured on the client, not the server. The server always verifies signatures the same way.
Server Environment Variables:
X402_MERCHANT_ADDRESS: Merchant wallet address (required)X402_CHAIN_ID: Default chain ID (e.g., 8453 for Base)X402_CURRENCY: Default currency (e.g., USDC)Per-Route Configuration:
X402Session class and patch_requests() functionX402Client (async) and X402HttpxClient (sync/async)X402_MERCHANT_ADDRESS=0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb
X402_CHAIN_ID=8453
X402_CURRENCY=USDC
@app.get("/expensive")
@payment_required(
price="0.05",
currency="USDC",
chain_id="8453",
description="Premium content access"
)
def expensive_route():
return {"content": "premium data"}
from fastx402 import configure_server
configure_server(
config=PaymentConfig(
merchant_address="0x...",
chain_id=8453,
currency="USDC"
)
)
Note: WAAS providers are configured on the client side, not the server. See client-side usage below.
Client uses user's wallet (MetaMask, WalletConnect, etc.) to sign payments. Server verifies signatures cryptographically.
Use Cases:
Client uses Wallet-as-a-Service (WAAS) providers like Privy for signing. Server verifies signatures cryptographically (same as instant mode).
Use Cases:
Note: Mode is configured on the client side using x402instant library. See x402instant documentation for WAAS setup.
For backend-to-backend requests that need to handle 402 challenges:
Using WebSocket server (frontend x402instant connects to us):
from fastx402 import X402Client
# Client starts WebSocket server - frontend x402instant auto-connects
client = X402Client(
base_url="https://api.example.com",
ws_port=4021 # Frontend x402instant will connect to this
)
response = await client.get("/paid-endpoint")
data = await response.json()
Using RPC handler (local signing):
from fastx402 import X402Client
from fastx402.types import PaymentChallenge, PaymentSignature
async def sign_payment(challenge: PaymentChallenge) -> Optional[PaymentSignature]:
# Sign challenge locally (e.g., using private key or WAAS)
return signed_payment
client = X402Client(
base_url="https://api.example.com",
rpc_handler=sign_payment
)
response = await client.get("/paid-endpoint")
data = await response.json()
Wrap requests library to automatically handle 402 challenges:
from fastx402 import patch_requests
def handle_x402(challenge):
# Sign challenge and return X-PAYMENT header value
return signed_payment_header
session = patch_requests(handle_x402=handle_x402)
response = session.get("https://api.example.com/protected")
data = response.json()
Or use the X402Session class:
from fastx402 import X402Session
def handle_x402(challenge):
return signed_payment_header
session = X402Session(handle_x402=handle_x402)
response = session.get("https://api.example.com/protected")
Wrap httpx for async requests:
from fastx402 import X402HttpxClient
async def handle_x402(challenge):
return await sign_payment(challenge)
# Sync usage
client = X402HttpxClient(handle_x402=handle_x402)
response = client.get("https://api.example.com/protected")
# Async usage
async def main():
async with X402HttpxClient(handle_x402=handle_x402) as client:
response = await client.get("https://api.example.com/protected")
fastx402 provides convenience wrappers for popular frameworks to enable x402 payment handling:
Enable FastAPI servers to make outgoing x402 requests to other services:
from fastapi import FastAPI
from fastx402 import wrap_fastapi_server
app = FastAPI()
async def handle_x402(challenge):
return await sign_payment(challenge)
# Wrap the FastAPI app to enable x402 requests
app = wrap_fastapi_server(
app=app,
handle_x402=handle_x402
)
@app.get("/proxy")
async def proxy_endpoint():
# Use the x402-enabled client from app state
client = app.state.x402_client
response = await client.get("https://api.example.com/paid-endpoint")
return await response.json()
Or use the X402FastAPIApp class:
from fastx402 import X402FastAPIApp
async def handle_x402(challenge):
return await sign_payment(challenge)
app = X402FastAPIApp(
handle_x402=handle_x402
)
@app.app.get("/proxy")
async def proxy_endpoint():
client = app.app.state.x402_client
response = await client.get("https://api.example.com/paid")
return await response.json()
Wrap FastMCP clients to automatically catch 402 responses and fire callbacks:
from fastmcp import Client as FastMCPClient
from fastx402 import wrap_fastmcp_client
async def handle_x402(challenge):
return await sign_payment(challenge)
# Wrap existing FastMCP client
mcp_client = FastMCPClient("https://api.example.com/mcp")
wrapped_client = wrap_fastmcp_client(
handle_x402=handle_x402,
mcp_client=mcp_client
)
async with wrapped_client as client:
result = await client.call_tool("tool_name", {"param": "value"})
Or use the X402FastMCPClient class:
from fastx402 import X402FastMCPClient
async def handle_x402(challenge):
return await sign_payment(challenge)
client = X402FastMCPClient(
url="https://api.example.com/mcp",
handle_x402=handle_x402
)
async with client as mcp:
result = await mcp.call_tool("tool_name", {"param": "value"})
Enable FastMCP servers to make outgoing x402 requests to other services:
from fastmcp import Server as FastMCPServer
from fastx402 import wrap_fastmcp_server
async def handle_x402(challenge):
return await sign_payment(challenge)
# Wrap existing FastMCP server
server = FastMCPServer()
wrapped_server = wrap_fastmcp_server(
handle_x402=handle_x402,
mcp_server=server
)
# Now server can make x402 requests
response = await wrapped_server.x402_client.get("https://api.example.com/paid")
Or use the X402FastMCPServer class:
from fastx402 import X402FastMCPServer
async def handle_x402(challenge):
return await sign_payment(challenge)
server = X402FastMCPServer(
handle_x402=handle_x402
)
# Make x402 requests using the attached client
response = await server.x402_client.get("https://api.example.com/paid")
Note: FastMCP wrappers require fastmcp to be installed. FastAPI server wrapper requires fastapi to be installed. These are optional dependencies and the wrappers will only be available if the respective packages are installed.
The library uses Pydantic models for type safety and validation:
PaymentChallenge: Payment challenge structure with price, currency, chain ID, merchant, timestamp, description, and noncePaymentConfig: Global payment configurationPaymentVerificationResult: Result of payment signature verificationPaymentSignature: Signed payment payload with signature, signer, and challengepayment_required(price, currency=None, chain_id=None, description=None) - FastAPI decorator for payment protectionconfigure_server(config=None) - Configure global server instanceX402Server - Server class for challenge creation and verificationcreate_challenge(price, currency=None, chain_id=None, description=None) - Create payment challengeverify_payment_header(request) - Verify X-PAYMENT headerissue_402_response(challenge) - Create HTTP 402 responseX402Client - Async httpx clientget(path, **kwargs) - GET requestpost(path, **kwargs) - POST requestrequest(method, path, **kwargs) - Generic requestX402Session - Requests session wrapperX402HttpxClient - httpx wrapper (sync/async)patch_requests(handle_x402, session=None) - Patch requests sessionFor frontend applications, use x402instant to handle wallet connections and payment signing:
# Backend (fastx402)
@app.get("/paid")
@payment_required(price="0.01", currency="USDC", chain_id="8453")
def paid_route():
return {"msg": "you paid!"}
// Frontend (x402instant)
import { x402Fetch } from "x402instant";
const response = await x402Fetch("http://api.example.com/paid");
const data = await response.json();
fastapi>=0.104.0 - Web frameworkhttpx>=0.25.0 - Async HTTP clientrequests>=2.31.0 - Synchronous HTTP clientpython-dotenv>=1.0.0 - Environment variable managementpydantic>=2.0.0 - Data validationeth-account>=0.9.0 - Ethereum account and signingeth-utils>=2.0.0 - Ethereum utilitiespytest
See the example/ directory for complete working examples:
MIT
Open-source marketplace where AI agents autonomously discover, negotiate, and purchase API services. x402 USDC payments, MCP bridge, reputation engine. MIT license.
CrewAI integration for x402 payments - autonomous agent crews that pay for APIs with USDC
Give any AI agent a crypto wallet. Agents deserve access to money. Pay x402 APIs, receive USDC, check balances โ autonomously. Works with Claude, LangChain, AutoGen, CrewAI, and any MCP client. EVM + Solana.
Building blocks for Agentic payments (x402, MPP, AP2) for TypeScript, Rust, Go, Python, Ruby, PHP, Lua, Kotlin and Swift.
Building blocks for Agentic payments (x402, MPP, AP2) for TypeScript, Rust, Go, Python, Ruby, PHP, Lua, Kotlin and Swift.
The open authority layer + SDKs for AI-agent payments. Thin Python/TS clients, an MCP server, framework adapters (LangChain/CrewAI/Hermes/OpenClaw/โฆ), and @sardis/reference โ a pure policy simulator + AP2/TAP/x402 verifiers showing exactly how Sardis decides if an agent may spend. The hosted engine that moves money is private.
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.