My Image
CoursesQuizzesProblemsContestsSmartBooks
Contest!

No results found

LOGINREGISTER
My ProgressCoursesQuizzesProblemsContestsSmartbooks
Published on 8 Jul 2021
Call Any API in smart contract Part-II
Get any external data in smart contract with chanlink
img
Ganesh Deshpande
0
Like
527

In previous smartbook we have discussed how to get uint from the API we want , we have also discussed about how to select oracle addresses and jobids as per our requirement.

In this smartbook we will try to get string from our API.

Complete contract

pragma solidity ^0.6.0;

import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";

contract GetAPI is ChainlinkClient {
    using Chainlink for Chainlink.Request;
  
    bytes32 public volume;
    
    address private oracle;
    bytes32 private jobId;
    uint256 private fee;
    
    constructor() public {
        setPublicChainlinkToken();
        oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
        jobId = "50fc4215f89443d185b061e5d7af9490";
        fee = 0.1 * 10 ** 18; // (Varies by network and job)
    }
    
    function requestVolumeData() public returns (bytes32 requestId) 
    {
        Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
        
        request.add("get", "https://reqres.in/api/products/3");
      
        request.add("path", "data.name");
        
        
        return sendChainlinkRequestTo(oracle, request, fee);
    }
    

    function fulfill(bytes32 _requestId, bytes32 _volume) public recordChainlinkFulfillment(_requestId)
    {
        volume = _volume;
    }
    
    function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
        uint8 i = 0;
        while(i < 32 && _bytes32[i] != 0) {
            i++;
        }
        bytes memory bytesArray = new bytes(i);
        for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
            bytesArray[i] = _bytes32[i];
        }
        return string(bytesArray);
    }
    
 
}

 

Explanation

Step 1:

pragma solidity ^0.6.0;
    
    import "@chainlink/contracts/src/v0.6/ChainlinkClient.sol";

define solidity version

import chainlink client contract 

 

Step 2:

contract GetAPI is ChainlinkClient {
    using Chainlink for Chainlink.Request;
  
    bytes32 public volume;
    
    address private oracle;
    bytes32 private jobId;
    uint256 private fee;
    
    constructor() public {
        setPublicChainlinkToken();
        oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
        jobId = "50fc4215f89443d185b061e5d7af9490";
        fee = 0.1 * 10 ** 18; // (Varies by network and job)
    }
  • Define Smart contract name
  • define some variable like show above
  • define constructor

Note that now volume variable is not a integer but its bytes32.

Also our jobId is changed, because now our job is to fetch string and not integer.

 

Step 3:

function requestVolumeData() public returns (bytes32 requestId) 
    {
        Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
        
        request.add("get", "https://reqres.in/api/products/3");
      
        request.add("path", "data.name");
        
        
        return sendChainlinkRequestTo(oracle, request, fee);
    }
    

    function fulfill(bytes32 _requestId, bytes32 _volume) public recordChainlinkFulfillment(_requestId)
    {
        volume = _volume;
    }

his is the function we will be most concern of, 

 

request.add("get", "API ADDRESS");

here you will replace the url you want to read the data from 

the above url provides random json object. you can directly open it in your browser and check the output it will be like this :

{
   "data":{
      "id":3,
      "name":"true red",
      "year":2002,
      "color":"#BF1932",
      "pantone_value":"19-1664"
   },
   "support":{
      "url":"https://reqres.in/#support-heading",
      "text":"To keep ReqRes free, contributions towards server costs are appreciated!"
   }
}

In last smartbook we fetched id, now in this smartbook we are fetching name.

so the path will be data.name.

there is a catch here, when you request and then set volume as returned parameter , it will be in bytes32 format and not readable , so we need to convert it to string , so one extra function will be used :

 

convert bytes32 to string

function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
        uint8 i = 0;
        while(i < 32 && _bytes32[i] != 0) {
            i++;
        }
        bytes memory bytesArray = new bytes(i);
        for (i = 0; i < 32 && _bytes32[i] != 0; i++) {
            bytesArray[i] = _bytes32[i];
        }
        return string(bytesArray);
    }

In this function you can pass our result as an argument and it will return the string.

bytes32: 0x7472756520726564000000000000000000000000000000000000000000000000

 

and after you pass this bytes32 value in the above function the result will be just as expected - 

string: true red

 

Happy smart building !

Enjoyed the SmartBook?
Like
logo
contact@dapp-world.com
Katraj, Pune, Maharashtra, India - 411048

Follow Us

linkedintwitteryoutubediscordinstagram

Products

  • SmartBooks
  • Courses
  • Quizzes
  • Assessments

Support

  • Contact Us
  • FAQ
  • Privacy Policy
  • T&C

Backed By

ah! ventures

Copyright 2023 - All Rights Reserved.

Recommended from DAppWorld
img
1 May 2021
How to connect Ganache with Metamask and deploy Smart contracts on remix without
Set up your development environment with (Metamask + Ganache + Remix) and skip truffle :)
3 min read
11494
5
img
8 Jul 2021
How to interact with smart contarct from backend node js
call and send functions from backend server side using nodejs
3 min read
8069
2
img
18 Aug 2021
Send transaction with web3 using python
Introduction to web3.py and sending transaction on testnet
3 min read
6215
5
img
5 Aug 2021
Deploy Smart Contract on Polygon POS using Hardhat
how to deploy smart contracts on polygon pos chain using hardhat both mainnet and testnet ?
3 min read
5533
3