Project Brief
Your task for this project is to build a simple news website that shows the latest business news. The code given in the solution link uses Flask and produces the following website.
Clicking any of the links takes the user to the relevant news article.
Environment Setup Instructions
Install the required libraries with:
pip flask requests
Obtain a free API key at https://newsapi.org/ and use requests to get news in JSON.
Execute with python main.py
Project Solution
Feel free to post your questions or comments in the comment section below.
Happy Coding!
Daily Python Projects Team
I have completed. Here is my code.
main.py
from flask import Flask, render_template
import requests
app = Flask(__name__)
NEWS_API_KEY = 'my_api_key'
NEW_API_URL = 'https://newsapi.org/v2/top-headlines?country=in&language=en&apiKey=' + NEWS_API_KEY
@app.route('/')
def home():
"""
Fetches the top headlines from NewsAPI and renders them on the home.html template.
:return:
str: The rendered HTML content for the home page, displaying the list of news articles.
"""
response = requests.get(NEW_API_URL)
news_data = response.json()
articles = news_data.get('articles', [])
return render_template('home.html', articles=articles)
if __name__ == "__main__":
app.run(debug=True)
home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<title>Latest News</title>
</head>
<body>
<div class="container">
<h1 class="my-4">Latest News Headlines</h1>
<div class="list-group">
{% for article in articles %}
<a href="{{ article['url'] }}" class="list-group-item list-group-item-action" target="_blank">
<h5 class="mb-1">{{ article['title'] }}</h5>
</a>
{% endfor %}
</div>
</div>
</body>
</html>