Flask Integration
This guide walks you through adding x402 payment requirements to a Flask 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 flask 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 flask import Flask, jsonify
from x402.middleware.flask import require_payment
from x402.types import FacilitatorConfig
load_dotenv()
app = Flask(__name__)
ADDRESS = os.getenv("ADDRESS")
FACILITATOR_URL = os.getenv("FACILITATOR_URL")
facilitator = FacilitatorConfig(url=FACILITATOR_URL)
@app.route("/weather")
@require_payment(
address=ADDRESS,
facilitator=facilitator,
price="$0.001",
network="solana-devnet",
description="Get weather data",
)
def get_weather():
return jsonify({"report": {"weather": "sunny", "temperature": 70}})
if __name__ == "__main__":
app.run(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.pyThe 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.route("/weather")
@require_payment(
address=ADDRESS,
facilitator=facilitator,
price="$0.001",
network="solana-devnet",
description="Get weather data",
)
def get_weather():
return jsonify({"report": {"weather": "sunny", "temperature": 70}})
@app.route("/forecast")
@require_payment(
address=ADDRESS,
facilitator=facilitator,
price="$0.005",
network="solana-devnet",
description="Get 7-day forecast",
)
def get_forecast():
return jsonify({"forecast": [{"day": "Monday", "weather": "sunny"}]})Routes without the decorator remain free and accessible without payment.