How Can You Build an AI News Aggregator with Flask & Vercel for Free? πŸ“°

13

πŸš€ Want to create a fully automated news website? This tutorial will teach you how to:
 βœ… Scrape & rank trending news using AI
 βœ… Fetch full articles (headings, images, links)
 βœ… Host your API for free on Vercel
 βœ… Load API keys securely from .env

Let’s build your AI-powered news API from scratch! πŸ”₯


πŸ“Œ Step 1: Install Dependencies

First, install the required Python libraries:

pip install flask requests newspaper3k beautifulsoup4 python-dotenv nltk textblob

We’ll use:


πŸ“Œ Step 2: Get a Free NewsAPI Key

1️⃣ Go to https://newsapi.org/
 2️⃣ Sign up & get your API key

Now, let’s store it securely in a .env file.


πŸ“Œ Step 3: Load API Key from .env

Create a .env file in your project folder:

NEWS_API_KEY=your_news_api_key

Now, modify your Flask app to load this key securely:

import os
from dotenv import load_dotenv
# Load API Key from .env
load_dotenv()
NEWS_API_KEY = os.getenv("NEWS_API_KEY")

βœ… Now, your API key isn’t exposed in the code!


πŸ“Œ Step 4: Build the Flask API

βœ… 1. Fetch & Rank Trending News

from flask import Flask, jsonify, request
import requests
import json
from bs4 import BeautifulSoup
from datetime import datetime
import nltk
from textblob import TextBlob
from dotenv import load_dotenv
import os
nltk.download('punkt')
app = Flask(__name__)
# Load API Key
load_dotenv()
NEWS_API_KEY = os.getenv("NEWS_API_KEY")
# Function to fetch news
def fetch_news():
    url = f"https://newsapi.org/v2/top-headlines?country=us&category=general&apiKey={NEWS_API_KEY}"
    response = requests.get(url)
    data = response.json()
    return data.get("articles", [])
# Function to analyze sentiment
def analyze_sentiment(text):
    analysis = TextBlob(text)
    return analysis.sentiment.polarity  # Returns score from -1 to 1
# Function to scrape full article content
def get_full_article(url):
    try:
        response = requests.get(url, headers={"User-Agent": "Mozilla/5.0"})
        soup = BeautifulSoup(response.content, "html.parser")
        # Extract Title
        title = soup.find("h1").get_text() if soup.find("h1") else ""
        # Extract Headings
        headings = [h.get_text() for h in soup.find_all(["h2", "h3"])]
        # Extract Paragraphs
        paragraphs = [p.get_text() for p in soup.find_all("p")]
        # Extract Images
        images = [img["src"] for img in soup.find_all("img") if "src" in img.attrs]
        # Extract Links
        links = [a["href"] for a in soup.find_all("a", href=True)]
        # Construct structured article
        full_article = {
            "title": title,
            "headings": headings,
            "content": "\n".join(paragraphs),
            "images": images,
            "links": links
        }
        return full_article
    except Exception as e:
        return {"error": f"Failed to scrape article: {str(e)}"}
# API to Get Top Ranked News
@app.route('/api/news', methods=['GET'])
def get_news():
    articles = fetch_news()
    ranked_news = sorted(articles, key=lambda x: analyze_sentiment(x["title"]), reverse=True)
    return jsonify(ranked_news[:5])  # Return top 5 news articles
# API to Fetch Full Article
@app.route('/api/full-article', methods=['GET'])
def get_full_news():
    url = request.args.get("url")
    if not url:
        return jsonify({"error": "URL parameter is required"}), 400
    full_article = get_full_article(url)
    return jsonify(full_article)
# Run Flask App
if __name__ == '__main__':
    app.run(debug=True)

πŸ“Œ Step 5: Test Your API Locally

Run the Flask app:

python app.py

Now, visit:


πŸš€ Deploy to Vercel for FREE

Now, let’s deploy our API on Vercel so anyone can access it online!

πŸ“Œ Step 6: Install Vercel CLI

npm install -g vercel

πŸ“Œ Step 7: Create vercel.json

Create a vercel.json file in your project:

{
  "version": 2,
  "builds": [{ "src": "app.py", "use": "@vercel/python" }],
  "routes": [{ "src": "/(.*)", "dest": "app.py" }]
}

πŸ“Œ Step 8: Deploy to Vercel

1️⃣ Login to Vercel

vercel login

2️⃣ Deploy your Flask API

vercel

βœ… Your API is now live on a URL like:
 πŸ‘‰ https://your-news-api.vercel.app/api/news


πŸ”₯ Final Thoughts

🎯 Now you have a fully automated AI-powered news API!
 βœ… Fetches trending news
 βœ… Extracts full articles (headings, images, links)
 βœ… Loads API key securely from .env
 βœ… Deployed for free on Vercel!


πŸš€ What’s Next?

πŸ’¬ Want help integrating this into a Next.js frontend? Let me know! πŸš€

AIFlaskVercelBackendAPI
Sagar Sangwan

Written by Sagar Sangwan

Code. Write. Build. Explore. πŸ’»βœοΈ Software developer by day, mechanical tinkerer by night. When I’m not shipping code or writing blogs, you’ll find me trekking up a mountain, whipping up a feast, or hitting the open road on two wheels. Life is better in high gear.

Follow

View more blogs by me CLICK HERE

Loading related blogs...

Stay Updated

Subscribe to get the latest posts delivered to your inbox