Home > database >  How to get only first 15 documents from google news API?
How to get only first 15 documents from google news API?

Time:12-05

Now my code is returning all the news related to a company. But I want only the first 15 elements. How to do this? Here is the code which returns all the news for a company. google-news-json is a npm package.

export default async function handler(req, res) {
  try {
    let news = await googleNewsAPI.getNews(googleNewsAPI.SEARCH, req.body.companyName, 'en-US')
    res.status(200).json(news)

  } catch (err) {
    res.status(500).json({ error: 'Failed to fetch news' })
  }
}

CodePudding user response:

You need to take a close look at the API reference of google news functionality. There you can find a query parameter ( something like ?q=15 or ?count=no.of.items ) after your API key to return the count of object that you may want to receive in the fetch url

CodePudding user response:

Typically you'd want to do what @iceweasel suggests in their answer. However, since this package isn't supported by Google (but rather seems to be scraping the HTML produced by directly querying Google News and returning the results as JSON), it doesn't support many of the typical options you'd expect (in particular, limiting the number of returned elements).

If you don't mind the network cost of downloading the full 100 items (which is what your function returns by default), you take the first 15 results from the API's response with:

let top15 = news.items.slice(0, 15)

  • Related