DEV Community

Currents API
Currents API

Posted on Originally published at currentsapi.services AI-assisted

How to Fetch News Data in Python Using Currents API

If you're building an application that needs real-time or historical news data, a news API is the fastest way to get started. In this tutorial, we'll walk through how to fetch news in Python using the Currents News API and its official Python SDK.

Currents provides 250 free requests per day (no credit card required), making it ideal for prototyping and small projects. By the end of this guide, you'll be able to:

  • Install the official Python SDK
  • Fetch the latest headlines
  • Search the archive (30 days back on the free plan, up to 1 year on paid plans)
  • Filter by language, country, category, and date range
  • Handle errors gracefully

Prerequisites

  • Python 3.8 or higher installed
  • A free Currents API account (sign up here)

Step 1: Get Your API Key

After signing up, grab your API key from the dashboard. You'll need this to authenticate every request.

Store it as an environment variable (recommended for security):

export CURRENTS_API_KEY="your-api-key-here"
Enter fullscreen mode Exit fullscreen mode

Step 2: Install the SDK

The official Python SDK is available on PyPI:

pip install currentsapi python-dateutil
Enter fullscreen mode Exit fullscreen mode

python-dateutil is a dependency the SDK uses for parsing date strings. It's included automatically when you install currentsapi, but explicit installation ensures you have it.


Step 3: Fetch the Latest News

Create a file called latest_news.py:

import os
from currentsapi import CurrentsAPI

# Load API key from environment variable
api_key = os.environ.get("CURRENTS_API_KEY")
api = CurrentsAPI(api_key=api_key)

# Fetch latest English news
response = api.latest_news(language="en")

# Print headlines
for article in response["news"]:
    print(f"- {article['title']}")
    print(f"  {article['url']}\n")
Enter fullscreen mode Exit fullscreen mode

Run it:

python latest_news.py
Enter fullscreen mode Exit fullscreen mode

The output looks like this (your headlines will differ):

- Chipmaker expands data-center investment
  https://example.com/business/chipmaker-expands

- Global climate summit reaches new agreement
  https://example.com/world/climate-summit
Enter fullscreen mode Exit fullscreen mode

What's happening here?

The CurrentsAPI client handles authentication for you. The latest_news() method calls the /v1/latest-news endpoint and returns a Python dictionary with the parsed JSON response. The news key contains a list of articles, each with title, description, url, author, image, language, category, and published fields.


Step 4: Search the Archive

The search() method searches the archive with keyword, date, and filter support. How far back you can search depends on the plan: 30 days on Free, 6 months on Builder, and 1 year on Professional and Scale.

Create search_news.py:

import os
from currentsapi import CurrentsAPI

api_key = os.environ.get("CURRENTS_API_KEY")
api = CurrentsAPI(api_key=api_key)

# Search for AI-related articles in English
response = api.search(
    keywords="artificial intelligence",
    language="en",
    country="US",
    category="technology"
)

print(f"Found {len(response['news'])} articles\n")

for article in response["news"][:5]:
    print(f"- {article['title']}")
    print(f"  Published: {article['published']}")
    print(f"  {article['url']}\n")
Enter fullscreen mode Exit fullscreen mode

Available search parameters

Parameter Type Description Example
keywords string Search terms "Bitcoin", "climate change"
language string 2-letter language code "en", "es", "de"
country string 2-letter country code "US", "GB", "JP"
category string Article category "technology", "business"
start_date string/date Search after this date "2026-01-01" or datetime.date(2026, 1, 1)
end_date string/date Search before this date "2026-04-01" or datetime.date(2026, 4, 1)

The SDK accepts dates as either ISO-formatted strings or Python datetime.date objects. The _parse_date helper converts them to the RFC 3339 format the API expects.


Step 5: Date-Range Search

One of the SDK's most useful features is flexible date handling. Here's how to search for articles from the past 7 days. Each search request can cover up to 7 days on the free plan and up to 31 days on Builder, so split longer ranges into several requests:

import os
from datetime import datetime, timedelta
from currentsapi import CurrentsAPI

api_key = os.environ.get("CURRENTS_API_KEY")
api = CurrentsAPI(api_key=api_key)

# Calculate date range
end = datetime.now()
start = end - timedelta(days=7)

# Search articles from the last 7 days
response = api.search(
    keywords="electric vehicles",
    language="en",
    start_date=start,
    end_date=end
)

