Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a string from any API using Chainlink Large Response Example

I just need to get a string from this json, for example: https://filesamples.com/samples/code/json/sample1.json

I took the Chainlink example and just change the URL and path. The example works fine, but if you use a different json o jobid it do not work.

Link to chainlink example: https://docs.chain.link/docs/large-responses/

Is there any way to solve this?

Code used:

//SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;

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

/**
 * @notice DO NOT USE THIS CODE IN PRODUCTION. This is an example contract. 
 */
contract GenericLargeResponse is ChainlinkClient {
  using Chainlink for Chainlink.Request;

  // variable bytes returned in a signle oracle response
  bytes public data;
  string public dataS;

  /**
   * @notice Initialize the link token and target oracle
   * @dev The oracle address must be an Operator contract for multiword response
   *
   *
   * Kovan Testnet details: 
   * Link Token: 0xa36085F69e2889c224210F603D836748e7dC0088
   * Oracle: 0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8 (Chainlink DevRel)
   *
   */
  constructor(
  ) {
    setChainlinkToken(0xa36085F69e2889c224210F603D836748e7dC0088);
    setChainlinkOracle(0xc57B33452b4F7BB189bB5AfaE9cc4aBa1f7a4FD8);
  }

  /**
   * @notice Request variable bytes from the oracle
   */
  function requestBytes(
  )
    public
  {
    bytes32 specId = "7a97ff8493ec406d90621b2531f9251a";
    uint256 payment = 100000000000000000;
    Chainlink.Request memory req = buildChainlinkRequest(specId, address(this), this.fulfillBytes.selector);
    req.add("get","https://filesamples.com/samples/code/json/sample1.json");
    req.add("path", "fruit");
    requestOracleData(req, payment);
  }

  event RequestFulfilled(
    bytes32 indexed requestId,
    bytes indexed data
  );

  /**
   * @notice Fulfillment function for variable bytes
   * @dev This is called by the oracle. recordChainlinkFulfillment must be used.
   */
  function fulfillBytes(
    bytes32 requestId,
    bytes memory bytesData
  )
    public
    recordChainlinkFulfillment(requestId)
  {
    emit RequestFulfilled(requestId, bytesData);
    data = bytesData;
    dataS = string(data);
  }

}
like image 713
mfabroni Avatar asked Dec 07 '25 02:12

mfabroni


1 Answers

The response of that API is:

{
  "fruit": "Apple",
  "size": "Large",
  "color": "Red"
}

The fruit has a value of Apple. You'll need to have the API return the bytes edition of Apple instead.

You'll notice the example returns JSON that looks like:

{
  "image": "0x68747470733a2f2f697066732e696f2f697066732f516d5358416257356b716e3259777435444c336857354d736a654b4a4839724c654c6b51733362527579547871313f66696c656e616d653d73756e2d636861696e6c696e6b2e676966"
}

Which is the hex edition of the URL of the image.

like image 193
Patrick Collins Avatar answered Dec 08 '25 14:12

Patrick Collins