Interact with the API

This guides describes how to interact with a blockchain network powered by the Lisk SDK.

To interact with a blockchain, it is necessary to communicate with the API of a blockchain node.

As an alternative to the Lisk SDK API, you can use and customize Lisk Service and its API to provide a more extensive API for your interfaces.

By default, it is only allowed to make API requests to a node from the localhost.

To make API requests from remote, use a node with a public API, or deploy your own node and whitelist your IP to make API requests.

Common interactions

Some examples for most common interactions are listed here.

For JavaScript developers, it is most convenient to use the @liskhq/lisk-api-client.

First perform the installation with npm:

In the terminal
npm i @liskhq/lisk-api-client

Then require it as dependency and create the API client:

In a javascript file
const { APIClient } = require('@liskhq/lisk-api-client');

const API_BASEURL = "http://localhost:4000"; (1)
const api = new APIClient([API_BASEURL]);
1 Replace http://localhost:4000 with the address of the node where you wish to send the API request.

It is also possible to do the API requests directly from the command line with programs like Curl or Lisk Commander.

In addition, it is of course also possible to write an API client based on other languages apart from JavaScript and TypeScript.

Get transactions

Syntax
api.transactions.get(options)

Where options can be any of the params described in the API specification: GET /transactions

Get transaction by ID
const { APIClient } = require('@liskhq/lisk-api-client');

const API_BASEURL = "http://localhost:4000";
const api = new APIClient([API_BASEURL]);

api.transactions.get({ id: '222675625422353767' })
    .then(res => {
        console.log(res.data);
    })
Get transaction by recipient ID
const { APIClient } = require('@liskhq/lisk-api-client');

const API_BASEURL = "http://localhost:4000";
const api = new APIClient([API_BASEURL]);

api.transactions.get({ recipientId: '123L' })
    .then(res => {
        console.log(res.data);
    });

Get blocks

Syntax
api.blocks.get(options)

Where options can be any of the params described in the API specification: GET /blocks

Get block by height
const { APIClient } = require('@liskhq/lisk-api-client');

const API_BASEURL = "http://localhost:4000";
const api = new APIClient([API_BASEURL]);

api.blocks.get({ height: '123456' })
    .then(res => {
        console.log(res.data);
    });

Get accounts

Syntax
await api.accounts.get(options)

Where options can be any of the params described in the API specification: GET /accounts

Get all accounts
const { APIClient } = require('@liskhq/lisk-api-client');

const API_BASEURL = "http://localhost:4000";
const api = new APIClient([API_BASEURL]);

let offset = 0;
let accounts = [];
const accountsArray = [];

async function getAccounts() {
    do {
        const retrievedAccounts = await api.accounts.get({ limit: 100, offset });
        accounts = retrievedAccounts.data;
        accountsArray.push(...accounts);

        if (accounts.length === 100) {
            offset += 100;
        }
    } while (accounts.length === 100);

    return accountsArray;
}

getAccounts().then(accountsArray => console.log(accountsArray));

Create new accounts

First it is necessary to generate a mnemonic passphrase, which will be the 12 word passphrase that belongs to the new account.

This passphrase is then used to generate a public/private key pair that is now also associated to the account.

Last but not least an address is generated, this is also referred to as the "account ID".

Whilst all these properties now belong to this specific account, it is important to be aware of which information is public, and which information needs to be kept private.

Private properties
  • passphrase: The 12 word mnemonic passphrase, ensures all is kept private and safe! However, if this passphrase is lost, then access to the funds of this account is lost as well.

  • privateKey: The cryptographic representation of the human-readable passphrase.

Public properties
  • address: The public address of this account. Example: 12345L

  • publicKey: The cryptographic representation of the human-readable address.

Create new account credentials
const cryptography = require('@liskhq/lisk-cryptography');
const { Mnemonic } = require('@liskhq/lisk-passphrase');

const createCredentials = () => {
    const passphrase = Mnemonic.generateMnemonic();
    const keys = cryptography.getPrivateAndPublicKeyFromPassphrase(
        passphrase
    );
    const credentials = {
        address: cryptography.getAddressFromPublicKey(keys.publicKey),
        passphrase: passphrase,
        publicKey: keys.publicKey,
        privateKey: keys.privateKey
    };
    return credentials;
};

const credentials = createCredentials();

console.log(credentials);

You may have noticed that for creating a new account, there was no API request sent to the network. Therefore there is no record yet regarding this account on the blockchain.

For this account to become part of the blockchain, it is necessary to transfer at least 1 token to the newly created account.

This balance transfer will create a new record for the account on the blockchain.

To ensure that no other user can generate the same address from a different passphrase (which could occur), it is necessary to initialize the new account, by sending an outgoing transaction.

This initialization will bind your public key to the address, and ensure the account cannot be hijacked at any point in the future.

Example: Initializing an account by sending a transfer transaction
const { APIClient } = require('@liskhq/lisk-api-client');
const { TransferTransaction, utils } = require('@liskhq/lisk-transactions');
const {getNetworkIdentifier} = require('@liskhq/lisk-cryptography');
// Generate the network identifier for Devnet
const networkIdentifier = getNetworkIdentifier(
    "19074b69c97e6f6b86969bb62d4f15b888898b499777bda56a3a2ee642a7f20a",
    "Lisk",
);
const API_BASEURL = "http://localhost:4000";
const api = new APIClient([API_BASEURL]);

let tx = new TransferTransaction({
    asset: {
        amount: '1',
        recipientId: '12345678L',
    },
    fee: utils.convertLSKToBeddows('0.1'),
    nonce: '0',
});
// Replace the passphrase with the passphrase of the newly created account
tx.sign(networkIdentifier,'creek own stem final gate scrub live shallow stage host concert they');

api.transactions.broadcast(tx.toJSON()).then(res => {
    console.log("++++++++++++++++ API Response +++++++++++++++++");
    console.log(res.data);
    console.log("++++++++++++++++ Transaction Payload +++++++++++++++++");
    console.log(tx.stringify());
    console.log("++++++++++++++++ End Script +++++++++++++++++");
}).catch(err => {
    console.log(JSON.stringify(err.errors, null, 2));
});

To conveniently initialize an account, transfer the funds back to the original account. Just replace the value of the recipientId with the account address.

In this case, only the transaction fee needs to be paid to initialize the account.

If the API responds with a success message in res.data, the transaction was broadcasted successfully.

Send transactions

To find out how to send a transaction to the network, please refer to the Broadcast a transaction guide.

Further interactions

For a complete reference of all available requests and options, please see the Lisk SDK API specification.

Click here to see the complete reference of the Lisk API client.