AgnicPay

X402 Fetch

Transparent payment proxy for X402-enabled endpoints

X402 Fetch

The X402 Fetch API is a transparent proxy that automatically handles HTTP 402 (Payment Required) responses. This is the recommended way to interact with paid APIs.

How It Works

sequenceDiagram
    participant App as Your App
    participant Agnic as AgnicPay
    participant API as Paid API
 
    App->>Agnic: POST /api/x402/fetch?url=...
    Agnic->>API: Forward request
    API-->>Agnic: 402 Payment Required
    Agnic->>Agnic: Sign payment
    Agnic->>API: Retry with payment header
    API-->>Agnic: 200 OK + Response
    Agnic-->>App: Response + payment info
  1. Your app sends a request to AgnicPay's fetch endpoint
  2. AgnicPay forwards the request to the target URL
  3. If the API returns 402, AgnicPay automatically signs and attaches payment
  4. The response is returned to your app with payment metadata

Endpoint

POST /api/x402/fetch?url={target_url}

Query Parameters

ParameterTypeRequiredDescription
urlstringYesThe target URL to fetch
methodstringNoHTTP method (default: GET)
maxValueintegerNoMaximum payment in atomic units (USDC has 6 decimals)
timeoutintegerNoRequest timeout in ms (default: 30000)

Request Headers

Pass any headers to forward to the target API:

curl -X POST "https://api.agnic.ai/api/x402/fetch?url=https://api.example.com/data" \
  -H "X-Agnic-Token: agnic_tok_YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -H "X-Custom-Header: value"

Request Body

Any JSON body is forwarded to the target URL:

curl -X POST "https://api.agnic.ai/api/x402/fetch?url=https://api.example.com/generate&method=POST" \
  -H "X-Agnic-Token: agnic_tok_YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "Write a poem about AI",
    "max_tokens": 500
  }'

Response Headers

AgnicPay adds metadata headers to the response:

HeaderDescription
X-Agnic-Paid"true" if payment was made, "false" otherwise
X-Agnic-AmountAmount paid in USD (e.g., "0.25")
X-Agnic-NetworkBlockchain network used (e.g., "base-sepolia")
X-Agnic-SchemePayment scheme: "exact" or "upto"

Examples

Basic GET Request

curl -X POST "https://api.agnic.ai/api/x402/fetch?url=https://api.example.com/data" \
  -H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"

POST with JSON Body

curl -X POST "https://api.agnic.ai/api/x402/fetch?url=https://api.example.com/generate&method=POST" \
  -H "X-Agnic-Token: agnic_tok_YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Hello world"}'

With Maximum Payment Limit

# Max payment of $0.50 (500000 atomic units)
curl -X POST "https://api.agnic.ai/api/x402/fetch?url=https://api.example.com/data&maxValue=500000" \
  -H "X-Agnic-Token: agnic_tok_YOUR_TOKEN"

Python Example

import requests
 
response = requests.post(
    "https://api.agnic.ai/api/x402/fetch",
    params={
        "url": "https://api.example.com/paid-endpoint",
        "method": "POST"
    },
    headers={
        "X-Agnic-Token": "agnic_tok_YOUR_TOKEN",
        "Content-Type": "application/json"
    },
    json={
        "prompt": "Generate something"
    }
)
 
# Check if payment was made
if response.headers.get("X-Agnic-Paid") == "true":
    print(f"Paid ${response.headers.get('X-Agnic-Amount')}")
 
print(response.json())

JavaScript Example

const response = await fetch(
  'https://api.agnic.ai/api/x402/fetch?url=https://api.example.com/data&method=POST',
  {
    method: 'POST',
    headers: {
      'X-Agnic-Token': 'agnic_tok_YOUR_TOKEN',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ prompt: 'Hello' })
  }
);
 
// Check payment info
const paid = response.headers.get('X-Agnic-Paid');
const amount = response.headers.get('X-Agnic-Amount');
 
if (paid === 'true') {
  console.log(`Paid $${amount}`);
}
 
const data = await response.json();

Error Handling

Insufficient Balance

{
  "error": "insufficient_balance",
  "error_description": "Not enough USDC balance to complete payment"
}

Spending Limit Exceeded

{
  "error": "spending_limit_exceeded",
  "error_description": "Payment of $0.50 exceeds per-transaction limit of $0.25"
}

Payment Exceeds maxValue

{
  "error": "payment_exceeds_max",
  "error_description": "Required payment exceeds maxValue parameter"
}

Best Practices

  1. Set maxValue - Always set a maximum payment to prevent unexpected charges
  2. Check response headers - Verify payment was made when expected
  3. Handle errors gracefully - Implement retry logic for transient failures
  4. Monitor spending - Use the transactions API to track costs

On this page