Computer >> Computer tutorials >  >> Programming >> Python

Fetching top news using news API in Python


News API is very famous API for searching and fetching news articles from any web site, using this API anyone can fetch top 10 heading line of news from any web site.

But using this API, one thing is required which is the API key.

Example Code

import requests    
def Topnews():
   # BBC news api
   my_api_key="Api_number”
   my_url = = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=my_api_key"
   my_open_bbc_page = requests.get(my_url).json()
   my_article = my_open_bbc_page["articles"]
   my_results = []
   for ar in my_article:
      my_results.append(ar["title"])
   for i in range(len(my_results)):
      print(i + 1, my_results[i])                
# Driver Code
if __name__ == '__main__':
   # function call
   Topnews()
Fetching top news using news API in Python

Using Panda

Using pandas DataFrame is much easier to work with down the road, we can easily convert from JSON to DataFrame using pd.DataFrame.from_dict and .appy([pd.Series]).

Fetching top news using news API in Python