Skip to content

402x APIs

APIs That Pay Per Call

Add one line of middleware to charge per request, token, or inference.

Perfect for AI, data, or SaaS endpoints.


Why Monetize Your API?

You've built something valuable. Whether it's:

  • An AI model that generates text, images, or predictions
  • A data API that serves real-time information
  • A specialized service that solves a specific problem

Your API costs you resources to run. It should generate revenue proportional to its use.

The API Economy is Here

Every API call consumes compute, bandwidth, and storage. 402x APIs lets you charge fairly for what you provide - no subscription tiers, no usage limits, just pay-per-use.


The Problem with Traditional API Monetization

Subscription Tiers

  • Users pay $50/month but only use 10 calls → Overcharged
  • Users need 1,000 calls but tier maxes at 500 → Forced to upgrade
  • All-or-nothing pricing hurts small users and creators

API Keys & Billing Systems

  • Build entire payment infrastructure from scratch
  • Manage subscriptions, invoicing, and rate limiting
  • Deal with chargebacks and payment processing
  • Month-long development time just for payments

Free with Ads or VC Funding

  • Unsustainable long-term
  • Privacy concerns with ad-supported models
  • Eventually forces aggressive monetization

How 402x APIs Work

With 402x APIs, you charge per request - and get paid instantly.

For Node.js (Express)

javascript
import { x402Middleware } from '402x-api';

app.use('/api/generate', x402Middleware({ 
  price: 0.01 // $0.01 per request
}));

app.post('/api/generate', async (req, res) => {
  const result = await yourAIModel(req.body.prompt);
  res.json({ result });
});

For Python (Flask)

python
from x402_api import require_payment

@app.route('/api/analyze', methods=['POST'])
@require_payment(price=0.05)  # $0.05 per request
def analyze():
    result = your_analysis_function(request.json)
    return jsonify(result)

For Any Language (HTTP Header Check)

javascript
// Client sends payment header
fetch('https://api.example.com/premium', {
  headers: {
    'X-402-Payment': payment_proof
  }
})

Your API validates the payment before processing the request.


Key Features

⚡ Instant Payments

No monthly billing cycles. Get paid the moment someone uses your API.

🎯 Flexible Pricing Models

Per Request

javascript
{ price: 0.01 } // $0.01 per API call

Per Token (AI Models)

javascript
{ 
  pricePerToken: 0.0001, // $0.0001 per output token
  countTokens: (response) => response.tokens 
}

Per Compute Time

javascript
{
  pricePerSecond: 0.001, // $0.001 per second
  trackTime: true
}

Dynamic Pricing

javascript
{
  price: (req) => calculatePrice(req.complexity)
}

🔐 Built-in Rate Limiting

Prevent abuse without complex infrastructure:

javascript
{
  price: 0.01,
  rateLimit: {
    maxRequests: 100,
    windowMs: 60000 // per minute
  }
}

📊 Analytics Dashboard

Track your API business in real-time:

  • Requests per second/minute/hour
  • Revenue per endpoint
  • Top users and geographic distribution
  • Error rates and latency

🌍 Global Access

Anyone, anywhere can use your API:

  • No signup required for users
  • Instant cross-border payments
  • Multi-currency support
  • No payment gateway fees

Use Cases

AI & Machine Learning APIs

Text Generation

javascript
// GPT-style text completion API
app.post('/api/complete', x402Middleware({ 
  pricePerToken: 0.00015 
}), async (req, res) => {
  const completion = await model.complete(req.body.prompt);
  res.json({ 
    text: completion.text,
    tokens: completion.tokenCount 
  });
});

Image Generation Charge per image based on size and complexity:

javascript
{
  price: (req) => {
    const { width, height, steps } = req.body;
    return (width * height * steps) / 1000000;
  }
}

Speech-to-Text Charge per minute of audio processed:

javascript
{
  pricePerMinute: 0.10,
  calculateMinutes: (req) => req.body.audioDuration / 60
}

Data APIs

Real-Time Market Data

javascript
// Stock prices, crypto data, sports scores
app.get('/api/market/:symbol', x402Middleware({ 
  price: 0.001 
}), async (req, res) => {
  const data = await getMarketData(req.params.symbol);
  res.json(data);
});

Weather & Climate Data High-resolution forecasts with per-query pricing.

Social Media Analytics Sentiment analysis, trend detection, audience insights.

Specialized Services

PDF/Document Processing Charge per page or per document:

javascript
{
  price: (req) => req.body.pages * 0.01
}

Image Recognition & OCR Charge per image analyzed:

javascript
{
  price: 0.02,
  countItems: (response) => response.detectedObjects.length
}

Code Execution Sandboxes Charge per execution or per CPU second:

javascript
{
  pricePerSecond: 0.005,
  trackExecutionTime: true
}

Integration Examples

REST API

