News Aggregator

Step 1: Set Up Your Environment

  1. Install Flask and Requests:bashCopy codepip install Flask requests
  2. Sign Up for News API:
    • Go to News API and sign up to get your API key.

Step 2: Create Your Flask App

Create a file named app.py:

pythonCopy codefrom flask import Flask, render_template, request
import requests

app = Flask(__name__)

API_KEY = 'YOUR_NEWS_API_KEY'  # Replace with your News API key

@app.route('/')
def index():
query = request.args.get('query', '')
articles = []
if query:
    url = f'https://newsapi.org/v2/everything?q={query}&apiKey={API_KEY}'
    response = requests.get(url)
    data = response.json()
    articles = data.get('articles', [])
return render_template('index.html', articles=articles, query=query)
if __name__ == '__main__':
app.run(debug=True)

Step 3: Create the HTML Template

Create a folder named templates in the same directory as app.py, and inside that folder, create a file named index.html:

htmlCopy code<!DOCTYPE html>
<html lang="en">
<head>
&lt;meta charset="UTF-8"&gt;
&lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt;
&lt;title&gt;News Aggregator&lt;/title&gt;
</head> <body>
&lt;h1&gt;News Aggregator&lt;/h1&gt;
&lt;form method="get"&gt;
    &lt;input type="text" name="query" placeholder="Search news..." value="{{ query }}"&gt;
    &lt;button type="submit"&gt;Search&lt;/button&gt;
&lt;/form&gt;
&lt;ul&gt;
    {% for article in articles %}
        &lt;li&gt;
            &lt;a href="{{ article.url }}" target="_blank"&gt;{{ article.title }}&lt;/a&gt;
            &lt;p&gt;{{ article.description }}&lt;/p&gt;
        &lt;/li&gt;
    {% else %}
        &lt;li&gt;No articles found.&lt;/li&gt;
    {% endfor %}
&lt;/ul&gt;
</body> </html>

Step 4: Run Your Application

To run your application, execute the following command in your terminal:

bashCopy codepython app.py

Step 5: Access Your News Aggregator

Open your web browser and go to http://127.0.0.1:5000/. You can enter a search query to fetch news articles related to that query.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *