Getting Started with Flask
Start accepting x402 payments in your Flask server in 2 minutes.
Example Code
You can find the full code for this example on GitHub.
Step 1: Install Dependencies
Install the required packages for your Flask server:
pip install x402 flask python-dotenv
Step 2: Set Your Environment Variables
Create a .env file in your project root:
echo "ADDRESS=0x...\nNETWORK=sui" > .env
Your .env file should look like this:
ADDRESS=0x... # wallet public address you want to receive payments to
NETWORK=sui # recommended for fastest settlement
# Optional: Configure facilitator URL if using custom facilitator
# FACILITATOR_URL=https://x402.blockeden.xyz
Network Options
BlockEden.xyz supports multiple networks:
sui(recommended for fastest settlement)ethereumbasepolygonavalanche
Step 3: Create a New Flask App
Create an app.py file with the following code:
import os
from typing import Any, Dict
from dotenv import load_dotenv
from flask import Flask, jsonify
from x402.flask.middleware import PaymentMiddleware
from x402.types import TokenAmount, TokenAsset, EIP712Domain
# Load environment variables
load_dotenv()
# Get configuration from environment
ADDRESS = os.getenv("ADDRESS")
NETWORK = os.getenv("NETWORK", "sui")
if not ADDRESS:
raise ValueError("Missing required environment variables")
app = Flask(__name__)
# Initialize payment middleware
payment_middleware = PaymentMiddleware(app)
# Apply payment middleware to specific routes
payment_middleware.add(
path="/weather",
price="$0.001",
pay_to_address=ADDRESS,
network=NETWORK,
)
# Apply payment middleware to premium routes
payment_middleware.add(
path="/premium/*",
price=TokenAmount(
amount="10000",
asset=TokenAsset(
address="0x...", # USDC contract address for your network
decimals=6,
eip712=EIP712Domain(name="USDC", version="2"),
),
),
pay_to_address=ADDRESS,
network=NETWORK,
)
@app.route("/")
def index() -> Dict[str, str]:
"""Root endpoint"""
return jsonify({
"message": "x402 Payment Server",
"status": "running",
})
@app.route("/weather")
def get_weather() -> Dict[str, Any]:
"""Get weather data - requires payment"""
return jsonify({
"report": {
"weather": "sunny",
"temperature": 70,
"location": "San Francisco",
}
})
@app.route("/premium/content")
def get_premium_content() -> Dict[str, Any]:
"""Get premium content - requires payment"""
return jsonify({
"content": "This is premium content",
"type": "article",
"timestamp": "2025-01-01T00:00:00Z",
})
@app.route("/premium/analytics")
def get_premium_analytics() -> Dict[str, Any]:
"""Get premium analytics - requires payment"""
return jsonify({
"analytics": {
"users": 1000,
"revenue": 50000,
"growth": 25.5,
}
})
if __name__ == "__main__":
app.run(
host="0.0.0.0",
port=4021,
debug=True,
)
Step 4: Run the Server
Start your Flask server:
python app.py
Or use Flask's built-in development server:
flask --app app run --port 4021
Your server will be available at http://localhost:4021.
Step 5: Test the Server
You can test payments against your server locally using HTTP clients like curl, Postman, or by building a Python client application.
Coming Soon
Client implementation guides for httpx and requests libraries will be available soon.