Search
This guide explains how to make an HTTP GET request to an external API from a smart contract using Chainlink's Request & Receive Data cycle and receive a single response.
Table of Contents
This example shows how to:
The Cryptocompare GET /data/pricemultifull API returns the current trading info (price, vol, open, high, low) of any list of cryptocurrencies in any other currency that you need. To check the response, you can directly paste the following URL in your browser https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD
or run this command in your terminal:
curl -X 'GET' \
'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD' \
-H 'accept: application/json'
The response should be similar to the following example:
{
"RAW": {
"ETH": {
"USD": {
"TYPE": "5",
"MARKET": "CCCAGG",
"FROMSYMBOL": "ETH",
"TOSYMBOL": "USD",
"FLAGS": "2049",
"PRICE": 2867.04,
"LASTUPDATE": 1650896942,
"MEDIAN": 2866.2,
"LASTVOLUME": 0.16533939,
"LASTVOLUMETO": 474.375243849,
"LASTTRADEID": "1072154517",
"VOLUMEDAY": 195241.78281014622,
"VOLUMEDAYTO": 556240560.4621655,
"VOLUME24HOUR": 236248.94641103,
...
}
To consume an API with multiple responses, your contract must import ChainlinkClient. This contract exposes a struct called Chainlink.Request
, which your contract should use to build the API request. The request should include the following parameters:
️ Note on Funding Contracts
Making a GET request will fail unless your deployed contract has enough LINK to pay for it. Learn how to Acquire testnet LINK and Fund your contract.
Assume that a user wants to call the API above and retrieve only the 24h ETH trading volume from the response.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import '@chainlink/contracts/src/v0.8/ChainlinkClient.sol';
import '@chainlink/contracts/src/v0.8/ConfirmedOwner.sol';
/**
* Request testnet LINK and ETH here: https://faucets.chain.link/
* Find information on LINK Token Contracts and get the latest ETH and LINK faucets here: https://docs.chain.link/docs/link-token-contracts/
*/
/**
* THIS IS AN EXAMPLE CONTRACT WHICH USES HARDCODED VALUES FOR CLARITY.
* PLEASE DO NOT USE THIS CODE IN PRODUCTION.
*/
contract APIConsumer is ChainlinkClient, ConfirmedOwner {
using Chainlink for Chainlink.Request;
uint256 public volume;
bytes32 private jobId;
uint256 private fee;
event RequestVolume(bytes32 indexed requestId, uint256 volume);
/**
* @notice Initialize the link token and target oracle
*
* Kovan Testnet details:
* Link Token: 0xa36085F69e2889c224210F603D836748e7dC0088
* Oracle: 0x74EcC8Bdeb76F2C6760eD2dc8A46ca5e581fA656 (Chainlink DevRel)
* jobId: ca98366cc7314957b8c012c72f05aeeb
*
*/
constructor() ConfirmedOwner(msg.sender) {
setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088);
setChainlinkOracle(0x74EcC8Bdeb76F2C6760eD2dc8A46ca5e581fA656);
jobId = 'ca98366cc7314957b8c012c72f05aeeb';
fee = (1 * LINK_DIVISIBILITY) / 10; // 0,1 * 10**18 (Varies by network and job)
}
/**
* Create a Chainlink request to retrieve API response, find the target
* data, then multiply by 1000000000000000000 (to remove decimal places from data).
*/
function requestVolumeData() public returns (bytes32 requestId) {
Chainlink.Request memory req = buildChainlinkRequest(jobId, address(this), this.fulfill.selector);
// Set the URL to perform the GET request on
req.add('get', 'https://min-api.cryptocompare.com/data/pricemultifull?fsyms=ETH&tsyms=USD');
// Set the path to find the desired data in the API response, where the response format is:
// {"RAW":
// {"ETH":
// {"USD":
// {
// "VOLUME24HOUR": xxx.xxx,
// }
// }
// }
// }
// request.add("path", "RAW.ETH.USD.VOLUME24HOUR"); // Chainlink nodes prior to 1.0.0 support this format
req.add('path', 'RAW,ETH,USD,VOLUME24HOUR'); // Chainlink nodes 1.0.0 and later support this format
// Multiply the result by 1000000000000000000 to remove decimals
int256 timesAmount = 10**18;
req.addInt('times', timesAmount);
// Sends the request
return sendChainlinkRequest(req, fee);
}
/**
* Receive the response in the form of uint256
*/
function fulfill(bytes32 _requestId, uint256 _volume) public recordChainlinkFulfillment(_requestId) {
emit RequestVolume(_requestId, _volume);
volume = _volume;
}
/**
* Allow withdraw of Link tokens from the contract
*/
function withdrawLink() public onlyOwner {
LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress());
require(link.transfer(msg.sender, link.balanceOf(address(this))), 'Unable to transfer');
}
}
To use this contract:
Open the contract in Remix.
Compile and deploy the contract using the Injected Web3 environment. The contract includes all the configuration variables for the Kovan testnet. Make sure your wallet is set to use Kovan. The constructor sets the following parameters:
setChainlinkToken
function.setChainlinkOracle
function.jobId
: A specific job for the oracle node to run. In this case, you must call a job that is configured to call a public API, parse a number from the response and remove any decimals from it. You can find the job spec for the Chainlink node here.Fund your contract with 0.1 LINK. To learn how to send LINK to contracts, read the Fund Your Contracts page.
Call the volume
function to confirm that the volume
state variable is equal to zero.
Run the requestVolumeData
function. This builds the Chainlink.Request
using the correct parameters:
req.add("get", "<cryptocompareURL>")
request parameter provides the oracle node with the url where to fetch the ETH-USD trading info.req.add('path', 'RAW,ETH,USD,VOLUME24HOUR')
request parameter tells the oracle node where to fetch the 24h ETH volume in the json response. It uses a JSONPath expression with comma(,) delimited string for nested objects. For example: 'RAW,ETH,USD,VOLUME24HOUR'
.req.addInt('times', timesAmount)
request parameter provides the oracle node with the multiplier timesAmount
by which the fetched volume is multiplied. Use this to remove any decimals from the volume.APIConsumer
in the example above is flexible enough to call any public API as long as the URL in get, path, and timesAmounnt are correct.After few seconds, call the volume
function. You should get a non-zero response.
Make sure to choose an oracle job that supports the data type that your contract needs to consume. Multiple data types are available such as:
uint256
- Unsigned integersint256
- Signed integersbool
- True or False valuesstring
- Stringbytes32
- Strings and byte values. If you need to return a string, use bytes32
. Here's one method of converting bytes32
to string
. Currently, any return value must fit within 32 bytes. If the value is bigger than that, make multiple requests.bytes
- Arbitrary-length raw byte dataThe setChainlinkToken
function sets the LINK token address for the network you are deploying to. The setChainlinkOracle
function sets a specific Chainlink oracle that a contract makes an API call from. The jobId
refers to a specific job for that node to run.
Each job is unique and returns different types of data. For example, a job that returns a bytes32
variable from an API would have a different jobId
than a job that retrieved the same data, but in the form of a uint256
variable.
market.link provides a searchable catalog of oracles, jobs, and their subsequent return types.