The Wayback Machine - https://web.archive.org/web/20241127002524/https://www.geeksforgeeks.org/make-http-request-using-your-solidity-smart-contract/
Open In App

Make HTTP Request Using Your Solidity Smart Contract

Last Updated : 27 Mar, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Smart contracts are self-executing digital programs that are designed to automate the enforcement of the terms of a contract. Solidity is a programming language used to write these smart contracts on the Ethereum blockchain. 

One of the challenges with smart contracts is their inability to interact with the outside world, including making HTTP requests. Smart contracts are often limited in their ability to interact with external systems, which is a major limitation when building decentralized applications. The inability to make HTTP requests is a significant challenge for smart contract developers, as it limits their ability to access external data and services that are necessary to create more advanced and complex decentralized applications.

Problem Statement

To be able to make an HTTP request using a Solidity smart contract, in order to interact with external APIs and retrieve data from web services. However, since Solidity is a low-level programming language and runs on the Ethereum blockchain, it does not have built-in support for making HTTP requests. Therefore, we need to find a way to integrate an HTTP client into our smart contract so that it can communicate with external servers and fetch data that our contract can use in its logic.

Oracles and Chainlinks

Oracles are third-party services that act as intermediaries between smart contracts and external systems. They can provide smart contracts with access to external data and services, including the ability to make HTTP requests. Additionally, the use of oracles can increase the security of smart contracts, as they act as a buffer between the smart contract and external systems, reducing the risk of security vulnerabilities.

To implement this solution, we will use Chainlink as our oracle provider. Chainlink is a decentralized oracle network that connects smart contracts with off-chain data sources, APIs, and payment systems. Chainlink nodes will act as oracles, providing smart contracts with access to external APIs and data sources.

Create a Solidity smart contract that interacts with the Chainlink oracle network to make HTTP requests. The contract will define a function that takes a URL and a query string as input parameters and returns the result of the HTTP request as a string. The function will use the Chainlink oracle to make the HTTP request and retrieve the response data.

How the Smart Contract Works?

  1. The smart contract sends a request to the Chainlink oracle, including the URL and query string.
  2. The Chainlink oracle retrieves the response data from the external API or data source.
  3. The Chainlink oracle sends the response data back to the smart contract.
  4. The smart contract returns the response data to the calling application.

Approach

1. Create a New Solidity Smart Contract

Create a new solidity smart contract that will interact with the Chainlink oracle. This smart contract will need to inherit from the ChainlinkClient contract, which can be found in the Chainlink documentation.

2. Define a Function

Define a function in your smart contract that will make the HTTP request. This function will need to call the requestOracleData() function from the ChainlinkClient contract. The requestOracleData() function takes several parameters, including the URL of the API endpoint you want to call, the HTTP method to use, and the data format to expect.

3. Specify Chainlink Oracle 

Before calling the requestOracleData() function, you will need to specify the Chainlink oracle contract that will handle the request. This can be done by calling the setChainlinkOracle() function and passing in the address of the oracle contract.

4. Specify the Chainlink Job ID 

Specify the chainlink job ID that corresponds to the API endpoint you want to call. This can be done by calling the setChainlinkJobID() function and passing in the job ID.

5. Call requestOracleData() Function

Once you have specified the oracle contract and job ID, you can call the requestOracleData() function to make the HTTP request. This function will return a request ID that you can use to track the status of the request.

6. Upon Request Completion Oracle Call Callback Function

Once the request is complete, the oracle will call a callback function in your smart contract with the response data. You can define this callback function to do whatever you need with the response data.

7. Use Response Data to Perform Operations

You can use the response data in your smart contract to perform various operations, such as updating storage variables or triggering other functions in the contract.

Prerequisites

1. Install Node.js: Download and install the latest version of Node.js from the official website.

Install Node.js

 

2. Solidity development environment: You should have a Solidity development environment set up on your computer. This includes a code editor, a Solidity compiler, and a local blockchain for testing your smart contracts. You can use an online IDE like Remix.org.

3. Install Oracle or API Service: You can choose an Oracle or API service that meets your needs. Some popular services include Chainlink, Provable, and Band Protocol. Follow the documentation provided by the chosen service to set up an account and get an API endpoint.

4. Install the Chainlink client library: Install chainlink client library in your project using the command:

