Using the API

Learn how to integrate Flux programmatically.

Gateway Endpoint

All API requests go through the Flux gateway:

https://useflux.site/api/v2/gateway/{apiId}/{path}

Replace {apiId} with your API ID and {path} with your endpoint path.

AI Agent Discovery

Flux provides two endpoints for AI agents to discover and integrate APIs automatically:

OpenAPI 3.0 Specification

GET /api/v2/apis/{apiId}/openapi

Returns a complete OpenAPI 3.0 specification with:

  • All endpoints and parameters

  • Request/response schemas

  • Pricing information (x-flux-pricing)

  • Example prompts (x-flux-example-prompts)

  • Security schemes (FluxPayment + FluxSignature)

Example Response:

{
  "openapi": "3.0.0",
  "info": {
    "title": "Your API",
    "version": "1.0.0",
    "x-flux-api-id": "abc123"
  },
  "paths": {
    "/users/:id": {
      "get": {
        "summary": "Get User",
        "x-flux-pricing": {
          "amount": "0.001",
          "token": "ETH",
          "chain": "base"
        }
      }
    }
  }
}

AI Agent Info

GET /api/v2/apis/{apiId}/agent-info

Returns human-readable metadata for AI agents:

  • API capabilities and descriptions

  • Integration guide with code examples

  • Payment flow instructions

  • Supported chains and tokens

Example Response:

{
  "api": {
    "id": "abc123",
    "name": "GitHub API",
    "description": "Access GitHub data"
  },
  "capabilities": [{
    "name": "Get Repos",
    "endpoint": {
      "method": "GET",
      "path": "/users/:username/repos"
    },
    "pricing": {
      "amount": "0.001",
      "token": "ETH",
      "chain": "base"
    },
    "examples": [
      "Get repositories for user hadley",
      "Show me repos for username octocat"
    ]
  }],
  "howToUse": {
    "step1": "Send payment transaction...",
    "exampleCode": { "javascript": "..." }
  }
}

Authentication

Every request requires two headers:

  1. Payment Transaction Hash - Proof of payment

  2. Wallet Signature - Proof of ownership

Required Headers

x-flux-payment-tx: 0x... (transaction hash)
x-flux-signature: 0x... (wallet signature)
Content-Type: application/json

Payment Flow

1. Send Payment

Send ETH/tokens to the endpoint's recipient address:

const tx = await wallet.sendTransaction({
  to: recipientAddress,
  value: ethers.utils.parseEther(price)
});

const txHash = tx.hash;

2. Sign Message

Sign a message proving you own the wallet:

const message = `Flux API Authorization

Transaction: ${txHash}
Service: ${endpointId}

By signing this message, you authorize Flux to use this payment for the specified API service.`;

const signature = await wallet.signMessage(message);

3. Make Request

Send your API request with the headers:

const response = await fetch(
  `https://useflux.site/api/v2/gateway/${apiId}/posts/1`,
  {
    method: 'POST',
    headers: {
      'x-flux-payment-tx': txHash,
      'x-flux-signature': signature,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({ key: 'value' })
  }
);

const data = await response.json();

Complete Example (ETH Payment)

import { ethers } from 'ethers';

async function callFluxAPI() {
  // 1. Connect wallet
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  const signer = provider.getSigner();
  
  // 2. Send payment
  const tx = await signer.sendTransaction({
    to: '0x...', // recipient address
    value: ethers.utils.parseEther('0.001')
  });
  
  await tx.wait(); // Wait for confirmation
  
  // 3. Sign message
  const message = `Flux API Authorization\n\nTransaction: ${tx.hash}\nService: endpoint123\n\nBy signing this message, you authorize Flux to use this payment for the specified API service.`;
  const signature = await signer.signMessage(message);
  
  // 4. Call API
  const response = await fetch(
    'https://useflux.site/api/v2/gateway/abc123/posts/1',
    {
      method: 'GET',
      headers: {
        'x-flux-payment-tx': tx.hash,
        'x-flux-signature': signature
      }
    }
  );
  
  return await response.json();
}

USDC Payments

Flux supports USDC and other ERC20 tokens. USDC uses 6 decimals (not 18 like ETH).

USDC Contract Addresses

const USDC_CONTRACTS = {
  base: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",        // Base Mainnet
  polygon: "0x3c499c542cEF5E3811e1192ce70d8cC03d5c3359",     // Polygon Mainnet
  ethereum: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",    // Ethereum Mainnet
  "base-sepolia": "0x036CbD53842c5426634e7929541eC2318f3dCF7e", // Base Sepolia Testnet
  amoy: "0x41E94Eb019C0762f9Bfcf9Fb1E58725BfB0e7582",        // Polygon Amoy Testnet
  sepolia: "0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238",     // Ethereum Sepolia
};

USDC Payment Example (Thirdweb)

import { getContract, prepareContractCall, sendTransaction } from 'thirdweb';
import { base } from 'thirdweb/chains';

async function payWithUSDC(price, recipientAddress) {
  // USDC uses 6 decimals (not 18!)
  const amountInUnits = BigInt(Math.floor(price * 1_000_000));
  
  // Get USDC contract
  const usdcContract = getContract({
    client: thirdwebClient,
    chain: base,
    address: USDC_CONTRACTS.base,
  });
  
  // Prepare transfer (no approval needed for transfer())
  const transaction = prepareContractCall({
    contract: usdcContract,
    method: "function transfer(address to, uint256 amount) returns (bool)",
    params: [recipientAddress, amountInUnits],
  });
  
  // Send transaction
  const result = await sendTransaction(transaction);
  return result.transactionHash;
}

USDC Payment Example (ethers.js)

import { ethers } from 'ethers';

async function payWithUSDC(price, recipientAddress) {
  const provider = new ethers.providers.Web3Provider(window.ethereum);
  const signer = provider.getSigner();
  
  // USDC contract ABI (just the transfer function)
  const usdcAbi = [
    "function transfer(address to, uint256 amount) returns (bool)"
  ];
  
  // Connect to USDC contract
  const usdcContract = new ethers.Contract(
    USDC_CONTRACTS.base,
    usdcAbi,
    signer
  );
  
  // USDC uses 6 decimals
  const amountInUnits = ethers.utils.parseUnits(price.toString(), 6);
  
  // Send USDC
  const tx = await usdcContract.transfer(recipientAddress, amountInUnits);
  await tx.wait();
  
  return tx.hash;
}

Important: USDC uses transfer() which transfers directly from your wallet. No approval needed!

Error Handling

try {
  const data = await callFluxAPI();
  console.log(data);
} catch (error) {
  if (error.status === 402) {
    console.error('Payment required or already used');
  } else if (error.status === 403) {
    console.error('Invalid signature');
  } else {
    console.error('API error:', error);
  }
}

Rate Limiting

Flux doesn't impose rate limits - you pay per request. However, the underlying API may have its own limits.

Best Practices

  1. Cache transaction hashes - Don't reuse the same payment

  2. Handle pending transactions - Wait for confirmation before calling

  3. Store signatures securely - Don't expose them publicly

  4. Monitor gas prices - Use appropriate gas for timely confirmation

Next Steps

Last updated