How to create Blockchain API in Javascript

In this tutorial, we’re gonna build an API that allows us to interact with our Blockchain.

Previous Post: How to build a Blockchain in Javascript

Next Post: How to build a Decentralized Blockchain Network in Javascript

Overview

We will create a server using Express.js, then build three endpoints that will allow us to interact with our Blockchain (in previous article):

– GET /blockchain allows us to fetch our entire Blockchain so that we can look at the data inside.
– POST /transaction to create a new transaction.
– GET /mine for mining new Block using the Proof of Work method.

Practice

Setup Environment

This was our project folder before:

build-blockchain-javascript-project-folder-tree

Now, under src folder, create new javascript file named api.js.

Install Express.js

Run command: npm install express.

Inside app.js, import and initialize Express.js:

Install Body Parser

This is Node.js body parsing middleware that can parse incoming request bodies before handlers, available under the req.body property.

To install it, run command: npm install body-parser.

Inside app.js, add the code below:

bodyParser.json() returns middleware that only parses json.

Install nodemon

During development of a NodeJs based application, nodemon will watch the files in the directory, and if any files change, it will automatically restart our node application.

To install it, run command: npm install nodemon.
Then add start script to package.json file:

After setup environment, our project folder structure will be like:

build-blockchain-api-javascript-structure

Build Blockchain API

Add code for endpoints in app.js:

Run and Check results

– Run the API with command: npm start.
– Open browser with url: http://localhost:3000/blockchain.

build-blockchain-api-javascript-run

http://localhost:3000/mine:

build-blockchain-api-javascript-run-mine

http://localhost:3000/blockchain again:

build-blockchain-api-javascript-run-blockchain-1

– POST a transaction with Advanced REST client:

build-blockchain-api-javascript-run-transaction

http://localhost:3000/blockchain:

build-blockchain-api-javascript-run-blockchain-2

http://localhost:3000/mine:

build-blockchain-api-javascript-run-mine-1

– POST other 2 transactions, then http://localhost:3000/blockchain:

build-blockchain-api-javascript-run-transaction-1

http://localhost:3000/mine again:

build-blockchain-api-javascript-run-mine-2

http://localhost:3000/blockchain:

build-blockchain-api-javascript-run-blockchain-final

This is all Blocks inside our Blockchain:

Source Code

Blockchain-API

By grokonez | May 31, 2018.



Related Posts


Got Something To Say:

Your email address will not be published. Required fields are marked *

*