Flask NEWS Application Using Newsapi


Python developers may create tiny to medium-sized web apps using the well-liked Flask web framework. It is easy to operate and lightweight. This project showcases the use of the News API, a well-known API for gathering news headlines and stories from many sources, to build a straightforward news application.

Installation and Syntax

To get started with our Flask news application, we need to first install Flask and the News API library. We can install Flask using pip, which is a package installer for Python. We can then install the News API library using the following command −

pip install newsapi-python flask

Before we dive into the implementation details of our Flask news application, let's first take a look at the basic syntax of Flask. A Flask application typically consists of a series of routes, which are URLs that map to Python functions. Here's an example of a simple Flask route −

from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
   return 'Hello, World!'

if __name__ == '__main__':
   app.run()

Algorithm

  • Install Flask and NewsAPI Client packages

  • Import the required libraries and create a Flask app instance

  • Define a route for the Flask application and create a function to retrieve news articles using the News API Client library. In this function, use the get_top_headlines() method to retrieve the top headlines from the BBC News source. Extract the title, description, urlToImage and url for each article and append them to separate lists.

  • In the Flask application's templates folder, create a new HTML file with the name news.html. Utilizing the Jinja2 templating syntax, display each news article's title, description, urlToImage, and url in an HTML template in this file.

  • Open a web browser and navigate to http://localhost:5000 in the python app.py file to check the News!

Example

Note − Replace <your-api-key> in with your own News API key. You can obtain a free API key by registering on the News API website.

app.py

from flask import Flask, render_template
from newsapi import NewsApiClient

app = Flask(__name__)
newsapi = NewsApiClient(api_key='<your-api-key>')

@app.route('/')
def news():
   top_headlines = newsapi.get_top_headlines(sources='bbc-news')
   top_headlines = top_headlines['articles']
   desc = []
   news = []
   img = []
   link = []
   for i in range(len(top_headlines)):
      myarticles = top_headlines[i]
      news.append(myarticles['title'])
      desc.append(myarticles['description'])
      img.append(myarticles['urlToImage'])
      link.append(myarticles['url'])
        
   mylist = zip(news, desc, img, link)
   return render_template('news.html', context=mylist)

if __name__ == '__main__':
   app.run()

news.html

Note − [Make a folder called “templates” in the same location as “app.py” and inside that folder store this news.html file]

{% block content %}
<h1>Top Headlines</h1>
{% for title, description, image, url in context %}
<div class="article">
   <h2>{{ title }}</h2>
   {% if image %}
   <img src="{{ image }}" alt="{{ title }}" width="100" height="100">
   {% endif %}
   <p>{{ description }}</p>
   <a href="{{ url }}">Read more</a>

</div>
{% endfor %}
{% endblock %}

To run this, open the terminal where your app.py file is located and type python app.py. Visit http://127.0.0.1:5000 to access the News App as this will launch a localhost server.

Output

Explanation

The project consists of two main files, "app.py" and "news.html", and requires the "flask" and "newsapi" libraries to be installed.

  • The "app.py" file contains the Flask web application's main logic. It imports the Flask and render_template modules from Flask and the NewsApiClient class from newsapi. An API key is also required to access the news data.

  • The "@app.route('/')" decorator specifies the URL endpoint for the Flask application. When the user navigates to the root URL, the "news" function is called. This function makes an API request to the NewsAPI to get the top headlines from the BBC News source. It extracts the relevant data from the API response and stores it in separate lists, including the title, description, image URL, and URL link to the full article.

  • Then, the function uses the built-in zip function to combine these lists into a single iterable called "mylist". This iterable contains a tuple for each article, where each tuple contains the title, description, image URL, and URL link.

  • Finally, the function renders the "news.html" template using the "render_template" method from Flask. It passes the "mylist" iterable to the "context" variable in the "news.html" template.

  • The "news.html" file contains the HTML and Jinja2 template code for displaying the top headlines on the webpage. The {% block content %} and {% endblock %} tags define a block where the content will be displayed. The for loop iterates over the "context" iterable passed from "app.py" and displays the title, image (if available), description, and a "Read more" link for each article.

Conclusion

Using this well-known service for gathering news stories from various sources, you can create a one-page news application that displays the most recent headlines, summaries, photographs, and links based on the chosen source. This article shows you how to develop a simple Flask news application using the News API enabling you to quickly and effectively create online applications by combining the Flask web framework and the Python programming language.

Updated on: 21-Aug-2023

153 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements