Search code examples
javascriptapisearchfeed

How to use ContextualWeb News API in node.js using axios HTTP client?


I am trying to integrate ContextualWeb News API in a node.js application. In particular, I would like to use axios with parameters to make the GET request to the news API endpoint.

The following code works but it uses fetch and the parameters are embedded in the url which is inconvenient:

const url ="https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI?autoCorrect=false&pageNumber=1&pageSize=10&q=Taylor+Swift&safeSearch=false"
const options = {
  method: 'GET',
  headers: {
    "X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
    "X-RapidAPI-Key": "XXXXXXXX"
  },
}

fetch(url, options)
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.error(e))

How can the code be converted to work with axios? The ContextualWeb news API should return a resulting JSON with the related news articles.


Solution

  • This approach should work:

    const axios = require("axios");
    const url = "https://contextualwebsearch-websearch-v1.p.rapidapi.com/api/Search/NewsSearchAPI";
    const config = {
        headers: {
            "X-RapidAPI-Host": "contextualwebsearch-websearch-v1.p.rapidapi.com",
            "X-RapidAPI-Key": "XXXXXX" // Replace with valid key
        },
        params: {
            autoCorrect: false,
            pageNumber: 1,
            pageSize: 10,
            q: "Taylor Swift",
            safeSearch: false
        }
    }
    
    axios.get(url, config)
    .then(response => console.log("Call response data: ", response.data))
    .catch(e => console.error(e))