Build Your Own Bitcoin API using Node.js and Bitcoin Core
In this tutorial we will build an API using Node.js and Express that retrieves data from Bitcoin Core. This tutorial is meant to be a starter for anyone looking to create Bitcoin applications with Javascript. You can use this API as a bitcoin backend to build web applications such as a block explorer or wallet.
Bitcoin Core is the primary software implementation of the Bitcoin protocol. It is basically a software program that allows you to mine, store, and transact in bitcoin. It also automatically validates other people’s transactions and lets you query all sorts of blockchain data.
Bitcoin has a RPC (remote procedure protocol) API with dozens of commands which can be found here. These commands include everything you need to interact with the Bitcoin client. It is possible to use the RPC API to create addresses and send transactions, however in this tutorial we will only be using commands which query data.
Before we can use this API, you will need to run Bitcoin Core. If you don’t already have Bitcoin Core installed on your computer, you can download it here. The blockchain size is over 225gb and always increasing, so make sure you have enough hard drive space and internet bandwidth to run the software (see Costs and Warnings). Bitcoin can take several days to sync to the current blockchain, so it is a good idea to setup the node in advance in order to test out the API.
Additionally you will need to install Node.js which can be found here.
The full code for this tutorial and API can be found on Github. If you clone the repository, make sure to create a .env
file and add your RPC login info (explained below)
Project Setup
Once you have bitcoin installed and synced, create a folder for your application and navigate to it.
mkdir bitcoin-api
cd bitcoin-api
Then initialize a new node application by entering
npm init -y
This will create a package.json file, which we can specify a start script and other details for our application.
Add the line "server": "nodemon server.js"
into the scripts object. You can replace the default "test"
command, which we won't be using.
Your package.json file should look similar to:
Next, lets build out our project structure and files. In the project directory add a server.js
file for our server and .env
file to store our bitcoin login. Next, add a routes
folder with api.js
file for our endpoints. The following commands, input separately, will do this in the command line:
touch server.js
touch .env
mkdir routes && cd routes
touch api.js && cd ..
Next we can install the additional javascript packages we’ll be using. Packages (or dependencies) are 3rd party javascript code we will utilize in our application. Install the needed dependencies with the following two commands
Dependencies:
npm install body-parser dotenv express request
Dev Dependencies:
npm install --save-dev nodemon
body-parser
- converts our HTTP responses to JSON to easily consume datadotenv
- reads our bitcoin login info from the .env fileexpress
- our routing framework, lets us specify method endpointsrequest
- allows us to send HTTP requests to the bitcoin clientnodemon
- restarts the server when changes are detected
Setting up a server
We will need a server that hosts our API endpoints in the browser. To do this, add the following code to server.js
In the first 3 lines we are setting our dependencies and endpoint location to be javascript variables.
Next we initialize express (our routing framework) to the app
variable. With app.use()
we can setup our body parser (formats data response) and declare where our API endpoints will live.
After that we will set a port variable to be 4444 or whatever digits you choose. This will be the location in the browser where you can view the returned blockchain data. At the end of this file, we initialize our server on the port specified and log a success message.
This script will run once when we start our server, then stay running until the process is terminated. Nodemon
will allow us to save changes to our application without having the restart the server. Before we start the server, let’s also setup our Bitcoin client login and API.
Configuring Login Information
In order to use the Bitcoin RPC API, a username and password are required in the Bitcoin Core configuration file. This will allow us to connect with the node remotely using HTTP. You can add these values to the bitcoin.conf
file by selecting
Settings -> Options... -> Open Configuration File
inside of Bitcoin Core, which will open a text file. Add the following lines to this file:
rpcuser=bitcoinuser
rpcpassword=bitcoinpassword
then save in the text editor, and restart Bitcoin Core.
Note: This login info will allow anyone with access to your node to run RPC commands including sending transactions. Be alert when setting up APIs connected to wallets containing Bitcoin, and don’t post this information anywhere on the web. For this example, I will use a dummy login, though you should choose your own username and password.
Now, back in our project’s .env
file, we can add the same information to our API. The naming convention will be slightly different, however the login will be the same as in bitcoin.conf
Lastly and optionally, if you plan to store this code remotely, create a .gitignore
file in the root project folder. Add .env
to this file, so that you don't accidentally commit your node's RPC login.
Bitcoin RPC Routes
In our server.js file we specified that express should look for our endpoints in /routes/api.js
. These endpoints will hold the various bitcoin RPC methods that we can use to interact with the software.
To setup this file, add the following code to api.js:
Here we are again initializing an express router, request module, and environmental variables. The headers variable will be the same in each request so we can include it at the top. The line that begins with router.get("/test", ...)
is our test route, which we will soon be able to view.
Start the application by entering the command:
npm run server
If the server has started correctly, in your console you should see
Server running on port 4444
Now open your browser and navigate to:
localhost:4444/api/test
you should get the message “backend works” as a response.
We will be setting up 12 more routes in this application, each which correspond to a Bitcoin RPC command. These methods can be used in the Bitcoin Core console (found under Window -> Console
in Bitcoin Core), as well as in our Node.js application.
Basic Routes
The first 8 routes we will use do not require an input argument. They include:
getblockcount
getbestblockhash
getconnectioncount
getdifficulty
getblockchaininfo
getmininginfo
getpeerinfo
getrawmempool
These 8 methods will return to us some details about the current state of the blockchain, mempool, and our node’s network connections. Each method will be accessed in the same way, and return an object with our requested data.
To setup our first route, replace the comment
// ... routes will go here
with the following code:
Here we are telling the express router to listen for when a user hits the endpoint /api/getblockcount
. The dataString
and options
variables include input parameters such as the name of the method we are calling and the url of our bitcoin node (including our login). If we are running both the server and bitcoin node, in the browser at localhost:4444/api/getblockcount
we should see the response
{
result: 588608,
error: null,
id: "curltext"
}
In this response, the value 588608
is the current number of blocks in the blockchain. Each response will have an object containing the requested data in the result
property.
To set up the other 7 methods
getbestblockhash, getconnectioncount, getdifficulty, getblockchaininfo, getmininginfo, getpeerinfo, getrawmempool
simply reuse the getblockcount
code above for each method. In each endpoint there will be 2 instances of the method name, one to specify the endpoint address such as /getblockcount
, and the other as a value in the dataString
variable such as "method": "getblockcount"
. Replace both of these variables for each of the 7 methods above and you will have an API with 8 endpoints to Bitcoin RPC commands!
(Alternatively you can just copy all 12 endpoints from here)
Take some time to explore the various responses from these basic commands. getblockchaininfo
, getmininginfo
, and getpeerinfo
are loaded with useful information that you can use to build interesting applications.
Single Parameter Methods
In this tutorial we will also be querying blockchain data using 4 methods which require 1 input argument each. These methods are listed below with a space between their name and the name of the input parameter.
getblockhash index
getblock hash
getrawtransaction id
decoderawtransaction hex
These 4 methods allow us to lookup blocks and transactions.
Each block on the Bitcoin blockchain has a unique index
and hash
value. The block's hash
is required to get data about the block. This hash can be retrieved with the getblockhash
method, passing in an index
of the specified block. Once the block's hash is returned, we can find the block info with the getblock
command, passing in the block's hash
.
To include this functionality in our API we can add the following methods for block retrieval
For getblock
For getblockhash
Note I included both endpoints here as the getblockhash
method accepts a number instead of a string.
With each of these methods, we will also need to pass in an input parameter. For example, to find a blockhash with the getblockhash
command, visit:
localhost:4444/api/getblockhash/520482
in your browser. The block index here is passed in by adding a /
after the method endpoint and before the input parameter.
You can find this block’s transaction data by using the returned block hash as an argument to a getblock
call.
Now, with our API we are capable of finding the transactions in the most recent block by stringing together the getblockcount
, getblockhash
, and getblock
commands together. We can also find the transactions in any block that we have the index
or hash
for.
Transaction Methods
For our transaction methods we will need a Bitcoin node that is indexing transactions in order to access the entire blockchain. To index the transactions on your node, you will need to add the following line to the bitcoin.conf
file
txindex=1
save this file, then restart Bitcoin Core. Indexing the entire blockchain will take some time as well as additional storage on your harddrive. It is recommended to index the blockchain overnight or while you are away from your computer, as it can take several to many hours.
Each transaction in the bitcoin blockchain has a unique id. This id can be used as an argument in the getrawtransaction
method to return the hex encoded transaction data. The decoderawtransaction
method can be used with this hex data as an argument to reveal information about that transaction.
Add the following transaction endpoints to your api.js
file
For getrawtransaction
For decoderawtransaction
Every Bitcoin RPC command can be added as an endpoint in this API to make fully functional Bitcoin applications.
With these 12 methods we have setup a communication with our Bitcoin node that will allow us to build all sorts of applications.
Next Steps (React)
There are a multitude of libraries and frameworks you can use to build fully functional web applications on top of Bitcoin. As a starting point, these are some basic steps to build a React application which is able to talk with our API.
To setup a new React application, enter the following command in the root of your project folder
npx create-react-app frontend
Next, change directories into your frontend
folder and add the axios
package for API requests by entering
yarn add axios
Additionally, you will need to add a proxy to your frontend
package.json file for your API requests.
"proxy": "http://localhost:4444",
From here we simply need to setup our React application to store the API data in state. To test out the getblockchaininfo
, getmininginfo
, and getpeerinfo
methods update your App.js
file to the following:
Let’s see our basic full stack application in action by starting our React frontend with the command:
yarn start
Summary
With our API fully setup we can use Bitcoin RPC commands as long as our Bitcoin node and Node.js server are running. With these commands accessible, you can easily build a block explorer, fee calculator, node dashboard, testnet wallet, or any number of other applications. Using your own node is an excellent sandbox for testing out various ideas and learning more about how to interact with the Bitcoin blockchain.