npm install @chainlink/contracts

Implementation

Step 1: We need to import the chainlink contract from the chainlink library as follows – 

import “https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/ChainlinkClient.sol”;

This provides us with the necessary functions to interact with Chainlink. The following GitHub code is being imported from chainlink.

GitHub code imported from Chainlink

 

Step 2: The contract defines the constructor function, which initializes the oracle, jobId, and fee variables to values specific to the testnet. It also calls the setPublicChainlinkToken() function from the ChainlinkClient contract, which sets the public Chainlink token as the token used for paying the fee.

    constructor() public {
       setPublicChainlinkToken();
       oracle = 0x2f90A6D021db21e1B2A077c5a37B3C7E75D15b7e;
       jobId = “29fa9aa13bf1468788b7cc4a500a45b8”;
       fee = 0.1 * 10 ** 18; // 0.1 LINK
   }

Chainlink Market

 

Step 3: The contract defines the requestEthereumPrice function, which sends a request to the external API to retrieve the current Ethereum price in US dollars. The function first creates a new Chainlink request by calling the buildChainlinkRequest function with the jobId, the address of the current contract instance (address(this)), and the fulfill function selector (which specifies the function to call when the request is fulfilled).

function requestEthereumPrice() public returns (bytes32 requestId) {
       Chainlink.Request memory request = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
       request.add(“get”, “https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD”);
       request.add(“path”, “USD”);
       request.addInt(“times”, 100);
       return sendChainlinkRequestTo(oracle, request, fee);
   }

Step 4: The function then adds the URL of the external API to the Chainlink request by calling the add function with the “get” parameter and the URL value. 

  • It also adds the path to the data in the API response that contains the Ethereum price in US dollars by calling the add function with the “path” parameter and the path value. 
  • The function multiplies the retrieved value by 100 to remove the decimals by calling the addInt function with the “times” parameter and the value of 100. 
  • Finally, the function sends the Chainlink request to the oracle by calling the sendChainlinkRequestTo function with the oracle, the request object, and the fee, and returns a requestId.
Etherscan

 

Step 5: When the oracle receives the request and retrieves the data from the external API, it triggers the fulfill function in the contract, passing in the requestId and the retrieved uint256 value. The fulfill function updates the value of the ethereumPrice variable with the retrieved value.

function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) {
       ethereumPrice = _price;
   }

 

Step 6: Deploy your contract to a local blockchain or testnet. 

Deploy contract

 

Step 7: Copy the address displayed and make sure you are signed into metamask.

Copy the address

 

Step 8: Choose a link token. Press the end and paste the copied address. Choose the transaction fee and click on “Next”.

Choose link token

 

Step 9: Confirm the transaction.

Confirm the transaction

 

Step 10: If you were to now check the currentPrice column the price of Ethereum will be updated. Overall, this smart contract demonstrates how to use Chainlink to securely retrieve data from external APIs and use it in a smart contract.

Solidity




pragma solidity ^0.6.0;
 
import "github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol";
 
