Getting Started with the Polkadot API
By: David Acevedo
Tags: Polkadot Network, Polkadot, Blockchain

What You Will Learn

In this tutorial, you will learn how to:

Setup a local Polkadot node running the blockchain software on your computer.

Connect to that node (and the blockchain) via a UI.

Establish a connection to the node via the Polkadot API.

Prerequisites

Before we get started, we just need to do a few things first.

Install Docker

Docker is an open platform for developing, shipping, and running applications. If you are unfamiliar with Docker, that is okay. We will not go into too much detail on what it is. However installing it is important, as this will be how we run a local instance of a Polkadot blockchain.

Navigate to the Get Docker page, and follow the installation instructions for your specific operating system.

Once you have finished all instructions, you can verify the installation by opening up your command line, and running the following to make sure the version of Docker is printed to the screen.

> docker -v

Docker version 20.10.11, build dea9396

Note: If the above command doesn’t print the version to the console, you may need to open up the Docker application on your computer, and then run the command again.

Install Node and npm

Both Node and npm are used to connect to the Polkadot API via code. The recommended way to install them is to install nvm (Node Version Manager).

To install nvm, first run the following command. This downloads and runs the installation script for nvm

Next, run the command below to load nvm

> export NVM_DIR="$([ -z "${XDG_CONFIG_HOME-}" ] && printf %s "${HOME}/.nvm" || printf %s "${XDG_CONFIG_HOME}/nvm")"

