In this tutorial, we will be building a flask app to update you on the latest news. We will be implementing the app using the flask web framework. More on the framework check here.
We will then use the news API from newsapi.org.
Go ahead to newsapi.org and get your API key by creating an account. Make sure to keep your API key secret.
To use the API we first need to install the news API module, to install it run the command below.
pip install newsapi-python
Next, we need to install flask. To install run the command below.
pip3 install flask
Now let’s create a folder called flask-news and insert a file called app.py and a folder called templates and place a file called index.html inside.
Inside the app.py file let’s import a few modules as shown below.
from flask import Flask, render_template, request
from newsapi import NewsApiClient
Now let’s initialize our app as shown below.
app = Flask(__name__)
Next, let’s create a function to handle the news requests.
@app.route('/',methods=['POST','GET'])
def search():
API_KEY = '123456789123345'
newsapi = NewsApiClient(api_key=API_KEY)
headlines = newsapi.get_top_headlines(sources='')
articles = headlines['articles']
return render_template('news.html', articles=articles)
Insert your API key and make sure to keep it private. Finish by adding the following in the app.py file.
if __name__ == '__main__':
app.run()
Now let’s create a template to render our news details. In the index.html file we created above insert the following.
<!doctype html>
<html>
<head>
</head>
<body>
<div class="container">
<div id="results">
{% for article in articles %}
<div class="result">
<h2><a href="{{ article.url }}">{{ article.title }}</a></h2>
<p>{{ article.description }}</p>
</div>
{% endfor %}
</div>
</div>
</body>
</html>
Now let’s start our server by running the command below.
python3 app.py
You can also use the command below.
flask run
Now open your web browser and enter the address below.
http://127.0.0.1:5000
You should now see news headlines pop up as shown below.
There you have it. Thanks for reading.