Development

Bitcoin APIs & Development

Build on Bitcoin. From querying blockchain data to accepting Lightning payments, this guide covers the APIs, libraries, and tools developers need to integrate Bitcoin into applications.

16 min read

Bitcoin's open protocol and transparent blockchain make it one of the most developer-friendly financial systems ever created. Whether you want to build a payment integration, analyze on-chain data, track Bitcoin prices, create a wallet application, or build on the Lightning Network, a rich ecosystem of APIs and libraries is available. This guide maps the landscape and helps you choose the right tools for your project.

Bitcoin API Categories

Bitcoin APIs fall into four main categories, each serving different development needs.

Full-Node APIs

Bitcoin Core JSON-RPC, Electrum Server. Run your own node for maximum privacy and reliability. No rate limits, no third-party dependency. Best for production applications handling significant volume.

Service APIs

Mempool.space, BlockCypher, Blockchain.com. Query blockchain data without running a node. Good for prototyping, small applications, and read-heavy workloads. Subject to rate limits and third-party availability.

Payment APIs

BTCPay Greenfield API, Strike API, OpenNode API. Accept Bitcoin payments in your application. Handle invoicing, payment detection, webhooks, and settlement. Fees range from 0% (BTCPay) to 1% (OpenNode).

Data & Analytics APIs

Glassnode, CoinGecko, Blockchair. On-chain metrics, market data, and blockchain analytics. Used for dashboards, research tools, and trading applications. Free tiers available for most providers.

Getting Started: Mempool.space API

Mempool.space is the recommended starting point for most developers. It provides free, open-source access to Bitcoin blockchain data with no API key required.

Example: Fetch Current Fee Estimates

// JavaScript / Node.js
const response = await fetch(
  'https://mempool.space/api/v1/fees/recommended'
);
const fees = await response.json();
// { fastestFee: 12, halfHourFee: 8, hourFee: 4, economyFee: 2 }
console.log(`Next block fee: ${fees.fastestFee} sat/vB`);

Example: Query Address Balance

# Python
import requests

address = 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh'
url = f'https://mempool.space/api/address/{address}'
data = requests.get(url).json()

funded = data['chain_stats']['funded_txo_sum']
spent = data['chain_stats']['spent_txo_sum']
balance_sats = funded - spent
print(f'Balance: {balance_sats} sats ({balance_sats/1e8} BTC)')

Bitcoin Core JSON-RPC

For production applications, running your own Bitcoin Core node provides the most reliable and private data source. The JSON-RPC API exposes over 100 commands for blockchain queries, transaction management, and wallet operations.

Example: Get Block Info via Bitcoin Core RPC

# Using curl with Bitcoin Core RPC
curl --user myuser:mypassword \
  --data-binary '{"jsonrpc":"1.0","method":"getblockcount"}' \
  -H 'Content-Type: text/plain;' \
  http://127.0.0.1:8332/

# Response: {"result":890123,"error":null,"id":null}

CoinGecko Price API

CoinGecko provides free cryptocurrency market data without requiring an API key for basic usage. It is the most popular choice for price data, historical charts, and market metrics.

Example: Fetch Bitcoin Price in Multiple Currencies

// JavaScript - CoinGecko API (no key required)
const response = await fetch(
  'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd,eur,gbp'
);
const data = await response.json();
// { bitcoin: { usd: 87500, eur: 80200, gbp: 69800 } }
console.log(`BTC/USD: $${data.bitcoin.usd.toLocaleString()}`);

Blockchain.info API

One of the oldest Bitcoin data APIs, Blockchain.info provides simple REST endpoints for querying transactions, blocks, and exchange rates. No API key required for basic queries.

Example: Query Transaction Details

# Python - Blockchain.info API
import requests

# Get latest Bitcoin exchange rates
rates = requests.get('https://blockchain.info/ticker').json()
usd_price = rates['USD']['last']
print(f'BTC/USD: ${usd_price:,.2f}')

# Get address transaction count
addr = 'bc1qxy2kgdygjrsqtzq2n0yrf2493p83kkfjhx0wlh'
info = requests.get(f'https://blockchain.info/rawaddr/{addr}?limit=0').json()
print(f'Total transactions: {info["n_tx"]}')

