1

I have quite some question regarding Chainlink call API.

I made an API and trying to call it from my Chainlink through smart contract. As I linked my API to bridge in Chainlink Operator UI, I try to write a simple job that just call my API and maybe fetch some data.

This is the job i wrote in TOML:

type = "directrequest"
schemaVersion = 1
name = "test"
externalJobID = "50dea92f-5a52-4c4e-9e8e-ad783b1fb5dc"
forwardingAllowed = false
maxTaskDuration = "0s"
contractAddress = "0xD415e06dCc8547A6B28b8F3CCa988C520Ae3E2e4"
minContractPaymentLinkJuels = "0"
observationSource = """
    fetch    [type="bridge" name="fastapi" requestData="{\\"data\\":{\\"foo\\": $(foo), \\"bar\\": $(bar)}}"]


    fetch 
"""

This is the API I simply made:

from fastapi import FastAPI, Request
import requests

app = FastAPI()


@app.post("/")
async def get_data(request: Request):
    try:
        # Extract the request data from the Chainlink node
        request_data = await request.json()

        # Ensure the correct endpoint and parameter is provided by Chainlink
        if "data" not in request_data:
            return {"error": "Invalid request format"}

        endpoint = request_data["data"]["endpoint"]
        # You can extract any other parameters as needed

        # Make a request to the external API (replace this with your desired external API)
        response = requests.get(endpoint)
        response_data = response.json()

        # Format the response in the format expected by Chainlink
        result = {
            "jobRunID": request_data["id"],
            "data": response_data,
            "statusCode": response.status_code
        }

        return result

    except:
        return {"error": "An error occurred while processing the request"}

And this is my Smart Contract Solidity code for calling:

pragma solidity >=0.4.22 <0.9.0;

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

contract FastAPI is ChainlinkClient {
    using Chainlink for Chainlink.Request;

    // Chainlink variables
    address private oracle;
    bytes32 private jobId;

    // Event to capture the API response
    event APIResponse(uint256 result);

    // Constructor
    constructor() {
        // Set the oracle address and Job ID for your specific Chainlink job
        oracle = 0xe61c17087b6De506D7B1D4A41808C4182EAbBa0a; // Replace with the actual oracle address
        jobId = "50dea92f5a524c4e9e8ead783b1fb5dc";
    }

    // Function to request data from Chainlink external adapter
    function requestDataFromChainlink(string memory data) public {
        Chainlink.Request memory req = buildChainlinkRequest(
            jobId,
            address(this),
            this.fulfill.selector
        );
        req.add("get", data);
        sendChainlinkRequestTo(oracle, req, 0); // Setting fee to 0 for Development mode
    }

    // Callback function called by Chainlink Oracle with the response
    function fulfill(
        bytes32 requestId,
        uint256 result
    ) public recordChainlinkFulfillment(requestId) {
        // Process the API response here
        emit APIResponse(result);
    }
}

Please give me some guidance as I am doing this for my research project with my university. Thanks in advance!!

4
  • What is your question? BTW, if you want to get results from external API for smart contracts for a research project, consider using Chainlink Functions to get any data from web2 API in a decentralized manner. By using Chainlink Functions, you don't need to do the node configuration and setup.
    – Frank Kong
    Commented Aug 3, 2023 at 9:22
  • Hi @FrankKong thanks for replying. Sorry for causing confusion, I'm trying to ask about on how to write a job in Chainlink so my smart contract will call it to run my API. So our reseach goal is to retrieve some data from another decentralize market like Ocean Market, would Chainlink Function work too without having to write jobs or external adapter API?
    – xopherwwl
    Commented Aug 3, 2023 at 22:16
  • Yes, if the Ocean Market provide API, you can use Chainlink Functions to fetch the result without writing jobs. If you want to use Chainlink any API to get API data, you need to set up a Chainlink node in the local and the node will provide an UI for you to write jobs. Please refer to here for node configuration and here for guides to write a job and contract.
    – Frank Kong
    Commented Aug 4, 2023 at 2:33
  • I understand what you mean now, thank you for explaining it perfectly!
    – xopherwwl
    Commented Aug 4, 2023 at 2:53

1 Answer 1

0

If you don't want to run your own Chainlink node, and are simply trying to call an internet-based API from your smart contract, you can feel free to use any of the various community Chainlink oracles (nodes) out there that exist to serve your request.

I recommend joining the Chainlink Official Discord server, and posting your request to the #operator-requests channel. One of the available oracles that monitor this channel will respond to your request.

Many of these Chainlink oracles (such as ourselves) also host websites with code examples that you can use in your smart contract to call your desired API.

Hope that helps!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.