Skip to main content

FastAPI middleware and decorators for X402 payment protocol

Project description

openlibx402-fastapi

FastAPI middleware and decorators for adding X402 payment requirements to API endpoints.

Overview

The openlibx402-fastapi package makes it easy to add payment requirements to your FastAPI endpoints. Simply decorate endpoints with payment requirements, and the middleware handles payment verification automatically.

Features

  • Easy-to-use decorators for payment-required endpoints
  • Dependency injection support for accessing payment details
  • Automatic 402 Payment Required response generation
  • Configurable payment amounts and descriptions
  • Seamless integration with existing FastAPI applications

Installation

pip install openlibx402-fastapi

Quick Start

1. Initialize X402 Configuration

from fastapi import FastAPI
from openlibx402_fastapi import X402Config, init_x402
import os

# Initialize X402 configuration
config = X402Config(
    payment_address=os.getenv("PAYMENT_WALLET_ADDRESS"),
    token_mint=os.getenv("USDC_MINT_ADDRESS"),
    network="solana-devnet",
    rpc_url=os.getenv("SOLANA_RPC_URL", "https://api.devnet.solana.com"),
)
init_x402(config)

app = FastAPI()

2. Add Payment Requirements with Decorator

from fastapi import Request
from openlibx402_fastapi import payment_required

@app.get("/premium-data")
@payment_required(
    amount="0.10",
    description="Access to premium market data"
)
async def get_premium_data(request: Request):
    """Endpoint requires 0.10 USDC payment"""
    return {
        "data": "This is premium content",
        "market_data": {"price": 100.50, "volume": 1_000_000}
    }

3. Access Payment Details with Dependency Injection

from fastapi import Depends
from openlibx402_fastapi import verify_payment_factory
from openlibx402_core import PaymentAuthorization

@app.get("/expensive-data")
async def get_expensive_data(
    payment: PaymentAuthorization = Depends(
        verify_payment_factory(
            amount="1.00",
            description="Access to expensive AI model inference"
        )
    )
):
    """Access payment details in your endpoint"""
    return {
        "data": "AI-generated content",
        "payment_id": payment.payment_id,
        "amount_paid": payment.actual_amount,
        "transaction_hash": payment.transaction_hash,
    }

Usage Patterns

Pattern 1: Simple Decorator (Recommended)

Best for endpoints that don't need to access payment details:

@app.get("/data")
@payment_required(amount="0.05", description="Data access")
async def get_data(request: Request):
    return {"data": "content"}

Pattern 2: Dependency Injection

Best when you need to access payment details (transaction hash, amount, etc.):

@app.get("/data")
async def get_data(
    payment: PaymentAuthorization = Depends(
        verify_payment_factory(amount="0.05", description="Data access")
    )
):
    return {
        "data": "content",
        "payment_id": payment.payment_id,
        "tx_hash": payment.transaction_hash,
    }

Pattern 3: Dynamic Pricing

Adjust payment requirements based on parameters:

@app.get("/tiered-data/{tier}")
@payment_required(amount="0.05", description="Tiered data access")
async def get_tiered_data(request: Request, tier: str):
    """Payment required regardless of tier"""
    tier_data = {
        "basic": {"quality": "720p"},
        "premium": {"quality": "4K"},
    }
    return {"tier": tier, "data": tier_data.get(tier)}

Complete Example

from fastapi import FastAPI, Depends, Request
from openlibx402_fastapi import (
    payment_required,
    verify_payment_factory,
    X402Config,
    init_x402
)
from openlibx402_core import PaymentAuthorization
import os

# Initialize X402
config = X402Config(
    payment_address=os.getenv("PAYMENT_WALLET_ADDRESS"),
    token_mint=os.getenv("USDC_MINT_ADDRESS"),
    network="solana-devnet",
)
init_x402(config)

app = FastAPI()

@app.get("/")
async def root():
    """Public endpoint - no payment required"""
    return {"message": "Welcome to the API"}

@app.get("/premium")
@payment_required(amount="0.10", description="Premium data")
async def premium(request: Request):
    """Protected endpoint - payment required"""
    return {"data": "premium content"}

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

Configuration

X402Config Options

  • payment_address: Your Solana wallet address for receiving payments
  • token_mint: Token mint address (e.g., USDC on Solana)
  • network: Network name (e.g., "solana-devnet", "solana-mainnet")
  • rpc_url: Solana RPC endpoint URL

Documentation

For complete API reference and guides, see:

Testing

pytest tests/

License

MIT License - See LICENSE file for details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

openlibx402_fastapi-0.1.1.tar.gz (7.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

openlibx402_fastapi-0.1.1-py3-none-any.whl (10.4 kB view details)

Uploaded Python 3

File details

Details for the file openlibx402_fastapi-0.1.1.tar.gz.

File metadata

  • Download URL: openlibx402_fastapi-0.1.1.tar.gz
  • Upload date:
  • Size: 7.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.9.23

File hashes

Hashes for openlibx402_fastapi-0.1.1.tar.gz
Algorithm Hash digest
SHA256 fd6d60d635ecf733a82a63e99edf738c03590416baf4882b43723042d8954ffd
MD5 8de8b744115c8b98486412178eaa2168
BLAKE2b-256 490e35f27ae1feccd357b7e062c11e1922ad0554853f44c605e4c4b48cef89cc

See more details on using hashes here.

File details

Details for the file openlibx402_fastapi-0.1.1-py3-none-any.whl.

File metadata

File hashes

Hashes for openlibx402_fastapi-0.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f2ae6ef20e6a7bf4cb90e0c7c0378e84f25545dfe416b3886acfc199e68802b0
MD5 b44edd0fb04bcc484fc65591053e4dc9
BLAKE2b-256 a6bc24039f70b5af075023edb3c280a1185b919ebd1328ee4c69bb1f17844221

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page