// MyContract inherits the ChainlinkClient contract to gain the
// functionality of creating Chainlink requests
contract ChainlinkExample is ChainlinkClient {
  // Stores the answer from the Chainlink oracle
  uint256 public currentPrice;
  address public owner;
   
  // The address of an oracle - you can find node addresses on https://market.link/search/nodes
  address ORACLE_ADDRESS = 0xB36d3709e22F7c708348E225b20b13eA546E6D9c;
   
  // The address of the http get job - you can find job IDs on https://market.link/search/jobs
  string constant JOBID = "628eded7db7f4f799dbf69538dec7ff2";
   
  // 17 0s = 0.1 LINK
  // 18 0s = 1 LINK
  uint256 constant private ORACLE_PAYMENT = 100000000000000000;
 
  constructor() public {
    // Set the address for the LINK token for the network
    setPublicChainlinkToken();
    owner = msg.sender;
  }
 
  // Creates a Chainlink request with the uint256 multiplier job
  // Ideally, you'd want to pass the oracle payment, address, and jobID as
  function requestEthereumPrice()
    public
    onlyOwner
  {
    // newRequest takes a JobID, a callback address, and callback function as input
    Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(JOBID), address(this), this.fulfill.selector);
    // Adds a URL with the key "get" to the request parameters
    // Uses input param (dot-delimited string) as the "path" in the request parameters
    req.add("path", "USD");
    // Adds an integer with the key "times" to the request parameters
    req.addInt("times", 100);
    // Sends the request with the amount of payment specified to the oracle
    sendChainlinkRequestTo(ORACLE_ADDRESS, req, ORACLE_PAYMENT);
  }
 
  // fulfill receives a uint256 data type
  function fulfill(bytes32 _requestId, uint256 _price)
    public
    // Use recordChainlinkFulfillment to ensure only the requesting oracle can fulfill
    recordChainlinkFulfillment(_requestId)
  {
    currentPrice = _price;
  }
   
  // cancelRequest allows the owner to cancel an unfulfilled request
  function cancelRequest(
    bytes32 _requestId,
    uint256 _payment,
    bytes4 _callbackFunctionId,
    uint256 _expiration
  )
    public
    onlyOwner
  {
    cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration);
  }
 
   
  // withdrawLink allows the owner to withdraw any extra LINK on the contract
  function withdrawLink()
    public
    onlyOwner
  {
    LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
    require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer");
  }
   
  modifier onlyOwner() {
    require(msg.sender == owner);
    _;
  }
   
   // A helper function to make the string a bytes32
  function stringToBytes32(string memory source) private pure returns (bytes32 result) {
    bytes memory tempEmptyStringTest = bytes(source);
    if (tempEmptyStringTest.length == 0) {
      return 0x0;
    }
    assembly { // solhint-disable-line no-inline-assembly
      result := mload(add(source, 32))
    }
  }
}


Output: 

Output

 

Functions

The contract imports the ChainlinkClient contract from “@chainlink/contracts/src/v0.8/ChainlinkClient.sol” to inherit from it. The contract defines a public uint256 variable ‘result’ and two public functions: ‘makeHttpRequest’ and ‘fulfill’.

  • makeHttpRequest Function: The ‘makeHttpRequest’ function is a public function that sends a GET request to a specified URL. It builds the Chainlink request using the buildChainlinkRequest function and adds a parameter to the request using the ‘add’ function. Finally, it sends the request using the ‘sendChainlinkRequestTo’ function, which specifies the oracle address and job ID to use.
  • fulfill Function: The ‘fulfill’ function is a public function that is called when the Chainlink request is fulfilled. It takes the request ID and the result of the request as parameters and stores the result in the ‘result’ variable.

Conclusion 

In conclusion, Chainlink is a valuable tool for interacting with external APIs in a secure and decentralized way within Solidity smart contracts. By using Chainlink, we can easily make HTTP requests to external data sources and receive the results back in a reliable and efficient manner. Its integration with Solidity is straightforward, which makes it an accessible option for developers looking to incorporate off-chain data into their on-chain applications to create more advanced and complex decentralized applications. 



Previous Article
Next Article

Similar Reads

