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!!