print(f"Found {len(response['news'])} articles\n")
for article in response["news"][:3]:
    print(f"- {article['title']} ({article['published'][:10]})")
Enter fullscreen mode Exit fullscreen mode

Step 6: Discover Available Languages, Regions, and Categories

The SDK includes helper methods to discover valid filter values:

import os
from currentsapi import CurrentsAPI

api_key = os.environ.get("CURRENTS_API_KEY")
api = CurrentsAPI(api_key=api_key)

# List available languages
languages = api.available_languages()
print(f"Available languages: {len(languages['languages'])}")
# Output: Available languages: 34

# List available regions
regions = api.available_regions()
print(f"Available regions: {len(regions['regions'])}")

# List available categories (V2 canonical taxonomy)
categories = api.available_category()
print("Categories:", ", ".join(categories['categories']))
# Output: Categories: general, society, science_technology, politics_government, ...
Enter fullscreen mode Exit fullscreen mode

Use these values to populate dropdown menus in your application or validate user input before making API calls.


Step 7: Error Handling

The SDK raises a CurrentsAPIError when the API returns a non-200 status. Always wrap your calls:

import os
from currentsapi import CurrentsAPI, CurrentsAPIError

api_key = os.environ.get("CURRENTS_API_KEY")
api = CurrentsAPI(api_key=api_key)

try:
    response = api.latest_news(language="en")
    for article in response["news"]:
        print(article["title"])

except CurrentsAPIError as e:
    print(f"API Error: {e.message}")
    print(f"Status: {e.status}")
    print(f"Code: {e.code}")

except Exception as e:
    print(f"Unexpected error: {e}")
Enter fullscreen mode Exit fullscreen mode

Common error codes

Code Cause Fix
401 Invalid or missing API key Check your API key in the dashboard
429 Rate limit exceeded Wait and retry, or upgrade your plan
500 Server error Retry with exponential backoff

Step 8: Putting It Together: A News Aggregator Script

Here's a complete script that fetches technology news from the US and UK, deduplicates by URL, and saves to a JSON file:

import os
import json
from datetime import datetime, timedelta
from currentsapi import CurrentsAPI, CurrentsAPIError

def fetch_tech_news():
    api_key = os.environ.get("CURRENTS_API_KEY")
    api = CurrentsAPI(api_key=api_key)

    all_articles = []
    countries = ["US", "GB"]

    for country in countries:
        try:
            response = api.latest_news(
                language="en",
                country=country,
                category="technology"
            )
            all_articles.extend(response["news"])
            print(f"Fetched {len(response['news'])} articles from {country}")

        except CurrentsAPIError as e:
            print(f"Error fetching {country}: {e.message}")

    # Deduplicate by URL
    seen = set()
    unique = []
    for article in all_articles:
        if article["url"] not in seen:
            seen.add(article["url"])
            unique.append(article)

    # Save to JSON file
    filename = f"tech_news_{datetime.now().strftime('%Y-%m-%d')}.json"
    with open(filename, "w") as f:
        json.dump(unique, f, indent=2)

    print(f"\nSaved {len(unique)} unique articles to {filename}")

if __name__ == "__main__":
    fetch_tech_news()
Enter fullscreen mode Exit fullscreen mode

Rate Limits and Best Practices

  • Free tier: 250 requests/day (no credit card)
  • Builder: 75,000 requests/month (2,500/day)
  • Professional: 300,000 requests/month (10,000/day)
  • Scale: 600,000 requests/month (20,000/day)

The daily cap resets at 00:00 UTC. Going over it returns HTTP 429 until the reset, with no overage billing.

Track your usage in the dashboard. The SDK has a default 30-second timeout, which you can override:

api = CurrentsAPI(api_key=api_key, timeout=60)
Enter fullscreen mode Exit fullscreen mode

Next Steps

Now that you can fetch news in Python, you might want to:

  • Build a news dashboard with Streamlit or Flask
  • Set up scheduled fetching with cron or APScheduler
  • Add NLP analysis with spaCy or Hugging Face transformers
  • Store results in a database (PostgreSQL, MongoDB) for long-term analysis

For more details, check out the full API documentation or browse the Python SDK source on GitHub.


Ready to start? Create your free Currents account and get 250 daily requests on the free news API with no credit card required.

This post first appeared on the Currents API blog.

Top comments (0)