Steps to Execute Solidity Smart Contract using Remix IDE
Remix IDE is generally used to compile and run Solidity smart contracts. Below are the steps for the compilation, execution, and debugging of the smart contract. Step 1: Open Remix IDE on any of your browsers, select on New File and click on Solidity to choose the environment. Step 2: Write the Smart contract in the code section, and click the Comp
1 min read
Creating a Smart Contract that Returns Address and Balance of Owner using Solidity
Problem: Create a smart contract named MyContract having a state variable as owner. Create a constructor to fetch the address of the owner from msg and hold it into the state variable owner. Also, create a function getBalance() to show the current balance of the owner. Solution: Every smart contract is owned by an address called as owner. A smart c
2 min read
How to use GANACHE Truffle Suite to Deploy a Smart Contract in Solidity (Blockchain)?
There are various processes involved in deploying a smart contract using Ganache and Truffle Suite: 1. Install Ganache first. Ganache is a personal blockchain for Ethereum development. You must first download and install it. It is available for download from https://www.trufflesuite.com/ganache, the official website. 2. Install Truffle Suite: The n
4 min read
What is Smart Contract in Solidity?
Solidity's code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (its state) that resides at a specific address on the Ethereum blockchain. A contract is a fundamental block of building an application on Ethereum. Now let's look at the code example for making smart contract : Example #
4 min read
How to use MetaMask to Deploy a Smart contract in Solidity (Blockchain)?
Smart contracts are self-executing contracts. They were first proposed by Nick Szabo in the 90s. They are set of rules and protocols which two parties agree upon and have to follow. One of the main features is that they are immutable once deployed on the blockchain. It is widely used in the Ethereum blockchain. The main language used for writing sm
3 min read
Solidity - Deploy a Smart Contract for Marks Management System
Solidity is a high-level language. The structure of smart contracts in solidity is very similar to the structure of classes in object-oriented languages. The solidity file has an extension .sol. What are Smart Contracts?Solidity’s code is encapsulated in contracts which means a contract in Solidity is a collection of code (its functions) and data (
3 min read
Decentralized Bank Smart Contract in Solidity
Solidity is an Object-oriented Programming Language for implementing Smart Contracts. It's a High-Level Statically Typed Language like C. The solidity file has an extension .sol. The article focuses on discussing the decentralized bank smart contract in Solidity. In the below example, the aim is to deploy a Smart Contract for Decentralized Bank Sys
3 min read
Integrating your Smart Contract with Frontend
In this article, we are going to learn how to connect a smart contract to the front end. To keep the process less complex and focus on the integration process, the smart contract in itself is kept simple. You can easily introduce multiple complex functions once you understand the basics. For this tutorial, we are simply putting a campaign on the lo
14 min read
Building a Simple Fixed Deposit Application Using Solidity Smart Contracts
Blockchain technology has revolutionized the way we handle financial transactions, and the world of decentralized finance (DeFi) is growing at an unprecedented rate. One of the most intriguing aspects of this financial evolution is the use of smart contracts, which are self-executing agreements with the power to automate and secure various financia
13 min read
Interacting With Ethereum Smart Contract Using Web3js
Ethereum is a cryptocurrency platform in the market just like Bitcoin. It is an open-source & decentralized blockchain featuring working on smart contracts. It has its own cryptocurrency known as ether. The smart contracts in Ethereum are written in solidity. TestRPC The Ethereum TestRPC is like a manual emulator for blockchain. It provides blo
4 min read
Solidity - Abstract Contract
Abstract contracts are contracts that have at least one function without its implementation or in the case when you don't provide arguments for all of the base contract constructors. Also in the case when we don't intend to create a contract directly we can consider the contract to be abstract. An instance of an abstract cannot be created. Abstract
3 min read
Interaction Between Smart Contracts with Solidity
Interaction between two smart contracts in Solidity means invoking functions of one contract from another contract so that we can use the content of one contract in another. For example, if you want to use contractA methods into contractB, so simply import the contractA inside contract B and create an instance of contractA then call methods using t
5 min read
What is Escrow Smart Contract?
Escrow is the third party that holds the asset(asset can be money, bond, or stocks) in the presence of two parties. Escrow will release the fund when certain conditions are met. For Example: "A" is a seller and wants to sell his car, and "B" is a buyer who wants to buy "A"'s car so they will contact Escrow "C"(an arbiter) which holds the asset unti
2 min read
How to Simply Deploy a Smart Contract on Ethereum?
Smart contracts are blocks of code that reside on the blockchain. It is like an Ethereum account but there is a critical difference between an external account and a smart contract. Unlike a smart contract, an external account can connect to multiple Ethereum networks (Goerli testnet, mainnet, etc.) whereas a smart contract is only specific to one
7 min read
Setting Up Smart Contract Development Environment
A development environment is an environment in which all the resources and tools are available which are used to develop a program or software product. Here, an attempt to create a development environment that is a collection of the processes and tools that are used to develop smart contracts. There are mainly two choices available to set up the en
5 min read
Deploy a Smart Contract on Ethereum with Python, Truffle and web3py
This article discusses deploying a Smart Contract on Ethereum with Python, Truffle, and web3py. Prerequisite: In order to write a simple smart contract, deploy it to a personal Ethereum blockchain, and call the contract using Python3, install the below software on a PC: 1. Python3 v3.5.3 or later versions: Install python following the instructions
6 min read
How to Test a Smart Contract for Ethereum?
Public Blockchains like Ethereum are immutable, it is difficult to update the code of a smart contract once it has been deployed. To guarantee security, smart contracts must be tested before they are deployed to Mainnet. There are several strategies for testing contracts, but a test suite comprised of various tools and approaches is suitable for de
15+ min read
How to Test a Smart Contract with Remix?
The Remix IDE is an open-source development environment for building, testing, and deploying smart contracts on the Ethereum blockchain. One of the most notable features of Remix IDE is its integration with the Solidity programming language. Solidity is a contract-oriented language that is specifically designed for building smart contracts on Ether
7 min read
How to Calling Smart Contract Functions with Web3.js?
Have you wondered how smart contracts interact with the front end? So, the answer is the web3.js library. First, briefly discuss some terms related to web3.js and learn about them. Web3.js: Web3. js is a collection of libraries that allow users to interact between smart contracts and the front end. It is used to develop websites that can interact w
4 min read
Steps to Create, Test and Deploy Ethereum Smart Contract
Smart contracts are self-execution programs stored on a blockchain that are automatically executed when predefined conditions are met. They allow the participants on the blockchain to transact with each other without a trusted central authority. After creating a smart contract, the next step is to deploy the smart contract onto a blockchain for exe
7 min read
What is a NFT Smart Contract?
NFT Smart contracts play an important role in the blockchain space across many use cases. In particular, NFT smart contracts are becoming increasingly important as the metaverse and Web3 attract more interest. NFT smart contracts are specialized blockchain contracts that facilitate the creation, ownership, transfer, and management of NFTs. This art
8 min read
Life Cycle of Smart Contract
Smart contracts are self-executing agreements with the terms directly written into code. Understanding their life cycle is essential for anyone involved in blockchain development. This life cycle includes key phases such as development, testing, deployment, interaction, and maintenance. Each phase plays a crucial role in ensuring the contract funct
7 min read
Random Number Generator in Solidity using keccak256
Random numbers are numbers that occur in a sequence with the following two mandatory conditions: The values are uniformly distributed over a set interval.One cannot predict future values based on past outputs.Example: In the below example, we have created a contract with a function that will generate a random number in a specific range. Below is th
3 min read
How to Deploy Contract From NodeJS using Web3?
This article focuses on discussing deploying a contract from NodeJS using web3. The following topics will be covered in this article: Introduction to web3js modules.How to generate ABI and bytecode using web3js.Compilation and deployment of smart contracts using web3js.Software requirements: Nodejs.Ganache.Text editor - VS Code1. Introduction to we
6 min read
How to deploy Smart Contracts using Ethers.js and Node.js on Goerli Testnet Blockchain from Back-end ?
In this article, we will be deploying smart contracts on blockchain from back-end, so that we do not have to require hardhat or truffle frameworks and their commands to deploy a smart contract or if somebody doesn't want to use these frameworks. Since we have to run manual commands of these frameworks in the terminal to deploy Smart Contracts. We c
9 min read
Solidity - Types
Solidity is a statically typed language, which implies that the type of each of the variables should be specified. Data types allow the compiler to check the correct usage of the variables. The declared types have some default values called Zero-State, for example for bool the default value is False. Likewise other statically typed languages Solidi
4 min read
Solidity - Functions
A function is basically a group of code that can be reused anywhere in the program, which generally saves the excessive use of memory and decreases the runtime of the program. Creating a function reduces the need of writing the same code over and over again. With the help of functions, a program can be divided into many small pieces of code for bet
4 min read
What are Events in Solidity?
Solidity Events are the same as events in any other programming language. An event is an inheritable member of the contract, which stores the arguments passed in the transaction logs when emitted. Generally, events are used to inform the calling application about the current state of the contract, with the help of the logging facility of EVM. Event
2 min read
Solidity - Inheritance
Inheritance is one of the most important features of the object-oriented programming language. It is a way of extending the functionality of a program, used to separate the code, reduces the dependency, and increases the re-usability of the existing code. Solidity supports inheritance between smart contracts, where multiple contracts can be inherit
6 min read
Solidity - Polymorphism
Polymorphism is the ability to process data in more than one form. Like any other programming language, Solidity also supports polymorphism. Solidity supports two types of polymorphism, Function Polymorphism, and Contract Polymorphism. Function Polymorphism Function Polymorphism is also known as method overloading. In function polymorphism, multipl
3 min read
three90RightbarBannerImg