Glasser Team9 min read
How to Use a News API with Python
Query NewsAPI with Python, save attributable article records, and understand when a Google News endpoint through Glasser fits your task.

Choose the news source your Python code needs
To use NewsAPI.org with Python, send a request to its /v2/everything endpoint or use the newsapi-python client. Start with one topic, a short date window, and a fixed page limit so you can inspect the articles before scheduling a larger job.
The service name matters. NewsAPI.org, NewsAPI.ai, and services that retrieve Google News have separate accounts, interfaces, and coverage. Installing one Python package does not connect you to all three.
| Your task | Suitable starting point | Check before implementation |
|---|---|---|
| Query articles through an existing NewsAPI.org account | NewsAPI V2 over HTTP or its Python wrapper | Account plan, date window and permitted use |
| Retrieve Google News results for a topic | A documented Google News data endpoint | Actual provider, locale, time coverage and returned fields |
| Supply an agent with general web evidence | A web search endpoint | Whether you need news specifically or broader sources |
This guide uses NewsAPI.org for the runnable Python example. Its official Python client page identifies newsapi-python as an unofficial client. The Google News path appears separately below, with its own input and limits.
Need a small news dataset before building the Python integration? Explore Glasser's news endpoints, choose a source, and inspect its coverage and price before requesting articles.
Make a bounded NewsAPI request with Python
Install Requests and keep your API key outside the code
Use a virtual environment and install the HTTP library:
python -m venv .venv
source .venv/bin/activate
python -m pip install requests
On Windows, activate .venv\Scripts\activate. Set NEWSAPI_KEY in your local environment or secret manager; the script reads it at runtime.
The Everything endpoint documentation defines the query, language, date and pagination fields. Save this author-written example as fetch_news.py:
import json
import os
from datetime import datetime, timedelta, timezone
from pathlib import Path
import requests
def fetch_articles(api_key, query, start, end, max_pages=2):
articles = []
page_size = 20
for page in range(1, max_pages + 1):
response = requests.get(
"https://newsapi.org/v2/everything",
headers={"X-Api-Key": api_key},
params={
"q": query,
"from": start,
"to": end,
"language": "en",
"sortBy": "publishedAt",
"pageSize": page_size,
"page": page,
},
timeout=30,
)
response.raise_for_status()
data = response.json()
if data.get("status") != "ok":
raise RuntimeError(f"NewsAPI error: {data.get('code', 'unknown')}")
batch = data.get("articles")
if not isinstance(batch, list):
raise ValueError("Expected an articles list")
articles.extend(batch)
if len(batch) < page_size:
break
return articles
if __name__ == "__main__":
now = datetime.now(timezone.utc)
records = fetch_articles(
api_key=os.environ["NEWSAPI_KEY"],
query='"battery recycling"',
start=(now - timedelta(days=7)).isoformat(),
end=(now - timedelta(days=2)).isoformat(),
)
Path("news-raw.json").write_text(
json.dumps(records, ensure_ascii=False, indent=2), encoding="utf-8"
)
print(f"Saved {len(records)} article records")
Run python fetch_news.py. The example requests at most two pages of twenty articles. Its end time leaves room for a delayed development feed; adjust the interval to your plan and task. If the second request fails, the function raises an error and the script does not write a misleading complete result file.
The timeout and page cap are application choices. Requests documents HTTP errors, JSON decoding and timeouts; a timeout limits network waiting behavior and is not a strict deadline for the entire multi-page job.
Use the Python client when you prefer SDK methods
The same service can be called through newsapi-python. Install the documented package with python -m pip install newsapi-python==0.2.7, then use its client:
import os
from newsapi import NewsApiClient
client = NewsApiClient(api_key=os.environ["NEWSAPI_KEY"])
data = client.get_everything(
q='"battery recycling"',
language="en",
sort_by="publishedAt",
page_size=20,
page=1,
)
articles = data["articles"]
Version 0.2.7 is the release checked on PyPI for this guide. Notice the wrapper's sort_by and page_size names; the HTTP API uses sortBy and pageSize. Apply the same account and result-quality checks whichever interface you choose.
The examples were reviewed against current documentation and checked with local fixtures. We did not run a live NewsAPI account test or measure news coverage.
When should you use Google News through Glasser?
Choose this path when the task specifically needs Google News discovery or when an agent should retrieve a small article set through an existing Glasser connection.
Glasser's Google News Articles by Keyword endpoint, provided by Apify, describes up to ten US English articles from the last seven days for one keyword. Its website snapshot lists title, URL, source and publication time as the intended data. It publishes no fixed output schema, so inspect the returned payload before writing a parser.
For a compatible local agent, follow the Glasser setup guide with:
set up https://glasser.ai/SKILL.md
Then give the agent a bounded task:
Find the Apify Google News Articles by Keyword endpoint in Glasser.
Inspect its current input, coverage, price and outcome charges.
Show me those terms before running one query for "battery recycling".
Keep the returned article links, sources and publication times where present.
This endpoint's documented input contains one keyword string inside keywords. NewsAPI parameters such as pageSize, from or language cannot be assumed to work here. The snapshot describes asynchronous execution; follow the current Run instructions when collecting its result.
Use this as a small discovery sample. A ten-record result does not establish that every relevant article was found, and an empty result does not prove that no publisher covered the topic.
Turn article responses into a reliable news feed
Keep publisher identity and retrieval time
After the first response, decide what your application needs to retain. For the NewsAPI example, this author-defined mapping preserves the source record while adding collection time:
def normalize_article(article, retrieved_at):
source = article.get("source") or {}
return {
"title": article.get("title"),
"url": article.get("url"),
"source_name": source.get("name"),
"published_at": article.get("publishedAt"),
"description": article.get("description"),
"retrieved_at": retrieved_at,
}
retrieved_at belongs to your application. Keep it separate from publication time so a freshly downloaded old article cannot pass a freshness check.
Retain the raw response alongside normalized records. For a simple first pass, detect exact duplicate URLs and mark records without a usable source link for review. Different URLs can still describe the same event; event clustering requires a separate policy and should preserve the original articles.
Keep failed retrievals visible
| Outcome | Application action |
|---|---|
| Successful response with no articles | Record a completed search with zero matches for that query and interval |
| HTTP 401 or invalid-key error | Check the credential; do not label the search empty |
| HTTP 429, exhausted quota or rate limit | Inspect the account and error code before scheduling another request |
| Timeout, invalid JSON or unexpected response structure | Record a failed collection attempt and retain diagnostic context |
NewsAPI documents its HTTP statuses and error codes. The example leaves these failures visible and adds no automatic retry loop. If you introduce retries or checkpoints, define their limits and account for additional requests.
For Glasser, follow its Run result model: check status, provider response and final charge separately. A completed Run can contain a provider error; the native NewsAPI code above is not a parser for Glasser Runs.
Check free access, freshness, and task cost
NewsAPI's Developer plan, checked October 14, 2026, lists 100 requests per day, a 24-hour article delay and a one-month search window. Its permitted use is development and testing; staging and production require an appropriate subscription. These conditions make it a development option, with limits that matter for a monitoring product.
For your own schedule, calculate requests before estimating records:
requests per day = topics × runs per topic × pages per run
Five topics, four runs per day and two pages per run produce at most forty requests daily under this example's cap. The number of articles returned can vary, and duplicate records reduce the value of that request volume.
Use the first sample to answer three questions: are the named sources relevant, are the articles recent enough, and do the source pages support the facts your workflow needs? If freshness fails because of a plan delay, changing the Python loop will not resolve it.
Full text is another separate requirement. NewsAPI's documentation describes truncated content, and its pricing FAQ says full article content is not supplied. A summary should remain tied to the publisher URL; obtaining and storing full text requires a suitable access path and rights for your use.
Ready to compare a Google News sample with your current feed? Start in Glasser, inspect one news endpoint and its terms, then review the actual articles before scheduling repeated calls.
Questions about news APIs in Python
Is newsapi-python the official Python package for every news API?
It is an unofficial client for NewsAPI.org. Other providers use their own interfaces, credentials and output formats.
Can the example retrieve Google News results?
The runnable example queries NewsAPI.org. For Google News discovery, use a documented Google News data service and check its actual provider and coverage.
Can I use the free NewsAPI plan for a production news dashboard?
The Developer plan is limited to development and testing. Check the current production subscription and freshness terms before deploying a dashboard or internal production job.
Does an empty article list mean no news exists?
It means that this successful request returned no matching records within its selected scope. Other sources, languages, dates or coverage may produce different results.
Can I use the same parser for NewsAPI and Glasser?
Build the parser against the selected endpoint's actual response. The NewsAPI fields shown here do not establish the shape of a Google News response returned through Glasser.
Related posts
View more
8 min read
How to Add Reliable Web Search to Your AI Agent
Connect your AI agent through the Glasser Skill or MCP, cut repeated searches, and verify sources, Run results, and costs before relying on an answer.

8 min read
Free Web Search APIs: Which Should Your AI Agent Use?
Choose a free search API for your AI agent. Compare APIs that return links, page content, or Google results, and estimate the cost after free usage.

6 min read
Dify × Glasser: Bringing Business Data into Your AI Workflows
Bring business data into your Dify workflows with Glasser. Find contacts, research companies, and retrieve search insights without leaving your workflow.
Make your agent
work with real data.
Search, inspect, and run data APIs through one Glasser key. Turn your next question into a result you can use.
Get started with Glasser