Skip to main content
Start here: need to register a service and create a plan first? Follow the 5-minute setup.
Add payment protection to your FastAPI application using the x402 protocol. The PaymentMiddleware handles verification and settlement automatically.

x402 Payment Flow

Installation

The [fastapi] extra installs FastAPI and Starlette dependencies required for the middleware.

Quick Start: One-Line Payment Protection

The PaymentMiddleware from payments_py.x402.fastapi handles the entire x402 flow:
That’s it! The middleware automatically:
  • Returns 402 with payment-required header when no token is provided
  • Verifies the x402 token via the Nevermined facilitator
  • Burns credits after request completion
  • Returns payment-response header with settlement receipt

x402 Headers

The middleware follows the x402 HTTP transport spec:

Route Configuration

Fixed Credits

Path Parameters

With Agent ID

Using RouteConfig

For more explicit configuration, use RouteConfig:
When scheme is omitted, the middleware calls resolve_scheme() to auto-detect the correct scheme from plan metadata. Plans with fiat pricing (isCrypto: false) automatically use nvm:card-delegation (Stripe).

Dynamic Credits

Calculate credits based on request data:
Sync functions also work:

Payment Scheme (Crypto vs. Fiat)

The middleware auto-detects the payment scheme from plan metadata. Plans with fiat pricing (isCrypto: false) automatically use nvm:card-delegation (Stripe), while crypto plans use nvm:erc4337. You can explicitly override the scheme in the route configuration:
The middleware automatically detects the payment scheme from plan metadata. Plans with fiat pricing (isCrypto: false) use nvm:card-delegation (Stripe). No code changes are needed on the agent side. You can explicitly override with the scheme parameter.
For the full card-delegation specification, see the Card Delegation Spec.

Middleware Options

Accessing Payment Context

After verification, the payment context is available in request.state.payment_context:

Complete Example

See the complete working example in the http-simple-agent-py tutorial on GitHub.

With Observability

For full observability integration with Helicone:

Client Implementation

For fiat plans, clients can use resolve_scheme() to auto-detect the payment scheme before generating tokens. See the x402 developer guide for details on scheme resolution and X402TokenOptions.
Here’s how clients interact with your payment-protected API:

Environment Variables

Alternative: Manual Dependency Injection

For more control or complex scenarios, you can use FastAPI’s dependency injection instead of middleware:

Next Steps

Payment Patterns

Advanced credit charging patterns

x402 Protocol

Deep dive into x402 payment flows

Payment Models

Configure credits, subscriptions, and dynamic pricing

http-simple-agent-py Tutorial

Complete working example on GitHub