Single Word Response

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.

Example

This example shows how to:

  • Fetch a single word response in a single call.

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:

  • Link token address
  • Oracle address
  • Job id
  • Request fee
  • Task parameters
  • Callback function signature

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.
 * THIS EXAMPLE USES UN-AUDITED CODE.
 * 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
     *
     * Goerli Testnet details:
     * Link Token: 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
     * Oracle: 0xCC79157eb46F5624204f47AB42b3906cAA40eaB7 (Chainlink DevRel)
     * jobId: ca98366cc7314957b8c012c72f05aeeb
     *
     */
    constructor() ConfirmedOwner(msg.sender) {
        setChainlinkToken(0x326C977E6efc84E512bB9C30f76E30c160eD06FB);
        setChainlinkOracle(0xCC79157eb46F5624204f47AB42b3906cAA40eaB7);
        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:

  1. Open the contract in Remix.

  2. Compile and deploy the contract using the Injected Provider environment. The contract includes all the configuration variables for the Goerli testnet. Make sure your wallet is set to use Goerli. The constructor sets the following parameters:

    • The Chainlink Token address for Goerli by calling the setChainlinkToken function.
    • The Oracle contract address for Goerli by calling the setChainlinkOracle function.
    • The 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. We are going to use a generic GET>uint256 job that can be found here.
  3. Fund your contract with 0.1 LINK. To learn how to send LINK to contracts, read the Fund Your Contracts page.

  4. Call the volume function to confirm that the volume state variable is equal to zero.

  5. Run the requestVolumeData function. This builds the Chainlink.Request using the correct parameters:

    • The req.add("get", "<cryptocompareURL>") request parameter provides the oracle node with the URL from which to fetch ETH-USD trading info.
    • The 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'.
    • The 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. Note: The times parameter is mandatory. If the API that you call returns a number without any decimals then provide 1as timesAmount. The 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.
  6. After few seconds, call the volume function. You should get a non-zero response.

Response Types

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 integers
  • int256 - Signed integers
  • bool - True or False values
  • string - String
  • bytes32 - 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 data

The 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.

Check the Find Existing Jobs page to learn how to find a job suitable to your use case.

Whats Next

Stay updated on the latest Chainlink news