If you have ever shipped an API, you know the awkward part is never the code. It is the billing. Card processors want monthly minimums, subscription tiers force you to guess usage in advance, and API keys turn into a customer-support burden the moment someone's card expires. Paying per request with Bitcoin's Lightning Network removes most of that friction, and it does so in a way that works for human developers and autonomous software agents alike.
This primer explains what a paid API over Lightning actually is, how the underlying pieces (BOLT11 invoices, HTTP 402, the L402 protocol) fit together, how to price and build a machine-payable endpoint, and how to test the whole loop with real sats without risking real money.
What is a paid API over Lightning?
A paid API over Lightning is an HTTP API that charges for access in bitcoin, settled instantly over the Lightning Network, usually on a per-request basis. Instead of registering an account, entering a credit card, and receiving an API key, the client pays a Lightning invoice (often just a few satoshis) and presents proof of payment with the request. The server verifies the proof and serves the response.
The core idea: payment replaces signup. The invoice is the price tag, the payment preimage is the receipt, and the receipt is the credential. No accounts, no card networks, no chargebacks, no geographic gatekeeping.
A satoshi (sat) is one hundred-millionth of a bitcoin, which makes it a natural unit for API pricing. Charging a fraction of a cent per call is impossible on card rails, where fixed fees dominate small transactions. On Lightning it is the normal case.
Why Lightning fits API payments
A few properties of the Lightning Network line up unusually well with how APIs are actually consumed:
True micropayments
Lightning payments routinely settle for amounts under one cent, with routing fees measured in fractions of a sat. That makes per-call pricing economical at any scale. You can charge 10 sats for a single data lookup and the economics still work, for you and for the caller.
Instant, final settlement
A successful Lightning payment settles in seconds and cannot be reversed. There is no chargeback window, no pending state, no reconciliation lag. For an API operator this means you can serve the response the moment you see the payment preimage, with zero settlement risk.
No accounts, no onboarding
Because the payment itself authenticates the request, a brand-new client can call your API on its first attempt. There is no registration form, no email verification, no billing address. This matters enormously for software agents, which cannot fill in a signup form or pass a card-on-file check, but can hold a Lightning wallet and pay an invoice programmatically.
Global by default
Lightning does not care where the caller lives, what currency their bank uses, or whether a card network operates in their country. A paid Lightning endpoint is available to anyone with sats, anywhere.
The building blocks
You only need to understand a handful of primitives to build or consume a Lightning-paid API.
BOLT11 invoices
A BOLT11 invoice is the standard Lightning payment request: a bech32-encoded string that contains the amount, a payment hash, a description, an expiry time, and the destination node. The server (or its wallet provider) generates an invoice for the price of the API call; the client pays it with any Lightning wallet or node.
Two fields matter most for API work:
- Payment hash. The invoice commits to the SHA-256 hash of a secret called the preimage.
- Preimage. Revealed to the payer only when the payment succeeds. Knowing the preimage is cryptographic proof that the invoice was paid.
That hash-and-preimage pair is what turns a payment into a verifiable API credential.
HTTP 402 and the L402 protocol
HTTP has had a status code reserved for this since the 1990s: 402 Payment Required. It sat unused for decades because the web had no native payment rail. Lightning gives it one.
L402 (formerly called LSAT) is the emerging convention for using 402 with Lightning. The flow uses two standard HTTP headers:
- The client requests a protected resource with no credentials.
- The server responds
402 Payment Requiredwith aWWW-Authenticate: L402header containing a macaroon (a bearer token with caveats baked in) and a BOLT11 invoice. - The client pays the invoice and receives the preimage.
- The client retries the request with
Authorization: L402 <macaroon>:<preimage>. - The server checks that the preimage hashes to the payment hash bound inside the macaroon, verifies the macaroon's caveats (expiry, scope, rate limits), and serves the response.
The macaroon part is what makes L402 more than a one-shot paywall. Caveats let you encode "valid for 1,000 requests", "expires after 30 days", or "read-only scope" directly into the token, so a single payment can buy a metered bundle of access.
Keysend and LNURL
Two adjacent tools worth knowing:
- Keysend lets a client push a spontaneous payment to a node's public key without an invoice. It is handy for tips and streaming payments, but it is a poor fit for APIs because the server never issued a price and gets no clean payment-to-request binding.
- LNURL-pay wraps invoice generation behind a static URL or QR code. It is common in wallet-to-service interactions and can complement an API for things like account top-ups.
For request-level API payments, the invoice-plus-preimage pattern (with or without the full L402 machinery) is the workhorse.
How an L402 flow works, step by step
Here is the complete loop from the perspective of each side.
Server side:
- Receive a request without an
Authorizationheader. - Ask your Lightning node (LND, Core Lightning, or a hosted provider) for an invoice at the endpoint's price, e.g. 50 sats.
- Mint a macaroon that binds the invoice's payment hash and any caveats you want (expiry, request quota, allowed paths).
- Return
402with the macaroon and invoice in theWWW-Authenticateheader. - On the retry, recompute SHA-256 of the presented preimage, confirm it matches the payment hash in the macaroon, validate caveats, then serve the response.
Client side:
- Make the request, get a
402, parse the macaroon and invoice from the header. - Sanity-check the invoice amount against your configured budget cap. Never blind-pay.
- Pay the invoice through your wallet or node API and capture the preimage from the payment result.
- Retry with
Authorization: L402 <macaroon>:<preimage>. - Cache the credential. If the macaroon allows multiple requests, reuse it until it expires instead of paying again.
Total added latency for a first call is typically one Lightning payment, a second or two. Subsequent calls with a cached credential add nothing.
Pricing a machine-payable endpoint
Sats-denominated pricing gives you options card billing never could.
Per-call pricing
The simplest model: every request costs a flat number of sats. It works best when each call has similar cost to serve. Keep the price well above your node's expected routing-fee noise but low enough that callers do not bother batching. Single-digit to low-hundreds of sats per call is a typical range for data lookups and small compute tasks.
Metered bundles via macaroon caveats
Per-call payment means a Lightning round trip on every request. For chatty clients, sell bundles instead: one 5,000-sat payment mints a macaroon valid for 1,000 calls or 30 days, whichever comes first. The caveat system handles enforcement without a user database.
Free tiers without API keys
You can still offer a free tier. Serve a limited number of unauthenticated requests per IP or per time window, then start answering 402. The paywall becomes a rate-limit escape hatch rather than a wall, which is a friendly on-ramp for developers evaluating your service.
Dynamic pricing
Because invoices are generated per request, the price can move with load, payload size, or upstream cost. An endpoint that proxies an expensive computation can quote a bigger invoice for a bigger job. The client always sees the price before paying, so dynamic pricing stays honest by construction.
Consuming paid APIs: the client checklist
Paying for APIs programmatically is easy to get working and easy to get wrong. A solid client implementation needs:
- A funded wallet or node. Anything that exposes a pay-invoice call and returns the preimage works: LND's gRPC/REST API, Core Lightning, or a hosted wallet API.
- A hard budget cap. Set a per-call maximum and a daily spend ceiling in code. Refuse any invoice above the cap. This is the single most important safety rail, especially for autonomous agents.
- Credential caching. Store macaroon-preimage pairs and reuse them for their full validity. Re-paying for access you already bought is the most common waste in naive clients.
- Idempotent retries. If a payment succeeds but the HTTP retry fails, you still hold the preimage. Retry the request with the same credential rather than paying again.
- Expiry handling. BOLT11 invoices expire, often within minutes. If you pay slowly (for example, after a human approval step), be ready to request a fresh quote.
Agents as customers
The most interesting consumers of Lightning-paid APIs are not humans at all. An autonomous agent with a wallet can discover an endpoint, read the 402 challenge, pay, and consume the result with no human in the loop. That unlocks machine-to-machine commerce that card rails structurally cannot serve: no agent can pass a KYC check or own a credit card, but any agent can hold sats.
For API operators this is a genuinely new customer class. Agents are price-sensitive, latency-sensitive, and tireless. If your endpoint is reliable and honestly priced, agent traffic compounds, because working integrations get reused and shared.
If you are building on this pattern, the Lightning Faucet builder tools are a practical place to experiment with Lightning-native payment flows against a live service.
Common pitfalls
A few failure modes show up in almost every first implementation:
- Trusting the invoice instead of the preimage. "An invoice exists" proves nothing. Only a preimage that hashes to the bound payment hash proves payment. Verify server-side, every time.
- No replay protection. A preimage proves the invoice was paid once, not that this is the first request using it. Bind credentials to quotas via macaroon caveats or server-side counters.
- Ignoring inbound liquidity. Your node can only receive payments up to its inbound capacity. A popular paid API drains inbound liquidity continuously; monitor it and rebalance or open channels before payments start failing.
- Invoice expiry mismatches. If your invoices expire in 60 seconds but your clients include slow approval steps, you will generate support pain. Match expiry to realistic client behavior.
- No refund story. Lightning payments are final. If your server takes payment and then errors, the right fix is credential reuse (let the client retry free), not ad-hoc refunds.
Getting your first sats to test with
The chicken-and-egg problem for new Lightning developers is simple: you cannot test paying an invoice without sats. You do not need to buy bitcoin on an exchange to get started.
Lightning Faucet exists for exactly this gap. You can earn small amounts of bitcoin through faucet claims and earn surfaces, withdraw over Lightning, and use those sats to exercise a real pay-per-request loop end to end: wallet funding, invoice payment, preimage capture, credential reuse.
Real sats moving through real products is also the fastest way to build intuition for sat-denominated economics. Watching how prices, payouts, and balances behave in prediction markets or at a multiplayer poker table teaches you more about micropayment UX than any spec document, because every stake, fee, and payout is the same unit your API will charge in.
FAQ
What does it cost to call a Lightning-paid API?
Whatever the invoice says, plus a routing fee that is usually a fraction of a sat to a few sats. Prices are set per endpoint by the operator; small data calls are commonly priced in single-digit to low-hundreds of sats. The client always sees the exact amount in the invoice before paying.
What is the difference between L402 and just sending an invoice?
A bare invoice flow proves payment for one request. L402 adds a macaroon, a bearer token with built-in caveats, so one payment can buy a scoped, metered, expiring bundle of access. If you need anything beyond strict pay-per-call, L402's token layer saves you from building your own session system.
Do my API users need their own Lightning node?
No. Any wallet or wallet API that can pay a BOLT11 invoice and expose the payment preimage works. Hosted wallet APIs and self-custodial wallets with developer interfaces both qualify. Running a node gives more control but is not a requirement for consuming paid APIs.
How do refunds work if my API fails after payment?
Lightning payments are final, so the practical answer is credential reuse rather than refunds: treat the paid credential as valid until the client receives a successful response, and make retries free. Operators who want true refunds must collect a return invoice from the client and pay it manually, which is workable but rarely worth the complexity for sat-scale prices.
Is a few sats per call really worth charging?
Yes, for three reasons. First, micro-prices deter abuse and scraping far better than IP rate limits, because every request has a cost. Second, sats compound: high-volume machine traffic at small per-call prices is real revenue. Third, the payment doubles as authentication, so you save the cost of running account, key, and billing infrastructure.
How do I prevent one payment from being replayed across many requests?
Bind every credential to a quota. With L402, encode the limit as a macaroon caveat (number of requests, expiry time, allowed scope) and track usage server-side keyed by payment hash. A preimage should never function as an unlimited password; it is proof of one specific payment, and your caveats define what that payment bought.
The short version
Lightning turns HTTP 402 from a historical curiosity into a working business model. Invoices price the request, preimages prove the payment, macaroons scope the access, and the whole loop settles in seconds with no accounts and no card networks. Start small: pick one endpoint, price it in sats, implement the 402 challenge, and test the full loop with faucet-earned sats before real traffic arrives. The rails are ready whenever you are.