Tutorials
No Results
Tutorial

Intermediate · 30 minutes

Making HTTP request to Algorand using AlgoExplorer API

The AlgoExplorer API provides a good opportunity for beginners to interact with the Algorand chain without setting up a node. It is RESTFul and can be implemented with any programming language

Requirements

Background

Representation State Transfers (REST) is a software architecture that allows developers to make HTTP(S) requests to a database to access and use data via an application programming interface (API). By using RESTFul APIs, developers can make an HTTP API calls to GET, POST, READ AND DELETE (CRUD) information data in a database or file. Similarly, interacting with Algorand requires a medium for through which developers can perform CRUD actions.

There are many ways of interacting and performing basic CRUD actions on the Algorand chain. To have full access to the Algorand chain, the best option is to set up a node (a server which synchs the Algorand database) to archive and store historical data. However, setting up a node on Algorand is technical and has overhead cost as well. You will need to buy server resources as well as commit human resources to managing it. Thankfully, there are Algorand RESTful APIs, which provide endpoints for perform basic CRUD functions on the blockchain. You should note the following about the capabilities of the RESTFul APIs
• They are mostly good for GET and POST, UPDATE transactions.
• They are cannot be used for wallet management
• You will need one of the Algorand SDKs to sign the transaction - if you are making a post request

Steps

1. include the algorand sdk

<html>
    <head>
        <title>Example HTML/JS Algorand SDK Clients</title>
<script src=scripts/algosdk.min.js></script>

<script>

2. Recover sender address from mnemonic phrase

//recover address 
//put your mnemonic code to replace this
var mnemonic = "wood clump category carpet cabin cement joy cover this hour armor twist write trade term only label later lizard disease boil pelican dish ability this";
account = algosdk.mnemonicToSecretKey(mnemonic);

3. GET PARAMs data

Make a get request to the algoexplorer API to get the params settings for the blockchain. We are processing this on window load. You could put it in a a function and call it at any time.

// get params
window.onload = async () => {

let url = 'https://api.testnet.algoexplorer.io/v2/transactions/params';
    let params = await (await fetch(url)).json();


firstRound = params["last-round"];
lastRound = params["last-round"] + 1000;
genesisID = params["genesis-id"];
genesisHash = params["genesis-hash"];
genesisID = params["genesis-id"];
 params.fee= 1000;

4. Construct params payload.

The params returned from the Algoexplorer API contains extra data which the MmakePaymentTxnWithSuggestedParams function won’t be able to process. Reconstruct the params json payload to match only the accepted parameters below. Also assign other variables as you design - amount, sender’s address, recipient address and note.

 let getParams = {
        "flatFee": true,
        "fee": params.fee,
        "firstRound": firstRound,
        "lastRound": lastRound,
        "genesisID": genesisID,
        "genesisHash": genesisHash,

    };

  amount = 1000000;
 let address = account.addr;
 const receiver = "AXTW46L6EPL4V7XSJAR7X24ATUM4N43BA6HQT3IBG3RS6GZCOBJNR735NI";
let note = algosdk.encodeObj("payment for shirt");

5. Sign the transaction

let txn = algosdk.makePaymentTxnWithSuggestedParams(address, receiver, amount, undefined, note, getParams);        
let signedTxn = txn.signTxn(account.sk);

6. Send transaction to Algorand using POST request

The algoexplorer post request accepts the raw signed transaction in step 5.

var traxUrl = "https://api.testnet.algoexplorer.io/v2/transactions";


    fetch(traxUrl, {
        method: 'POST', // or 'PUT'
        headers: {
          'Content-Type': 'application/x-binary',
        },
        body: signedTxn,
      })
      .then(response => response.json())
      .then(data => {

        document.getElementById("examples").value = JSON.stringify(data);

      })
      .catch((error) => {
        console.error('Error:', error);
      });


    }
    </script>

7. Access transaction ID and other data

There are two ways to access the transaction ID. The first option is in step 5 above. The signed transaction will return the transaction ID

let txId = txn.txID().toString();

The second option is after the transaction is successfully sent to the blockchain using the AlgoExplorer API. It returns the transaction ID after a success operation. In step 6, the data object in the response contains the transaction ID. AS Shown below.

.then(response => response.json())
      .then(data => {



      })

8 Close HTML

</script>

<style>
    .log {
        font-size: 18px;
        width:50%;
        padding:1%;
        height: 40%;
    }
</style>

</head>
<body>


</html>

9. Complete code

<html>
    <head>
        <title>Example HTML/JS Algorand SDK Clients</title>
<script src="scripts/algosdk.min.js"></script>

<script>

//recover address 
//put your mnemonic phrase to replace this
var mnemonic = "wood clump category carpet cabin cement joy cover this hour armor twist write trade term only label later lizard disease boil pelican dish ability this";
let account = algosdk.mnemonicToSecretKey(mnemonic);

window.onload = async () => {

    let url = 'https://api.testnet.algoexplorer.io/v2/transactions/params';
        let params= await (await fetch(url)).json();
        firstRound = params["last-round"];
        lastRound = params["last-round"] + 1000;
        genesisID = params["genesis-id"];
        genesisHash = params["genesis-hash"];
       params.fee= 1000;

    let getParams = {
        "flatFee": true,
        "fee": params.fee,
        "firstRound": firstRound,
        "lastRound": lastRound,
        "genesisID": genesisID,
        "genesisHash": genesisHash,

    };

amount = 1000000;
address = account.addr;

const receiver = "AXTW46L6EPL4V7XSJAR7X24ATUM4N43BA6HQT3IBG3RS6GZCOBJNR735NI";
let note = algosdk.encodeObj("payment for shirt");

let txn = algosdk.makePaymentTxnWithSuggestedParams(address, receiver, amount, undefined, note, getParams);        
let signedTxn = txn.signTxn(account.sk);



//console.log("Signed transaction with txID: %s", txId);


    var traxUrl = "https://api.testnet.algoexplorer.io/v2/transactions";


    fetch(traxUrl, {
        method: 'POST', // or 'PUT'
        headers: {
          'Content-Type': 'application/x-binary',
        },
        body: signedTxn,
      })
      .then(response => response.json())
      .then(data => {
        document.getElementById("examples").value = JSON.stringify(data);

      })
      .catch((error) => {
        console.error('Error:', error);
      });


    }




</script>

<style>
    .log {
        font-size: 18px;
        width:50%;
        padding:1%;
        height: 40%;
    }
</style>

</head>
<body>
    <p>Example output</p>
    <textarea id="examples" class="log"></textarea>


    </body>

</html>

PureStake

AlgoExplorer

v2 api

December 17, 2020