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>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>News Aggregator</title>
</head>
<body>
    <h1>News Aggregator</h1>
    <form method="get">
        <input type="text" name="query" placeholder="Search news..." value="{{ query }}">
        <button type="submit">Search</button>
    </form>
    <ul>
        {% for article in articles %}
            <li>
                <a href="{{ article.url }}" target="_blank">{{ article.title }}</a>
                <p>{{ article.description }}</p>
            </li>
        {% else %}
            <li>No articles found.</li>
        {% endfor %}
    </ul>
</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 *