[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"

The commands are a bit complex and outside the scope of this tutorial. While we won’t dissect each one, you can read more about nvm here.

Lastly, verify that the installation was successful by running

> command -v nvm

nvm

If the installation was successful, you should see nvm output to the console. You can also run node -v and npm -v to verify that they were installed as well. Both commands should output a version number.

Creating a Local Polkadot Node

Once you have Docker installed, you can run the following command to create a local node on your computer.

docker run -p 9944:9944 parity/polkadot:v0.8.24 --name "MyPolkadotNode" --rpc-external --ws-external --alice --dev

The above command may seem a bit confusing, so lets dissect it.

docker run This tells docker to initialize what are known as “containers” with some piece of software that will be defined later in the command.

This tells docker to initialize what are known as “containers” with some piece of software that will be defined later in the command. -p 9944:9944 Here you are telling Docker that any request that comes in on port 9944 of your computer should be forwarded to port 9944 of the docker container.

Here you are telling Docker that any request that comes in on port 9944 of your computer should be forwarded to port 9944 of the docker container. parity/polkadot:v0.8.24 This is the name and the version of the software that exists on DockerHub. Think of it as a public repository that contains the Polkadot blockchain software.

This is the name and the version of the software that exists on DockerHub. Think of it as a public repository that contains the Polkadot blockchain software. --name "MyPolkadotNode" This is giving our node a name. The name can be anything you’d like but should be descriptive to know what it is, hence MyPolkadotNode.

This is giving our node a name. The name can be anything you’d like but should be descriptive to know what it is, hence MyPolkadotNode. --rpc-external --ws-external This enables both RPC and WebSockets on the node. This isn’t important right now, but will be later when developing against the API.

This enables both RPC and WebSockets on the node. This isn’t important right now, but will be later when developing against the API. --alice This initializes our instance with a few accounts with ALOT of money. Unfortunately because it is a testnet, that money is worthless

This initializes our instance with a few accounts with ALOT of money. Unfortunately because it is a testnet, that money is worthless --dev This informs the polkadot instance that we will be running this in a dev mode.

Once the command is run, you should a bunch of information printed to the console that looks like this.

Congratulations! You are now running a Polkadot blockchain node on your computer!

It is worth noting that this creates a new blockchain with no information on it, that does not sync up with the Polkadot network. It is simply a local copy.

Connecting to the Local Node

Now that we have a node actively creating blocks and contributing to the blockchain, we want to be able to connect to it and view the information.

Connecting via Polkadot.js.org

Polkadot.js.org allows us to via the details of the Polkadot network as well as other substrate-based networks.

To see the details of our local node on Polkadot.js, we do the following:

Navigate to the Polkadot explorer. Click on the icon in the top left to reveal the sidebar menu. In the sidebar menu, navigate to the Development section, select Local Node, and then click on the Switch button on top.

Remember, we told docker to run the application on port 9944 of of local computer with -p 9944:9944.

This will connect the Polkadot UI to the local node currently running on our computer. It should look something like this

Take a look around. Even though blocks are still being created under the recent blocks section, there are no transactions within these blocks.

If you navigate to the Accounts section, you will see several accounts with money in it! Play around with these accounts by transferring money to and from them to get a feel for the UI and what goes on.

Optional: Running Polkadot.js locally

Because Polkadot is an open-source platform, we can view the code behind all of their applications online.

The Polkadot.js code base is located on Github, which allows us to run the website locally and connect to our Polkadot node the same way we did above.

In a new command window, run the following:

> git clone https://github.com/polkadot-js/apps polkadot-js

> cd polkadot-js

> yarn

> yarn run start

Note: If you do not have yarn installed on your computer, you can do so here. You can verify if you do have yarn installed by running this command with a successful output:

> yarn --version

1.22.17

As a result, you should see some output to the console that the project is now running on localhost:3000.

Once you navigate to that link, you’ll notice that the UI is the same as the one on Polkadot.js.org. As a results, we can use the same steps defined up to connect to our local node.

Connecting to the Polkadot API

Let’s recap everything up to this point. First, we setup a Polkadot node on our computer that runs the blockchain software and is actively creating blocks.

We then inspected the details of our network by connecting to our node via the Polkadot.js UI.

In this section, we are going to complete the final step by connecting to our local node via the Polkadot API and pull some piece of information about the network! While we are only querying our local blockchain, in theory, this same code could be used to connect to Polkadot’s mainnet.

Creating the Node.js project

The first thing we want to do is create the project that will house our code. In the prerequisites, we installed Node and npm via Node Version Manager (nvm).

First, we want to create the directory where our project will live. To do so, run

> mkdir MyPolkadotProject

> cd MyPolkadotProject

mkdir makes a directory (or folder) in the current location of your command window. In this case, we call that directory MyPolkadotProject.

cd then says to “Change Directory” to a specific directory, which we specify to be the directory we just created.

Next, to create a project in the directory that we just made, run:

> npm init --yes

Once again, let’s dissect this command

npm init This creates the project by adding a package.json file to the current directory you are in. If you are unfamiliar with Node, just know that the package.json file is the centerpiece of any project. It defines your dependencies, the file to execute when running your project, and other helpful information.

This creates the project by adding a package.json file to the current directory you are in. If you are unfamiliar with Node, just know that the package.json file is the centerpiece of any project. It defines your dependencies, the file to execute when running your project, and other helpful information. --yes Without this command, Node would ask some questions regarding the new project (name, description, etc). With this flag, we skip those questions and have Node create the project with default values.

Installing the Polkadot API package

With the project created, we now want to install the package that will give us access to the Polkadot API.

In the same location as the package.json file that was created in the previous section (the MyPolkadotProject directory), run

> npm i @polkadot/api --save

This installs the @polkadot/api package to the current project for us to use later. To verify that it has been added to the project, you can open the package.json file in your IDE and see it in the dependencies object.

Creating Our Main File

If you inspect the package.json again, you’ll see that there is a section that says

"main": "index.js"

What this means is that when we run our project via the node command, it will run whatever is in this file. However, we haven’t created the file yet. To do so, in the same directory, run

> touch index.js

This will create our index.js file. If you run node index.js you’ll notice that nothing happened. This is because we haven’t defined any code in the file. Let’s do that now.

Connecting To The API

Using your favorite IDE, open the index.js file and add the following code.

const { ApiPromise, WsProvider } = require(' @polkadot/api '); async function main () {

// Initialise the provider to connect to the local node

const provider = new WsProvider('ws://127.0.0.1:9944'); // Create the API and wait until ready

const api = await ApiPromise.create({ provider }); // Prints the results

console.log(`Our client is connected: ${api.isConnected}`);

} main().catch(console.error).finally(() => process.exit());

Let’s go through this line by line:

const { ApiPromise, WsProvider } = require('@polkadot/api'); This imports the @polkadot/api package that we installed earlier via npm.

This imports the package that we installed earlier via npm. const provider = new WsProvider('ws://127.0.0.1:9944'); This creates a WebSocket provider that listens on port 9944 (remember we initialized it with the -p 9944:9944 flag when setting up Docker). Polkadot currently only supports WebSockets as a provider because of its bi-directional nature.

This creates a WebSocket provider that listens on port 9944 (remember we initialized it with the flag when setting up Docker). Polkadot currently only supports WebSockets as a provider because of its bi-directional nature. const api = await ApiPromise.create({ provider }); We attach the WebSocket provider, which then returns an API instance. We will use the api property for every subsequent api call we make. We use the await keyword to hold up the function until an API instance is returned.

To run the code, we use the following command

> node index.js

If everything is successful, we should the console.log statement printed with a value of true .

Our client is connected: true

Success! You have connected to your local node and can use the Polkadot API to perform actions on the blockchain!

Next Steps

Upon completion, you now have a local node running the Polkadot blockchain on your computer, as well as having connected to that node via the Polkadot.js UI and Polkadot API in code.

Polkadot’s API documentation can be found here with more information on the key concepts behind how the API operates.

You can also find examples of how to use it to get certain information here.

Lastly, have a look around on the Polkadot.js website that is pointed to your local node. You can transfer money back and forth, stake Polkadot, and submit proposals without worrying about losing real world money.