News API in Python: search, paginate and retry

To get news in Python, send a GET request to https://api.worldnewsapi.com/search-news with your key in the x-api-key header and filters such as text, language and earliest-publish-date. Each request returns up to 100 articles and costs 1 point plus 0.01 points per article, so a full page of 100 costs 2 points. This guide builds a small requests client with filters, pagination and retries on 429, then shows the same search with the official worldnewsapi SDK, for about 8 points in total.

  • Endpoint: GET https://api.worldnewsapi.com/search-news (reference).
  • Authentication: x-api-key header or api-key query parameter.
  • Page size: number from 1 to 100. Page with offset (the parameter schema allows up to 10,000).
  • Cost: 1 point per request plus 0.01 points per returned article.
  • Errors to handle: 402 (free plan: daily points used up) and 429 (too many requests per second or at once).
  • SDK: pip install worldnewsapi, class NewsApi, method search_news().

What you'll build

A file news_client.py with a NewsClient class that sends your key in a header, waits 1 second between requests, retries 429 responses with growing delays, stops cleanly on 402, and a search_all() function that collects as many articles as you ask for, 100 at a time. At the end you will run the same search with the SDK.

Prerequisites

  • Python 3.9 or newer.
  • A free API key from the console. Confirm your email address first: the API stays closed until you do. See the free API key guide for what the free plan includes.
  • The requests package.

Step 1: Install requests and store your key

pip install requests
export WORLD_NEWS_API_KEY="YOUR_API_KEY"

Keeping the key in an environment variable keeps it out of your code and out of Git. The terms ask you to keep the key confidential and remove it before you post code anywhere.

Step 2: Make your first request

import os
from datetime import date, timedelta

import requests

API_KEY = os.environ.get("WORLD_NEWS_API_KEY", "YOUR_API_KEY")
since = (date.today() - timedelta(days=7)).isoformat()

response = requests.get(
    "https://api.worldnewsapi.com/search-news",
    headers={"x-api-key": API_KEY},
    params={
        "text": "earthquake",
        "language": "en",
        "earliest-publish-date": since,
        "number": 10,
    },
    timeout=30,
)
response.raise_for_status()
data = response.json()

print(data["available"], "matching articles")
for article in data["news"]:
    print(article["publish_date"], article["title"])
    print("   ", article["url"])
print("Points used:", response.headers.get("X-API-Quota-Request"))
print("Points left today:", response.headers.get("X-API-Quota-Left"))

The header is the safer place for the key: the authentication docs recommend it for production because it keeps the key out of server logs and browser history. requests encodes the dashed parameter names for you.

Example response (shortened), from the Search News docs for text=earth+quake&language=en&earliest-publish-date=2024-04-01. Your results will be newer.

{
  "offset": 0,
  "number": 10,
  "available": 83,
  "news": [
    {
      "id": 206030983,
      "title": "Nearly 30 aftershocks recorded around NJ quake epicenter since Friday",
      "text": "New Jersey continues to shake after Friday’s 4.8-magnitude earthquake ...",
      "summary": "Twenty nine areas around Whitehouse Station, NJ, ...",
      "url": "https://nypost.com/2024/04/06/us-news/nearly-30-aftershocks-recorded-around-nj-quake-epicenter/",
      "image": "https://nypost.com/wp-content/uploads/sites/2/2024/04/79582612.jpg?quality=75&strip=all&w=1200",
      "video": "https://cdn.jwplayer.com/videos/70lDQJpg-RyIcpnTz.mp4",
      "publish_date": "2024-04-06 22:44:18",
      "authors": ["Deirdre Bardolf"],
      "category": "environment",
      "language": "en",
      "source_country": "us",
      "sentiment": -0.545
    }
  ]
}

available is the total number of matches. If it reads 100000, there are at least that many and you should narrow the query.

Step 3: Add filters

You can combine as many filters as you like, but you must set at least one. These are the ones most scripts need:

