x402 Python
Python package for the x402 payments protocol.
Installation
pip install x402
Overview
The x402 package provides the core building blocks for implementing the x402 Payment Protocol in Python. It's designed to be used by:
- FastAPI middleware for accepting payments
- Flask middleware for accepting payments
- httpx client for paying resources
- requests client for paying resources
FastAPI Integration
The simplest way to add x402 payment protection to your FastAPI application:
from fastapi import FastAPI
from x402.fastapi.middleware import require_payment
app = FastAPI()
app.middleware("http")(
require_payment(price="0.01", pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C")
)
@app.get("/")
async def root():
return {"message": "Hello World"}
To protect specific routes:
app.middleware("http")(
require_payment(price="0.01",
pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C"),
path="/foo" # <-- this can also be a list ex: ["/foo", "/bar"]
)
Flask Integration
The simplest way to add x402 payment protection to your Flask application:
from flask import Flask
from x402.flask.middleware import PaymentMiddleware
app = Flask(__name__)
# Initialize payment middleware
payment_middleware = PaymentMiddleware(app)
# Add payment protection for all routes
payment_middleware.add(
price="$0.01",
pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
)
@app.route("/")
def root():
return {"message": "Hello World"}
To protect specific routes:
# Protect specific endpoint
payment_middleware.add(
path="/foo",
price="$0.001",
pay_to_address="0x209693Bc6afc0C5328bA36FaF03C514EF312287C",
)
Client Integration
Simple Usage
Httpx Client
from eth_account import Account
from x402.clients.httpx import x402HttpxClient
# Initialize account
account = Account.from_key("your_private_key")
# Create client and make request
async with x402HttpxClient(account=account, base_url="https://api.example.com") as client:
response = await client.get("/protected-endpoint")
print(await response.aread())
Requests Session Client
from eth_account import Account
from x402.clients.requests import x402_requests
# Initialize account
account = Account.from_key("your_private_key")
# Create session and make request
session = x402_requests(account)
response = session.get("https://api.example.com/protected-endpoint")
print(response.content)
Advanced Usage
Httpx Extensible Example
import httpx
from eth_account import Account
from x402.clients.httpx import x402_payment_hooks
# Initialize account
account = Account.from_key("your_private_key")
# Create httpx client with x402 payment hooks
async with httpx.AsyncClient(base_url="https://api.example.com") as client:
# Add payment hooks directly to client
client.event_hooks = x402_payment_hooks(account)
# Make request - payment handling is automatic
response = await client.get("/protected-endpoint")
print(await response.aread())
Requests Session Extensible Example
import requests
from eth_account import Account
from x402.clients.requests import x402_http_adapter
# Initialize account
account = Account.from_key("your_private_key")
# Create session and mount the x402 adapter
session = requests.Session()
adapter = x402_http_adapter(account)
# Mount the adapter for both HTTP and HTTPS
session.mount("http://", adapter)
session.mount("https://", adapter)
# Make request - payment handling is automatic
response = session.get("https://api.example.com/protected-endpoint")
print(response.content)
Manual Server Integration
If you're not using the FastAPI middleware, you can implement the x402 protocol manually. Here's what you'll need to handle:
- Return 402 error responses with the appropriate response body
- Use the facilitator to validate payments
- Use the facilitator to settle payments
- Return the appropriate response header to the caller
Here's an example of manual integration:
from typing import Annotated
from fastapi import FastAPI, Request
from x402.types import PaymentRequiredResponse, PaymentRequirements
from x402.encoding import safe_base64_decode
payment_requirements = PaymentRequirements(...)
facilitator = FacilitatorClient(facilitator_url)
@app.get("/foo")
async def foo(req: request: Request):
payment_required = PaymentRequiredResponse(
x402_version: 1,
accepts=[payment_requirements],
error="",
)
payment_header = req.headers.get("X-PAYMENT", "")
if payment_header == "":
payment_required.error = "X-PAYMENT header not set"
return JSONResponse(
content=payment_required.model_dump(by_alias=True),
status_code=402,
)
payment = PaymentPayload(**json.loads(safe_base64_decode(payment_header)))
verify_response = await facilitator.verify(payment, payment_requirements)
if not verify_response.is_valid:
payment_required.error = "Invalid payment"
return JSONResponse(
content=payment_required.model_dump(by_alias=True),
status_code=402,
)
settle_response = await facilitator.settle(payment, payment_requirements)
if settle_response.success:
response.headers["X-PAYMENT-RESPONSE"] = base64.b64encode(
settle_response.model_dump_json().encode("utf-8")
).decode("utf-8")
else:
payment_required.error = "Settle failed: " + settle_response.error
return JSONResponse(
content=payment_required.model_dump(by_alias=True),
status_code=402,
)
For more examples and advanced usage patterns, check out our examples directory.
Metadata
Release files for og-test-x402 0.0.10
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| og_test_x402-0.0.10.tar.gz | 2.2 MB | Without provenance | Details for og_test_x402-0.0.10.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| og_test_x402-0.0.10-py3-none-any.whl | Python 3 | none | any | Details for og_test_x402-0.0.10-py3-none-any.whl |
Total release size: 4.3 MB
Release files / og_test_x402-0.0.10.tar.gz
| Download URL | og_test_x402-0.0.10.tar.gz |
|---|---|
| Size | 2.2 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
66dc78e344b5974dfdb9c667eb28ca33648eaa983492089d52806d00f841b5f0
|
|
BLAKE2b-256 checksum How to use checksums |
1fabc9917b34b5aaaf7c068e73aeedc17bb4cf9c558ff250c1e1531894ba4f78
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.6.17
|
Release files / og_test_x402-0.0.10-py3-none-any.whl
| Download URL | og_test_x402-0.0.10-py3-none-any.whl |
|---|---|
| Size | 2.1 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
5d9a5b089314bd424b3b31e23fa45f7c24e86bb3748b043a46946cdf21f98269
|
|
BLAKE2b-256 checksum How to use checksums |
0025f50e6c7a98847ede5c42dfe326b10a116fab5796d212b94f66f3d9455fba
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.6.17
|
Security for og-test-x402 0.0.10
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.