Free vs Paid API Comparison

ProviderFree TierRate Limit (Free)Paid FromBest For
Mempool.spaceFull APIFair useSelf-hostBlockchain data, fees
CoinGeckoBasic data10-50/min$129/moPrice data, charts
BlockCypher200 req/hr200/hr$75/moWebhooks, tx monitoring
Blockchain.infoBasic queries10K/8hrN/ASimple lookups
GlassnodeLimited metrics200/day$29/moOn-chain analytics
Bitcoin Core RPCUnlimitedNoneSelf-hostFull node, production

Building a Simple Price Tracker

Here is a complete example combining multiple APIs to build a simple Bitcoin price tracker with fee awareness. This pattern is common in dashboards, portfolio apps, and notification services.

Example: Combined Price and Fee Tracker (TypeScript)

interface BitcoinData {
  price: { usd: number; eur: number };
  fees: { fastest: number; halfHour: number; hour: number };
  blockHeight: number;
}

async function getBitcoinData(): Promise<BitcoinData> {
  const [priceRes, feeRes, blockRes] = await Promise.all([
    fetch('https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd,eur'),
    fetch('https://mempool.space/api/v1/fees/recommended'),
    fetch('https://mempool.space/api/blocks/tip/height'),
  ]);

  const price = await priceRes.json();
  const fees = await feeRes.json();
  const blockHeight = await blockRes.json();

  return {
    price: { usd: price.bitcoin.usd, eur: price.bitcoin.eur },
    fees: { fastest: fees.fastestFee, halfHour: fees.halfHourFee, hour: fees.hourFee },
    blockHeight,
  };
}

// Usage
const data = await getBitcoinData();
console.log(`BTC: $${data.price.usd.toLocaleString()}`);
console.log(`Next-block fee: ${data.fees.fastest} sat/vB`);
console.log(`Block height: ${data.blockHeight.toLocaleString()}`);

Lightning Network Development

The Lightning Network enables instant, low-cost Bitcoin payments and is essential for applications requiring sub-second settlement. The main implementations are LND (Go), Core Lightning (C), and Eclair (Scala), each with comprehensive APIs. For applications that need Lightning without running infrastructure, hosted solutions like Strike API, Alby, and Voltage provide managed Lightning access.

WebSocket APIs for Real-Time Data

REST APIs are suitable for periodic polling, but real-time applications benefit from WebSocket connections that push updates as they happen. Mempool.space provides a WebSocket API for live mempool and block data, while exchanges like Kraken and Coinbase offer WebSocket feeds for real-time price data.

Example: Mempool.space WebSocket (Real-Time Blocks)

// Browser or Node.js with ws package
const ws = new WebSocket('wss://mempool.space/api/v1/ws');

ws.onopen = () => {
  // Subscribe to new block notifications
  ws.send(JSON.stringify({ action: 'want', data: ['blocks'] }));
};

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.block) {
    console.log(`New block: #${data.block.height}`);
    console.log(`Transactions: ${data.block.tx_count}`);
    console.log(`Size: ${(data.block.size / 1e6).toFixed(2)} MB`);
  }
};

Example: Kraken WebSocket (Real-Time Price Feed)

const ws = new WebSocket('wss://ws.kraken.com');

ws.onopen = () => {
  ws.send(JSON.stringify({
    event: 'subscribe',
    pair: ['XBT/USD'],
    subscription: { name: 'ticker' },
  }));
};

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (Array.isArray(msg) && msg[2] === 'ticker') {
    const ticker = msg[1];
    console.log(`BTC/USD: $${parseFloat(ticker.c[0]).toLocaleString()}`);
  }
};

When using WebSocket connections in production, implement automatic reconnection with exponential backoff. Connections will drop periodically due to server maintenance, network instability, or idle timeouts. Keep-alive pings (typically every 30 seconds) help detect stale connections early.

Security Best Practices for Bitcoin API Development

Building on Bitcoin requires careful attention to security. API keys, private keys, and transaction data are high-value targets. Follow these practices to protect your application and your users.

Never Expose API Keys Client-Side

Keep API keys on the server. Use environment variables (never hardcode) and proxy requests through your backend. Client-side JavaScript is visible to anyone viewing page source.

Validate All Webhook Signatures

Payment processors sign webhook payloads with HMAC. Always verify these signatures server-side before processing payment events. An unverified webhook endpoint is an open door for attackers to mark fake payments as confirmed.

Verify Payment Amounts Server-Side

Never trust client-side payment confirmation. Always check the blockchain (via your node or a trusted API) to verify that the correct amount was sent to the correct address with sufficient confirmations before releasing goods or services.

Use Rate Limiting and Caching

Cache API responses to avoid hitting rate limits and reduce latency. Price data does not need to be fetched on every request. A 30-60 second cache for price data and a 5-minute cache for blockchain data is sufficient for most applications.

Use Testnet for Development

Always develop and test against Bitcoin testnet or signet before deploying to mainnet. Testnet coins have no value, so mistakes during development cost nothing. Most APIs including Mempool.space, BlockCypher, and Bitcoin Core support testnet endpoints. Switch to mainnet only after thorough testing of transaction construction, fee estimation, and payment verification logic.

Implement Proper Error Handling

Bitcoin API calls can fail due to network issues, rate limiting, or service outages. Always implement retry logic with exponential backoff, graceful degradation when APIs are unavailable, and fallback providers for critical operations. Never let an unhandled API failure result in incorrect payment status or lost transaction data.

Payment Integration Quickstart

For merchants and businesses wanting to accept Bitcoin payments, the fastest path is Strike's API (simple REST endpoints, Lightning support, 0.3% fee) or BTCPay Server's Greenfield API (self-hosted, zero fees, full control). Both support webhooks for payment notifications, invoice generation, and automatic conversion to fiat currency.

Essential Libraries by Language

LanguageLibraryUse Case
JavaScriptbitcoinjs-libTransaction construction, signing
Pythonpython-bitcoinlibScripting, prototyping, RPC interaction
Rustrust-bitcoin + LDKHigh-performance, Lightning integration
Gobtcsuite / LNDFull-node, Lightning daemon

Developer Getting Started Checklist

1

Start with Mempool.space API for blockchain queries. No key required, generous rate limits, and excellent documentation.

2

Add CoinGecko for price data. Free tier supports most development and small production applications.

3

Choose a Bitcoin library for your language: bitcoinjs-lib (JS/TS), python-bitcoinlib (Python), or rust-bitcoin (Rust).

4

For payment integration, evaluate BTCPay Server vs Strike based on your custody and fee requirements.

5

When your application grows, run your own Bitcoin Core node for maximum reliability, privacy, and unlimited API access.

The Bottom Line

Bitcoin's API ecosystem is mature, well-documented, and accessible to developers at every skill level. Start with Mempool.space for read operations, add Strike or BTCPay for payments, and use the fee estimation tools to optimize transaction costs. Graduate to running your own node as your application grows. The open-source nature of Bitcoin means you are never locked into a single provider, and the community is among the most helpful in all of software development.

Frequently Asked Questions

What is the best Bitcoin API for beginners?
Mempool.space is the best starting point for most developers. It provides a free, open-source REST API for querying Bitcoin blockchain data (transactions, blocks, addresses, fees) without requiring registration or API keys. The API is well-documented, rate limits are generous, and it runs on Bitcoin's public infrastructure. For payment integration, Strike's API offers the simplest path to accepting Bitcoin payments with Lightning Network support.
Do I need to run a Bitcoin node to use Bitcoin APIs?
No. Service APIs like Mempool.space, BlockCypher, and Blockchain.com provide access to Bitcoin blockchain data without running your own node. However, running your own node (Bitcoin Core) gives you the highest level of privacy, reliability, and independence. If you are building a production application that handles significant transaction volume, running your own node with its JSON-RPC API is recommended to avoid third-party dependency and rate limits.
How do I get real-time Bitcoin price data via API?
CoinGecko (free, no API key for basic usage, 10-50 calls/minute), CoinMarketCap (free tier available, API key required), Kraken (WebSocket API for real-time price feeds), and Binance (REST + WebSocket, extensive market data). For historical price data, CoinGecko and Messari provide comprehensive datasets. Most applications should cache price data and update at reasonable intervals rather than making a request for every page load.
What is the Bitcoin Core JSON-RPC API?
Bitcoin Core, the reference implementation of the Bitcoin protocol, exposes a JSON-RPC API that allows you to interact directly with a Bitcoin node. Through this API you can create and send transactions, query blockchain data, manage wallets, and monitor the mempool. It is the most authoritative data source possible because you are querying your own validated copy of the blockchain rather than trusting a third party. Access requires running Bitcoin Core and configuring RPC authentication.
How do I accept Bitcoin payments programmatically?
The recommended approach depends on your requirements. For self-hosted zero-fee payments, use BTCPay Server's Greenfield API. For simple integration with Lightning support, use Strike's API (0.3% fee) or OpenNode's API (1% fee). For custodial solutions, Coinbase Commerce API handles payment flow, conversion, and settlement. Each provides webhooks to notify your application when payments are received and confirmed. BTCPay is preferred for businesses that want full control; Strike is preferred for simplicity.
What are the rate limits for popular Bitcoin APIs?
Rate limits vary by provider. Mempool.space: no published limits but requests fair use. BlockCypher: 200 requests/hour (free), 200,000/hour (paid). Blockchain.com: 10,000 requests/8 hours. CoinGecko: 10-50 calls/minute (free), higher on paid tiers. Bitcoin Core JSON-RPC: no rate limits (self-hosted). For production applications, implement caching, use WebSocket connections where available, and consider running your own node to eliminate external rate limit dependency entirely.
How do I build a Bitcoin wallet application?
Building a Bitcoin wallet requires handling key generation, address derivation, transaction construction, signing, and broadcasting. Libraries like bitcoinjs-lib (JavaScript), python-bitcoinlib (Python), and BTCLib (Go) provide the cryptographic primitives. For key management, use BIP-39 (mnemonic seed phrases), BIP-32 (hierarchical deterministic wallets), and BIP-84 (native SegWit addresses). Security is paramount: private keys must never be transmitted over the network or stored in plaintext. Most developers should use established wallet libraries rather than implementing cryptography from scratch.
What is the Lightning Network API ecosystem?
The Lightning Network has several major implementations, each with its own API. LND (Lightning Network Daemon) exposes a gRPC and REST API for managing channels, sending/receiving payments, and querying network state. Core Lightning (formerly c-lightning) provides a JSON-RPC interface. Eclair offers a simpler REST API. For applications that need Lightning without running a node, services like Strike, Alby, and Voltage provide hosted Lightning APIs. The LNURL and Lightning Address protocols standardize payment flows across implementations.
How do I query Bitcoin on-chain data for analytics?
For on-chain analytics, Glassnode provides comprehensive metrics (SOPR, NVT, exchange flows) via REST API with free and paid tiers. Blockchain.com offers raw blockchain data through its API. Mempool.space provides transaction, block, and fee data. For custom analysis, Blockchair provides a SQL-like query language for blockchain data. Chainalysis and Elliptic offer compliance-focused APIs for transaction tracing. For maximum flexibility, query your own Bitcoin Core node using the getblock, getrawtransaction, and getblockstats RPC commands.
What programming languages are best for Bitcoin development?
Bitcoin Core is written in C++, but you can interact with Bitcoin in any language. The most popular choices are Python (python-bitcoinlib, broad ecosystem), JavaScript/TypeScript (bitcoinjs-lib, web integration), Rust (rust-bitcoin, growing in the Bitcoin ecosystem), and Go (btcd, btcsuite). For Lightning development, Go (LND) and Rust (LDK) are dominant. For web applications that interact with Bitcoin APIs, TypeScript/JavaScript is the most practical choice due to its web-native tooling.
How do I handle Bitcoin webhooks and payment notifications?
Most payment processors (BTCPay, Strike, OpenNode) support webhooks that POST JSON to your server when payment events occur (payment received, confirmed, expired). Implement an endpoint that validates the webhook signature, processes the event, and returns a 200 status code. For self-hosted solutions, Bitcoin Core's walletnotify and blocknotify options can trigger scripts when transactions are detected. Always verify payment amounts and confirmations server-side rather than trusting client-side data.

Build with Bitcoin

Learn about Bitcoin scaling solutions and how merchants are using these APIs in production.