ParameterExampleWhat it does
texttesla (model OR mustang) -ford3 to 100 characters. Terms are joined with AND, uppercase OR matches either, - excludes, quotes match a phrase. No wildcards.
text-match-indexestitleSearch only titles, only content, or both (default).
languageen2-letter language code.
source-countryus2-letter country code of the source.
categoriesbusiness,technology13 categories. The docs warn it can leave out news, especially outside English.
entitiesORG:Tesla,PER:Elon MuskMatch people, organizations and places by semantic type, whatever name the article uses.
news-sourcesbbc.com,cnbc.comUp to 10 sources. More are rejected with HTTP 400.
min-sentiment, max-sentiment-0.8, 0.8Sentiment range in [-1, 1].
earliest-publish-date, latest-publish-date2026-11-15Publish date window. The free plan covers the last month.
sort, sort-directionpublish-time, DESCNewest or oldest first.
params = {
    "text": "tesla (model OR mustang) -ford",
    "text-match-indexes": "title",
    "language": "en",
    "source-country": "us",
    "earliest-publish-date": since,
    "sort": "publish-time",
    "sort-direction": "DESC",
    "number": 100,
}

One rule to know: if you sort by publish-time, set text or both publish dates. Otherwise the API limits the time range to the last 31 days.

Step 4: Build a client with retries

Save this as news_client.py. It spaces requests 1 second apart (the free plan allows 1 request per second and 1 at a time), retries 429 up to 5 times with delays of 2, 4, 8, 16 and 32 seconds plus jitter, and raises a clear error on 401 and 402.

import os
import random
import time

import requests

BASE_URL = "https://api.worldnewsapi.com"


class QuotaExhausted(Exception):
    """HTTP 402: today's points are used up (free plan)."""


class NewsClient:
    def __init__(self, api_key=None, max_retries=5, min_interval=1.0):
        self.session = requests.Session()
        self.session.headers["x-api-key"] = api_key or os.environ.get("WORLD_NEWS_API_KEY", "YOUR_API_KEY")
        self.max_retries = max_retries
        self.min_interval = min_interval  # seconds between requests
        self.quota_left = None
        self._last_request = 0.0

    def get(self, path, params):
        attempt = 0
        while True:
            pause = self.min_interval - (time.monotonic() - self._last_request)
            if pause > 0:
                time.sleep(pause)
            self._last_request = time.monotonic()
            response = self.session.get(f"{BASE_URL}/{path}", params=params, timeout=30)
            self.quota_left = response.headers.get("X-API-Quota-Left", self.quota_left)

            if response.status_code == 429 and attempt < self.max_retries:
                attempt += 1
                time.sleep(min(60, 2 ** attempt) + random.uniform(0, 1))
                continue
            if response.status_code == 402:
                raise QuotaExhausted("Daily points used up. The quota resets at midnight UTC.")
            if response.status_code == 401:
                raise PermissionError("401 Unauthorized: check WORLD_NEWS_API_KEY.")
            response.raise_for_status()
            return response.json()

    def search(self, **filters):
        """Python names use underscores, the API uses dashes: source_country becomes source-country."""
        params = {name.replace("_", "-"): value for name, value in filters.items()}
        return self.get("search-news", params)

The docs do not mention a Retry-After header, so the client uses its own delays.

Step 5: Paginate with offset and number

Add this to news_client.py. It asks for 100 articles per request, moves offset forward by what came back, and stops when it has enough, when the API runs out of matches, or at the offset limit.

def search_all(client, max_results=300, **filters):
    """Collect up to max_results articles, 100 per request."""
    articles = []
    offset = 0
    while len(articles) < max_results and offset <= 10000:
        number = min(100, max_results - len(articles))
        page = client.search(offset=offset, number=number, **filters)
        news = page.get("news", [])
        articles.extend(news)
        offset += len(news)
        if not news or offset >= page.get("available", 0):
            break
    return articles


if __name__ == "__main__":
    from datetime import date, timedelta

    client = NewsClient()
    try:
        articles = search_all(
            client,
            max_results=300,
            text="electric vehicles",
            language="en",
            source_country="us",
            earliest_publish_date=(date.today() - timedelta(days=7)).isoformat(),
            sort="publish-time",
            sort_direction="DESC",
        )
    except QuotaExhausted as error:
        print(error)
    else:
        print(len(articles), "articles. Points left today:", client.quota_left)

Run it with python news_client.py. 300 articles take 3 requests of 2 points each. Do not fetch pages in parallel threads on the free plan: it allows 1 concurrent request, and extra ones come back as 429.

Step 6: Use the official SDK

The worldnewsapi package is generated from the OpenAPI file. It returns typed objects instead of dictionaries. This example sends the key as the x-api-key header (the headerApiKey setting); apiKey would send it as a query parameter instead.

pip install worldnewsapi
import os

import worldnewsapi
from worldnewsapi.rest import ApiException

configuration = worldnewsapi.Configuration(
    api_key={"headerApiKey": os.environ.get("WORLD_NEWS_API_KEY", "YOUR_API_KEY")}
)

with worldnewsapi.ApiClient(configuration) as api_client:
    news_api = worldnewsapi.NewsApi(api_client)
    try:
        response = news_api.search_news(
            text="electric vehicles",
            language="en",
            source_country="us",
            sort="publish-time",
            sort_direction="DESC",
            offset=0,
            number=10,
        )
    except ApiException as error:
        print("Request failed with HTTP status", error.status)
    else:
        print(response.available, "matching articles")
        for article in response.news:
            print(article.publish_date, article.title, article.url)

Each endpoint has one method on NewsApi. Add _with_http_info to a method name (for example search_news_with_http_info) to also get the status code and response headers.

EndpointSDK methodPoints
/search-newssearch_news()1 + 0.01 per result
/top-newstop_news() (the date argument is var_date)1
/retrieve-newsretrieve_news_articles_by_ids()0.1 per article
/extract-newsextract_news()2, plus 2 with analyze
/feed.rssnews_website_to_rss_feed()1, plus 0.5 per item with extract-news
/retrieve-front-pageretrieve_newspaper_front_page()1 (not on the free plan)

Error handling

StatusWhat it meansWhat to do
401 UnauthorizedListed for every endpoint in the OpenAPI file. The docs say nothing more about it.Check the key first: right header name (x-api-key) or parameter (api-key), no spaces, email address confirmed.
402 Payment RequiredOn the free plan, today's points are used up (quota docs).Do not retry. Wait for the reset at midnight UTC or upgrade.
429 Too Many RequestsMore requests per second, or more at the same time, than your plan allows.Wait and retry with growing delays. Send 1 request at a time on the free plan.
400The request is invalid, for example more than 10 news-sources.Fix the parameters. Retrying will not help.

With the SDK, all of these arrive as ApiException; read error.status to tell them apart.

What this guide costs

StepRequestsPoints
Step 2: first search, 10 results11.1
Step 5: 300 articles36
Step 6: SDK search, 10 results11.1
Total58.2 of the free plan's 50 daily points

Next steps

Frequently asked questions

Is there an official Python SDK for World News API?

Yes. Install it with pip install worldnewsapi, create a worldnewsapi.NewsApi object and call search_news(). It is generated from the OpenAPI file. Plain requests calls work just as well and need no extra package.

How do I get more than 100 news articles in Python?

Each request returns at most 100 articles, set with the number parameter. Move the offset parameter forward by the number of articles you received and repeat until you have enough or offset reaches the available count. Each full page of 100 costs 2 points.

How should I handle 429 errors?

Wait and retry with growing delays, for example 2, 4, 8 and 16 seconds plus a random fraction. The free plan allows 1 request per second and 1 request at a time, so space your calls at least 1 second apart and do not run them in parallel.

What does a 402 error mean?

On the free plan, 402 means today's 50 points are used up. Requests keep failing until the quota resets at midnight UTC, so retrying sooner does not help.

Last updated November 22, 2026 by the World News API team. Spotted an error? Tell us at [email protected] or on Discord.

More from World News API

  • Compare news APIs
    World News API next to NewsAPI.org, NewsData.io, GNews, Mediastack and others.
  • Guides
    Step-by-step tutorials with working code.
  • Use cases
    AI agents, finance, media monitoring and research.
  • Documentation
    Every endpoint with parameters, examples and quotas.

Get a free API key