How I created a News Application using the Flask Framework

4.6/5 - (5 votes)

As part of your journey to becoming a web developer, working on projects is a compulsory requirement. You gain experience, exposure, and the necessary skills to increase your chances of getting a job.

πŸ’‘ In this tutorial, we will use Flask, one of Python’s web development framework to create a News application. We will make use of an API to fetch the latest news.

Our previous Flask project tutorial that involved using an API was when we created a weather app, it was there we introduced Flask. Feel free to check it out to become more familiar with Flask!

Getting started

Create a folder for this project. Inside the folder, create and activate a virtual environment.

Afterward, install Flask, python-dotenv, python-decouple and the requests module.

Finally, create a requirements.txt file to store the module versions which will be used in case a future version affects the smooth running of this application.

mkdir && cd project
pip -m venv .venv
source .venv/bin/activate
pip install flask python-dotenv python-decouple requests
pip freeze > requirements.txt

We use both python-dotenv and python-decouple to load environment variables. Requests will be used to fetch the latest news headlines.

News API

For this project, we will use News API2 to fetch the latest news. Sign up for a free account to receive your API key. Then create a .env file in the project directory, and store your API key there.

NEWS_API_KEY = 'YOUR_API_KEY'

Then, create a main.py file and add the following script to it:

from flask import Flask, render_template
import requests
from decouple import config


API_KEY = config('NEWS_API_KEY')

app = Flask(__name__)

country = 'us'

@app.route('/')
def news_headlines():
    url = f'https://newsapi.org/v2/top-headlines?country={country}&apiKey={API_KEY}'
    res = requests.get(url).json()
    news_articles = res['articles']
    return render_template('index.html', news_articles=news_articles)

As usual, we import the Flask app and creates the application object as an instance of the class. The __name__ variable passed to the Flask class is used, among other things, to locate associated resources such as templates.

We follow best practices regarding storing sensitive information such as API key. Instead of exposing our API key, we store it in a .env file. Then use the config class from the python-decouple module to get the values of the environment variable.

πŸ’‘ Recommended: How I Designed a News Aggregator Web Application Using Django

We also set the country to United States to get the latest news happening in the country. Of course, you can use any country of your choice. Check the documentation to know the country code.

The news_headlines() function has a @app.route decorator that links the function to the associated URL. The return value of the function will be displayed to the browser when the URL is requested.

Using the requests module, we make a GET request to the URL of the News API. The response is converted into JSON. We save the list containing the news in a variable, and pass it to the render_template() function.

Templates

Flask, by default, searches for template files in the template folder. So, we have to create the folder, and also create an index.html file. Remember, this was passed to the render_template() function.

<!DOCTYPE html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <!-- Bootstrap CSS -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3"
      crossorigin="anonymous"
    />
    <title>Flask Latest News</title>
  </head>
  <body>
    <h1 class="text-center mt-4 mb-5">Flask Latest News Headlines</h1>
    <div class="row mt-5">
      <div class="col-md-2"></div>
      <div class="col-md-8">
        <div class="row">
          {% for news in news_articles %}
          <div class="col-md-4 mb-5">
            <div class="card" style="width: 18rem">
              <img src="{{ news.urlToImage }}" class="card-img-top" alt="..." />
              <div class="card-body">
                <h5 class="card-title">{{ news.title }}</h5>
                <p class="card-text">{{ news.description }}</p>
                <a href="{{ news.url }}" class="btn btn-primary">Read More</a>
              </div>
            </div>
          </div>
          {% endfor %}
        </div>
      </div>
      <div class="col-md-2"></div>
    </div>
    <!-- Bootstrap Bundle with Popper -->
    <script
   src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

We use Bootstrap to style the website. Each news headline gotten from the News API has an image, a title, description, and a link to read more. So, we use Jinja2 for-loop to iterate over the news_articles.

The urlToImage is the URL for the image of the article.

Conclusion

This is a how we use an API to fetch the current news headlines and have them rendered on our Flask application. It is a very simple project for beginners. No doubt, you have learned a lot from this project tutorial. πŸ’ͺ

In upcoming tutorials, I’m going to demonstrate how to create this application using the Django framework. To run the Flask app, create a .flaskenv file and write the following:

FLASK_APP=main.py

Now that we have taken care that, we will not always have to set the FLASK_APP environment variable whenever we want to run the flask command. Make sure you have installed the python-dotenv package.

We are done. Just type flask run in your terminal, hit the Enter key to start the local server, and get the latest news. The full code is available on my GitHub page. Alright, enjoy your day!

πŸ’‘ Recommended: How I Deployed a Machine Learning Application Using the Flask Webserver