Python Server

Add x402 payments to your FastAPI or Flask server. Perfect for AI services, data APIs, and Python-based backends.

Python Support

The x402 Python SDK works with FastAPI, Flask, and any ASGI/WSGI framework. Perfect for machine learning APIs, data services, and Python-based microservices.

Installation

pip

pip install x402-python

poetry

poetry add x402-python

FastAPI Example

Add x402 payment protection to your FastAPI endpoints:

from fastapi import FastAPI, Depends
from x402 import X402Middleware, require_payment
import os

app = FastAPI()

# Initialize x402 middleware
x402 = X402Middleware(
    wallet_address=os.getenv("WALLET_ADDRESS"),
    network="base-sepolia",
    facilitator_url="https://facilitator.payai.network"
)

# Apply middleware globally
app.add_middleware(x402)

# Protect specific endpoints
@app.get("/weather")
@require_payment(price="$0.001", network="base-sepolia")
async def get_weather():
    return {
        "temperature": 72,
        "condition": "sunny",
        "humidity": 45
    }

@app.post("/ai/generate")
@require_payment(price="$0.05", network="base-sepolia")
async def generate_ai_content(prompt: str):
    # Your AI generation logic
    return {
        "generated": f"AI response to: {prompt}"
    }

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

Flask Example

Use x402 with Flask applications:

from flask import Flask, jsonify
from x402 import X402Middleware, require_payment
import os

app = Flask(__name__)

# Initialize x402
x402 = X402Middleware(
    wallet_address=os.getenv("WALLET_ADDRESS"),
    network="base-sepolia",
    facilitator_url="https://facilitator.payai.network"
)

# Apply middleware
app.wsgi_app = x402(app.wsgi_app)

@app.route("/data")
@require_payment(price="$0.002", network="base-sepolia")
def get_data():
    return jsonify({
        "data": "Premium data content",
        "timestamp": "2025-01-01T00:00:00Z"
    })

@app.route("/analytics")
@require_payment(price="$0.01", network="base-sepolia")
def get_analytics():
    return jsonify({
        "metrics": {
            "users": 1000,
            "revenue": 50000
        }
    })

if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8000)

Configuration

Set up your environment variables:

# .env
WALLET_ADDRESS=0x... # Your wallet address to receive payments
NETWORK=base-sepolia # or base, polygon, solana
FACILITATOR_URL=https://facilitator.payai.network

# For Base mainnet (optional)
CDP_API_KEY_ID=your_cdp_key_id
CDP_API_KEY_SECRET=your_cdp_key_secret

Advanced Usage

Custom Pricing Logic

@app.get("/dynamic-pricing")
@require_payment(
    price=lambda request: calculate_price(request),
    network="base-sepolia"
)
async def dynamic_endpoint(request):
    return {"result": "content"}

def calculate_price(request):
    # Custom pricing based on request parameters
    size = request.query_params.get("size", "small")
    prices = {"small": "$0.001", "large": "$0.01"}
    return prices.get(size, "$0.001")

Multiple Networks

# Accept payment on multiple networks
@app.get("/multi-network")
@require_payment(
    price="$0.001",
    networks=["base-sepolia", "polygon", "solana"]
)
async def multi_network_endpoint():
    return {"data": "available on multiple chains"}

Use Cases

AI & ML Services

Monetize GPT models, image generation, data analysis, and machine learning inference APIs

Data APIs

Charge per query for financial data, weather data, market analytics, and real-time feeds

Scraping Services

Monetize web scraping, data extraction, and content aggregation endpoints

Processing APIs

Charge for PDF generation, image processing, video conversion, and data transformation

Deploy Your Python Service

Ready to deploy? Learn about client integration and production deployment.

Nova402