FastAPI Quickstart

Set up an x402-protected resource server with Python 3.11+ and FastAPI.

Step 1: Install dependencies

pip install fastapi uvicorn x402-xrpl python-dotenv

Step 2: Set your environment variables

Create a .env file with your configuration:

XRPL_FACILITATOR_URL=https://xrpl-facilitator-testnet.t54.ai
XRPL_NETWORK=xrpl:1
XRPL_PAY_TO=rha... # your wallet address to receive funds
XRPL_PRICE_DROPS=1000 # price in drops (1 XRP = 1,000,000 drops)

Step 3: Create your server

import os
from dotenv import load_dotenv
from fastapi import FastAPI
from x402_xrpl.server import require_payment

load_dotenv()

app = FastAPI()

# 1. Configure the x402 middleware
# This protects specific paths (or all paths if path=None)
# and handles the 402 Payment Required flow automatically.
app.middleware("http")(
    require_payment(
        path="/hello",  # Protect only the /hello endpoint
        price=os.getenv("XRPL_PRICE_DROPS", "1000"),
        pay_to_address=os.getenv("XRPL_PAY_TO"),
        facilitator_url=os.getenv("XRPL_FACILITATOR_URL"),
        network=os.getenv("XRPL_NETWORK", "xrpl:1"),
        asset="XRP",
        description="A paid hello world endpoint",
    )
)

# 2. Define your paid endpoint
# This handler is only called if the payment is valid and settled.
@app.get("/hello")
async def hello():
    return {"message": "Hello World! Thanks for the payment."}

# 3. Define a free endpoint
@app.get("/health")
async def health():
    return {"status": "ok"}

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

Step 4: Run the server

python server.py

Try visiting http://localhost:8000/hello. You will receive a 402 Payment Required response, which your client (like the Python requests client) can use to pay. The facilitator URL belongs on this resource server or on direct facilitator API calls, not in buyer client setup.