This Python program gets the latest news headlines from the NewsAPI service and prints each headline title with its publication date.
This project uses NewsAPI.org.
Endpoint used: https://newsapi.org/v2/top-headlines
Make sure Python is installed on your computer.
You also need the requests library.
Run this command in the terminal:
python -m pip install requests- Go to https://newsapi.org/
- Create an account or log in
- Copy your API key from your dashboard
This project uses an environment variable named NEWS_API_KEY.
Run this in the terminal:
export NEWS_API_KEY="your_actual_api_key_here"Run this in PowerShell:
$env:NEWS_API_KEY="your_actual_api_key_here"In the terminal, run:
python latest_news.py- Sends a GET request to the NewsAPI top headlines endpoint
- Checks if the request was successful
- Reads the JSON response
- Prints the headline title and publication date
- Prints the total number of headlines shown
The program handles these common problems:
- Missing API key
- Request failure
- JSON parsing errors
- No articles returned
If the API key is missing, the program prints:
API key not found. Please set your API key.
Do not upload your real API key to GitHub.
If you use a file like config.py for your key instead of an environment variable, add config.py to .gitignore.