Menu

Add x402 pay-per-call to a FastAPI server in ~40 lines
πŸ“°

Add x402 pay-per-call to a FastAPI server in ~40 lines

DEV Community: pythonΒ·int devΒ·1 day ago
#BizTTRFo
#devtopython#devto#dev#payment#json
Reading 0:00
15s threshold

Adding x402 pay-per-call to a FastAPI server in ~40 lines

x402 is the Coinbase HTTP-payment standard: your server returns 402 Payment Required with payment terms, the client signs a USDC transfer, retries with the payment header, and your middleware settles on-chain. No API keys, no accounts β€” the signature IS the auth.

import base64 , json from fastapi import FastAPI , Request from fastapi . responses import JSONResponse

PAY_TO = "0xYourWallet" FACILITATOR = "https://facilitator.payai.network"

def paywall ( price_usdc : str , description : str ) : async def mw ( request : Request , call_next ) : pay_header = request . headers . get ( "x-payment" ) if not pay_header : # tell the client what to pay return JSONResponse ( { "x402Version" : 1 , "accepts" : [ { "scheme" : "exact" , "network" : "base" , "maxAmountRequired" : price_usdc , "resource" : str ( request .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.