Overview
The prism-flask package provides Flask middleware for payment-protecting your API routes using the x402 protocol. It uses Flask’s decorator pattern and request context for seamless integration.Pythonic API
Flask decorators and context managers
Request Context
Payment info in
g.prism_payerMinimal Setup
Single function call to configure
Installation
- pip
- Poetry
- requirements.txt
Quick Start
Configuration
Middleware Configuration
Route Configuration
Route Protection Patterns
Exact Path Matching
Wildcard Matching
Multiple Route Groups
Accessing Payment Information
Payment info is stored in Flask’sg context object:
Safe Access Helper
Settlement Validation
The Flask middleware uses @app.after_request decorator to validate settlement before sending data:@app.after_requestruns after view function but before sending to client- Can return a different response if settlement fails
- Works with all Flask response types (
jsonify(),make_response(), etc.)
Error Handling
Payment Errors
When a request lacks valid payment:Gateway Errors
Custom Error Handlers
Testing
Unit Testing with pytest
Integration Testing
Production Deployment
Environment Variables
Production Configuration
Logging & Monitoring
WSGI Deployment (Gunicorn)
Type Hints
Full type hint support with mypy:Examples
AI Agent API
Content Paywall
Premium API with Rate Limiting
Troubleshooting
ImportError: cannot import name 'prism_payment_middleware'
ImportError: cannot import name 'prism_payment_middleware'
Make sure you installed the correct package:Check Python version:
g.prism_payer is None even with valid payment
g.prism_payer is None even with valid payment
Check: 1. Payment header is properly formatted JSON string 2. Middleware
is configured BEFORE route definitions 3. Route path matches configured route
pattern 4. Payment signature is valid Debug:
python @app.before_request def debug_payment(): print(f'Path: {request.path}') print(f'Payment header:{" "} {request.headers.get("X-PAYMENT")}') print(f'Payer:{" "} {getattr(g, "prism_payer", "NOT SET")}') Settlement fails but payment was valid
Settlement fails but payment was valid
Common causes: 1. Insufficient balance in sender’s wallet 2. Token
allowance not set for USDC contract 3. Network congestion (transaction
timeout) 4. Nonce already used (replay attack prevention) Check logs:
python import logging logging.basicConfig(level=logging.DEBUG) Type hints not working in IDE
Type hints not working in IDE
Install type stubs:Configure mypy: