This guide outlines the process for integrating with Mempool's API, focusing on initial setup and making a first request. Mempool provides real-time data related to the Bitcoin blockchain and the Lightning Network, offering insights into transaction activity, block propagation, and network health. The public instance of Mempool.space does not require user accounts or API keys for basic usage, simplifying the initial integration process for developers accessing public data. For advanced use cases or custom requirements, self-hosting a Mempool node is an option.
Getting started overview
To begin using the Mempool API, you will primarily interact with its RESTful endpoints. The process does not involve traditional account creation or API key generation for the publicly available service. Instead, you directly access the API using standard HTTP requests. This approach allows for immediate data retrieval concerning the Bitcoin mempool, blocks, transactions, and Lightning Network statistics. Developers building applications that require real-time Bitcoin data can query specific API endpoints to retrieve JSON-formatted responses, which can then be parsed and utilized within their systems. For instance, monitoring unconfirmed transactions or tracking block propagation can be achieved by making simple GET requests to the relevant Mempool API URLs.
The core steps to get started include identifying the API endpoints relevant to your data needs, constructing the HTTP request, and processing the JSON response. Mempool's documentation provides specific endpoint definitions and example call structures to facilitate this. Projects requiring a dedicated, high-performance, or customized data feed may consider deploying their own self-hosted Mempool node, which offers greater control over data access and infrastructure. However, for most read-only data access, the public API is sufficient.
Quick reference: Mempool API access
| Step | What to Do | Where |
|---|---|---|
| 1. Understand Authentication | No API key needed for public endpoints. | Public Mempool instance (e.g., mempool.space) |
| 2. Review API Endpoints | Identify the specific data you need (e.g., latest block, transaction details). | Mempool API Reference |
| 3. Construct Request | Formulate an HTTP GET request to the chosen endpoint. | Your code editor or a command-line tool (e.g., curl) |
| 4. Send Request | Execute the HTTP request. | Via your application, script, or curl |
| 5. Process Response | Parse the JSON data returned by the API. | Within your application logic |
Create an account and get keys
For the primary Mempool.space service, which provides public access to Bitcoin and Lightning Network data, there is no requirement to create an account or obtain API keys. This design choice enables immediate and open access to real-time blockchain information without an authentication layer. Developers can integrate with the Mempool API directly by making HTTP requests to the public endpoints. This contrasts with many commercial APIs that require registration and API key management for access control and usage tracking. For example, payment APIs like Stripe's API require both publishable and secret keys for authenticating requests and managing transactions.
The absence of an account and key system for public access means developers do not need to manage credentials, rotate keys, or handle authentication headers for most use cases. This simplifies the development process for applications that consume public Mempool data. However, if you opt to self-host a Mempool node, you would be responsible for securing access to your instance through network configurations, firewalls, or other authentication mechanisms as per your infrastructure requirements. In a self-hosted environment, you have full control over who can access your Mempool data and how that access is secured, but this responsibility falls entirely on the implementer.
Your first request
To make your first request to the Mempool API, you will use a simple HTTP GET request. A common starting point is to retrieve information about the latest block. The API provides an endpoint specifically for this purpose. You can use command-line tools like curl or integrate this request directly into your application using a programming language's HTTP client library.
Example: Get the latest block height
The endpoint to get the latest block height is /api/blocks/tip/height.
Using curl:
curl https://mempool.space/api/blocks/tip/height
This command will return a plain text integer representing the height of the most recently mined block.
Using JavaScript (Node.js with node-fetch):
const fetch = require('node-fetch');
async function getLatestBlockHeight() {
try {
const response = await fetch('https://mempool.space/api/blocks/tip/height');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const blockHeight = await response.text();
console.log('Latest Block Height:', blockHeight);
} catch (error) {
console.error('Error fetching latest block height:', error);
}
}
getLatestBlockHeight();
Using Python (with requests library):
import requests
def get_latest_block_height():
url = "https://mempool.space/api/blocks/tip/height"
try:
response = requests.get(url)
response.raise_for_status() # Raise an HTTPError for bad responses (4xx or 5xx)
block_height = response.text
print(f"Latest Block Height: {block_height}")
except requests.exceptions.RequestException as e:
print(f"Error fetching latest block height: {e}")
get_latest_block_height()
Example: Get details of the latest block
To get more comprehensive details about the latest block, you can first retrieve its hash and then query for the block's full information. The endpoint for the latest block hash is /api/blocks/tip/hash, and for block details by hash, it's /api/block/{hash}.
Using curl (chained requests):
LATEST_BLOCK_HASH=$(curl -s https://mempool.space/api/blocks/tip/hash)
curl https://mempool.space/api/block/$LATEST_BLOCK_HASH
This command will first fetch the hash of the latest block and then use that hash to retrieve a JSON object containing detailed information about that block, such as its ID, height, timestamp, transaction count, and more. This demonstrates how to combine multiple API calls to get specific data, a common pattern in API integrations.
Common next steps
After successfully making your first request, consider these common next steps to further integrate with Mempool's API:
- Explore other endpoints: Review the Mempool API documentation to understand the full range of available endpoints. These include data for specific transactions, addresses, the mempool itself (e.g., fees, size), and Lightning Network statistics. For example, you might want to fetch details of a specific transaction using its ID, or monitor the current transaction fees in the mempool.
- Integrate into an application: Embed API calls into your web, mobile, or backend applications. This might involve building a dashboard to display real-time Bitcoin network activity, creating an alert system for transaction confirmations, or providing data for a blockchain analytics tool.
- Handle API rate limits: While Mempool's public instance is generally permissive, excessive requests can lead to temporary blocking. Design your application to respect reasonable request intervals. For high-volume needs, consider self-hosting a Mempool node.
- Error handling: Implement robust error handling in your code to manage network issues, malformed requests, or unexpected API responses. The API typically returns standard HTTP status codes (e.g., 404 for not found, 500 for server errors) that should be handled gracefully.
- Data parsing and transformation: Learn to effectively parse the JSON responses and transform the data into usable formats for your application. This often involves selecting specific fields from the JSON object or aggregating data from multiple API calls.
- Stay updated: Monitor the Mempool documentation for any API updates, new features, or changes to existing endpoints.
Troubleshooting the first call
If your first API call to Mempool encounters issues, consider the following troubleshooting steps:
- Verify the URL: Double-check that the endpoint URL is correct and free of typos. Ensure you are using
https://mempool.spaceas the base URL for public access. - Check network connectivity: Confirm that your machine has an active internet connection and can reach external services. A simple test is to ping
mempool.spaceor try accessing the website in a browser. - Review HTTP method: Most Mempool API endpoints are read-only and expect GET requests. Ensure you are not attempting to use POST, PUT, or DELETE unless explicitly stated for a specific endpoint (which is not common for public data retrieval).
- Inspect HTTP response status: If you receive an error, examine the HTTP status code. Common codes include:
400 Bad Request: Often indicates an issue with your request parameters or format.404 Not Found: The requested resource (endpoint or specific data, like a transaction ID) does not exist.429 Too Many Requests: You have exceeded the implicit rate limits. Wait before making further requests.5xx Server Error: Indicates an issue on the Mempool server side. These are usually temporary.
- Parse JSON correctly: If the API returns JSON, ensure your parsing logic is correct. Malformed JSON or incorrect field access can lead to errors in your application. Tools like online JSON validators or browser developer tools can help inspect raw JSON responses.
- Check for firewalls or proxies: Enterprise networks or personal firewalls might block outgoing HTTP requests to certain domains. Ensure that your environment allows access to
mempool.space. - Consult Mempool documentation: The Mempool API reference provides specific details for each endpoint, including expected parameters and response formats. Referencing this documentation can help clarify correct usage.