News App (API) in Python.
About the project: This is the project for a News App that uses an API to fetch real-time news headlines.
This program will allow you to get the latest news headlines from a public news API for a specific country and category.
It will fetch the data, parse the JSON response, and display the headlines and their sources in your console.
Before you run the code:
- Get an API Key: You'll need a free API key from a news service. A good option is NewsAPI.org.
- Go to https://newsapi.org/
- Sign up for a free developer account.
- Your API key will be displayed on your dashboard.
- Install requests library: Open your terminal or command prompt and run:
pip install requests
How to use this program:
- Save the code: Save the code below as a Python file (e.g., news_app.py).
- Get your API Key: Visit NewsAPI.org, sign up for a free account, and get your API key.
- Insert API Key: Open the news_app.py file and replace 'YOUR_API_KEY' with the actual API key you obtained.
- Install requests: If you haven't already, install the requests library by running pip install requests in your terminal.
- Run the script: Open your terminal or command prompt, navigate to the directory where you saved the file, and run:
python news_app.py
The program will then prompt you to enter a country code and a category, fetch the top headlines, and display them for you.
Project Level: Intermediate
You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.
Steps: Follow these stepsStep 1: Copy below code using green 'copy' button.
Step 2: Paste the code on your chosen editor.
Step 3: Save the code with filename and .py extention.
Step 4: Run (Press F5 if using python IDLE)
# news_app.py
import requests
import json
# IMPORTANT: Replace 'YOUR_API_KEY' with your actual NewsAPI key
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://newsapi.org/v2/top-headlines?"
def get_top_headlines(country='us', category='general'):
"""
Fetches top news headlines for a given country and category.
Args:
country (str): The 2-letter country code (e.g., 'us', 'gb', 'in').
category (str): The news category (e.g., 'business', 'technology', 'sports').
Returns:
dict or None: A dictionary containing news articles if successful, None otherwise.
"""
complete_url = f"{BASE_URL}country={country}&category={category}&apiKey={API_KEY}"
try:
response = requests.get(complete_url, timeout=10)
response.raise_for_status() # Raise an HTTPError for bad responses
data = response.json()
if data["status"] == "ok":
return data
else:
print(f"Error: {data.get('message', 'Could not retrieve news.')}")
return None
except requests.exceptions.RequestException as e:
print(f"Network error or invalid request: {e}")
return None
except json.JSONDecodeError:
print("Error: Could not decode JSON response from API.")
return None
def display_headlines(news_data):
"""
Displays the extracted news headlines and sources.
"""
if news_data is None or not news_data['articles']:
print("No articles found.")
return
print("\n--- Top Headlines ---")
for i, article in enumerate(news_data['articles']):
title = article.get('title', 'No Title')
source = article['source'].get('name', 'Unknown Source')
url = article.get('url', 'No URL')
print(f"{i+1}. {title}")
print(f" Source: {source}")
print(f" Link: {url}")
print("-" * 20)
print("---------------------")
def main():
"""
Main function to run the News App.
"""
if API_KEY == "YOUR_API_KEY":
print("WARNING: Please replace 'YOUR_API_KEY' in the script with your actual NewsAPI key.")
print("You can get a free API key from https://newsapi.org/")
return
print("--- Python News App ---")
print("Get the latest news headlines from around the world.")
print("Type 'q' to quit at any time.")
while True:
country = input("\nEnter the 2-letter country code (e.g., us, gb, in): ").strip().lower()
if country == 'q':
print("Exiting News App. Goodbye!")
break
category = input("Enter a news category (e.g., business, technology, sports, general): ").strip().lower()
if category == 'q':
print("Exiting News App. Goodbye!")
break
if not country or not category:
print("Country and category cannot be empty.")
continue
news_data = get_top_headlines(country, category)
if news_data:
display_headlines(news_data)
# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
main()
← Back to Projects
