FastAPI Integration
This guide walks you through adding x402 payment requirements to a FastAPI server. By the end, you will have a running API that charges $0.001 per request on a protected route, with payment verification and settlement handled by the facilitator.
Installation
bash
pip install x402 fastapi uvicorn python-dotenvEnvironment Setup
Create a .env file in your project root:
bash
ADDRESS=<your-solana-wallet-address>
FACILITATOR_URL=https://facilitator.svmacc.tech| Variable | Description |
|---|---|
ADDRESS | The Solana wallet address where you want to receive payments. |
FACILITATOR_URL | The URL of the x402 facilitator service that verifies and settles payments. |
Server Code
Create a file called server.py:
python
import os
from dotenv import load_dotenv
from fastapi import FastAPI
from x402.middleware.fastapi import require_payment
from x402.types import FacilitatorConfig
load_dotenv()
app = FastAPI()
ADDRESS = os.getenv("ADDRESS")
FACILITATOR_URL = os.getenv("FACILITATOR_URL")
facilitator = FacilitatorConfig(url=FACILITATOR_URL)
@app.get("/weather")
@require_payment(
address=ADDRESS,
facilitator=facilitator,
price="$0.001",
network="solana-devnet",
description="Get weather data",
)
async def get_weather():
return {"report": {"weather": "sunny", "temperature": 70}}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=4021)How It Works
FacilitatorConfigcreates a configuration object pointing at the facilitator service athttps://facilitator.svmacc.tech.- The
@require_paymentdecorator wraps your route handler. When a request arrives without a validX-PAYMENTheader, it returns a402 Payment Requiredresponse containing the payment terms (price, network, facilitator URL, and your wallet address). - When a client includes a valid payment header, the decorator forwards the payment proof to the facilitator for on-chain verification and settlement. If the payment is valid, your route handler executes normally.
- The
networkparameter is set tosolana-devnetfor testing. Switch tosolana-mainnetfor production.
Running the Server
bash
python server.pyOr using uvicorn directly:
bash
uvicorn server:app --host 0.0.0.0 --port 4021The server will start on http://localhost:4021. Requests to GET /weather without payment will receive a 402 response with payment instructions.
Protecting Multiple Routes
Apply the @require_payment decorator to any route you want to charge for:
python
@app.get("/weather")
@require_payment(
address=ADDRESS,
facilitator=facilitator,
price="$0.001",
network="solana-devnet",
description="Get weather data",
)
async def get_weather():
return {"report": {"weather": "sunny", "temperature": 70}}
@app.get("/forecast")
@require_payment(
address=ADDRESS,
facilitator=facilitator,
price="$0.005",
network="solana-devnet",
description="Get 7-day forecast",
)
async def get_forecast():
return {"forecast": [{"day": "Monday", "weather": "sunny"}]}Routes without the decorator remain free and accessible without payment.