Got a cool example to share? Get listed here! Submit it now.

useChainlinkFunctions()

Collection of community submitted examples for Chainlink Functions

Get inspired from quick examples

Chainlink Functions, a new self-service platform that allows anyone to write serverless code to fetch any data from any API and run custom compute on Chainlink's network. Learn from examples created by the community or contribute your own!
Learn more about Chainlink Functions

Latest News Headline from NEWS API

Submitted by:
Shikhar Agarwal
This Function returns the latest news headline for a particular country. It uses the NEWS API to get the news. Parameters include country code and keyword(if user want to filter search on the basis of keyword)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 // This function fetches the latest news headline from a country // Args include country code and keyword(if any) // If user don't want to filter result on the basis of keyword, just pass an empty string for keyword if (!secrets.apiKey) { throw Error("Api Key Not Found") } const url = "https://newsapi.org/v2/top-headlines?" const country = args[0] // Example - "in" for India const keywordSearch = args[1] // Example - "web3" (This arg is optional, leave an empty string) console.log(`Sending HTTP GET Request to ${url}country=${country}&q=${keywordSearch}`) const newsRequest = Functions.makeHttpRequest({ url: url, method: "GET", headers: { "X-Api-Key": secrets.apiKey }, params: { country: country, q: keywordSearch } }) // Execute the API request (Promise) const newsResponse = await newsRequest // check if there was any error during the request if (newsResponse.error) { throw Error("Request failed") } // if there is no news, throw an error with the message if (newsResponse.data.articles.length == 0) { throw Error("No news!") } // get the latest news const newsSelect = newsResponse.data.articles[0] // choosing the required parameters to be uploaded const newsData = { publishTime: newsSelect.publishedAt, title: newsSelect.title } // Use JSON.stringify() to convert from JSON object to JSON string // Finally, use the helper Functions.encodeString() to encode from string to bytes return Functions.encodeString(JSON.stringify(newsData))