javascript
// Server
import express from 'express';
import { x402Middleware } from '402x-api';

const app = express();

app.post('/api/translate', 
  x402Middleware({ price: 0.02 }), 
  async (req, res) => {
    const translation = await translate(req.body.text, req.body.targetLang);
    res.json({ translation });
  }
);
javascript
// Client
import { x402Client } from '402x-client';

const response = await x402Client.post('https://api.example.com/translate', {
  text: 'Hello, world!',
  targetLang: 'es'
});

console.log(response.data.translation); // "¡Hola, mundo!"

GraphQL

javascript
import { x402GraphQL } from '402x-api';

const server = new ApolloServer({
  typeDefs,
  resolvers,
  plugins: [
    x402GraphQL({
      pricing: {
        Query: {
          user: 0.001,
          posts: 0.005
        },
        Mutation: {
          createPost: 0.01
        }
      }
    })
  ]
});

WebSocket (Streaming)

javascript
import { x402WebSocket } from '402x-api';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', async (ws, req) => {
  const payment = await x402WebSocket.verify(req);
  
  if (payment.verified) {
    // Stream data with per-message or time-based billing
    setInterval(() => {
      ws.send(JSON.stringify(getRealtimeData()));
    }, 1000);
  }
});

Pricing Strategies

Cost-Plus Pricing

Calculate your costs and add a margin:

javascript
{
  price: (req) => {
    const computeCost = estimateComputeCost(req);
    const margin = 1.5; // 50% markup
    return computeCost * margin;
  }
}

Value-Based Pricing

Charge based on the value you provide:

javascript
// High-accuracy AI model
{ price: 0.10 }

// Fast but less accurate model  
{ price: 0.01 }

Tiered Volume Discounts

Reward heavy users:

javascript
{
  price: (req, user) => {
    if (user.monthlyRequests > 10000) return 0.005;
    if (user.monthlyRequests > 1000) return 0.008;
    return 0.01;
  }
}

Time-Based Pricing

Charge more during peak hours:

javascript
{
  price: () => {
    const hour = new Date().getHours();
    return (hour >= 9 && hour <= 17) ? 0.02 : 0.01;
  }
}

Advanced Features

Request Validation

javascript
x402Middleware({
  price: 0.01,
  validate: (req) => {
    if (!req.body.prompt) throw new Error('Prompt required');
    if (req.body.prompt.length > 1000) throw new Error('Prompt too long');
  }
})

Response Metering

javascript
{
  price: 0.01,
  meterResponse: (res) => {
    // Charge more for larger responses
    return res.data.length / 1000; // $0.01 per KB
  }
}

Webhook Notifications

javascript
{
  price: 0.01,
  onPayment: (payment) => {
    // Notify your system
    analytics.track('api_payment', payment);
  }
}

Security & Best Practices

Important Security Considerations

Always validate payment proofs server-side. Never trust client-side payment claims.

Prevent Replay Attacks

javascript
{
  price: 0.01,
  verifyNonce: true, // Ensures payments can't be reused
  nonceExpiry: 60000 // 1 minute
}

Rate Limiting

javascript
{
  price: 0.01,
  rateLimit: {
    maxRequests: 100,
    windowMs: 60000,
    message: 'Too many requests, please slow down'
  }
}

Error Handling

javascript
app.use('/api/*', (err, req, res, next) => {
  if (err.code === 'PAYMENT_REQUIRED') {
    res.status(402).json({
      error: 'Payment required',
      price: err.price,
      paymentAddress: err.address
    });
  }
});

Comparison: Traditional vs 402x

FeatureTraditional API Business402x APIs
Setup TimeWeeks (build billing system)Minutes (one line of code)
Pricing ModelMonthly tiersPer-request
Payment Delay30+ daysInstant
Platform Fees3-5% + payment processing~1-2% protocol fee
User FrictionAccount signup requiredNo account needed
InternationalComplex, high feesSeamless, low cost
FlexibilityFixed tiersDynamic, granular

Getting Started

1. Install the Library

bash
npm install 402x-api

2. Add Middleware

javascript
import { x402Middleware } from '402x-api';

app.use('/api/premium', x402Middleware({ price: 0.01 }));

3. Start Earning

That's it. Your API is now monetized.


FAQ

What if a request fails after payment?

402x automatically handles refunds for failed requests. You can configure refund policies in your middleware.

Can I offer free tier + paid tier?

Yes! Use conditional middleware based on request parameters or user identity.

How do I handle long-running requests?

Use our streaming payment protocol for continuous billing during execution.

What about API documentation?

We auto-generate OpenAPI/Swagger docs with payment requirements included.

Can users prepay for bulk requests?

Yes, 402x supports credit purchases and automatic deduction per request.


Next Steps

Start monetizingGetting Started Guide
See examplesAPI Demo
Join developersDiscord Community

Explore More Use Cases