newsdataio/newsdataapi
Composer 安装命令:
composer require newsdataio/newsdataapi
包简介
Official PHP client (SDK) for the Newsdata.io News API — fetch real-time, historical, crypto, and stock-market news via REST with validation, retries, and error handling.
README 文档
README
Newsdata.io PHP Client
The official PHP client for the Newsdata.io REST API. It
wraps every endpoint (latest, archive, sources, crypto, market,
count, crypto/count, market/count) with client-side parameter validation,
automatic retries with exponential backoff, and a typed exception hierarchy.
Requirements
PHP 7.3+ with the curl and json extensions.
Installation
With Composer:
composer require newsdataio/newsdataapi
Without Composer, include the bundled autoloader:
require_once '/path/to/php-client/autoload.php';
Quickstart
use NewsdataIO\NewsdataApi; use NewsdataIO\Exception\NewsdataException; $client = new NewsdataApi(NEWSDATA_API_KEY); try { $response = $client->get_latest_news([ 'q' => 'bitcoin', 'country' => ['us', 'gb'], // string or array of strings 'language' => 'en', ]); foreach ($response->results as $article) { echo $article->title, PHP_EOL; } } catch (NewsdataException $e) { echo 'Request failed: ', $e->getMessage(), PHP_EOL; }
Pass ['language' => ['en', 'fr']] and the array is sent comma-separated.
By default the response is decoded to objects; call
$client->setDecodeJsonAsArray(true) to get associative arrays instead.
Endpoints
| Method | Endpoint | Notes |
|---|---|---|
get_latest_news($data) |
/1/latest |
Real-time news |
news_archive($data) |
/1/archive |
Historical news |
news_sources($data) |
/1/sources |
Available sources |
get_crypto_news($data) |
/1/crypto |
Cryptocurrency news |
get_market_news($data) |
/1/market |
Market / financial news |
get_news_count($data) |
/1/count |
Aggregate counts (requires from_date, to_date) |
get_crypto_count($data) |
/1/crypto/count |
Aggregate crypto counts (requires dates) |
get_market_count($data) |
/1/market/count |
Aggregate market counts (requires dates) |
Each $data value may be a single string or an array of strings. Parameter
names are case-insensitive. See the
Newsdata.io documentation — or the
OpenAPI 3.1 spec — for the full
parameter reference per endpoint.
$client->get_market_news(['q' => 'apple', 'symbol' => 'AAPL']); $client->get_news_count([ 'from_date' => '2024-01-01', 'to_date' => '2024-01-31', 'interval' => 'day', ]);
Raw query
To pass a query string or full URL verbatim, use raw_query. It is mutually
exclusive with every other parameter and is validated against the endpoint's
allowed keys:
$client->get_latest_news(['raw_query' => 'q=bitcoin&country=us&language=en']);
Client-side validation
Before any request is sent, parameters are validated and normalized. A
NewsdataValidationError is raised (without spending API quota) when:
- a parameter is not accepted by that endpoint;
- mutually-exclusive parameters are set together —
q/qInTitle/qInMeta,country/excludecountry,category/excludecategory,language/excludelanguage,domain/domainurl/excludedomain; sizeis outside 1–50;sentiment_scoreis set withoutsentiment;- a count endpoint is missing
from_dateorto_date.
Booleans (full_content, image, video, removeduplicate) are coerced to
1 / 0.
Error handling
use NewsdataIO\Exception\NewsdataValidationError; use NewsdataIO\Exception\NewsdataAuthError; use NewsdataIO\Exception\NewsdataRateLimitError; use NewsdataIO\Exception\NewsdataAPIError; use NewsdataIO\Exception\NewsdataNetworkError; try { $client->get_latest_news(['q' => 'news']); } catch (NewsdataValidationError $e) { // bad parameter — $e->getParam() } catch (NewsdataAuthError $e) { // 401 / 403 } catch (NewsdataRateLimitError $e) { // 429 — $e->getRetryAfter() } catch (NewsdataAPIError $e) { // other API error — $e->getStatusCode(), $e->getResponseBody() } catch (NewsdataNetworkError $e) { // cURL / connectivity failure }
Hierarchy (all under the NewsdataIO\Exception namespace):
NewsdataException (catch-all base)
├── NewsdataValidationError (getParam())
├── NewsdataAPIError (getStatusCode(), getResponseBody())
│ ├── NewsdataAuthError (401 / 403)
│ ├── NewsdataRateLimitError (429; getRetryAfter())
│ └── NewsdataServerError (5xx)
└── NewsdataNetworkError (cURL / connectivity)
Configuration
$client->setTimeouts($connectSeconds = 10, $totalSeconds = 30); $client->setRetries($maxAttempts = 5, $backoffBaseSeconds = 2.0); $client->setRetryBackoffMax($seconds = 60.0); $client->setDecodeJsonAsArray(true); $client->setProxy([ 'CURLOPT_PROXY' => 'proxy.example.com', 'CURLOPT_PROXYPORT' => 8080, 'CURLOPT_PROXYUSERPWD' => 'user:pass', ]); $client->setLogger($psr3Logger); // API key is redacted from logged URLs
Retries cover network errors, HTTP 429, and 5xx responses. 429 honors the
Retry-After header (integer seconds or HTTP-date); otherwise backoff is
exponential (2s → 4s → 8s …, capped). Auth and other 4xx errors are never
retried.
Response metadata for the most recent call:
$client->getLastResponse()->getHttpCode(); $client->getLastResponse()->getHeaders();
Development
composer install composer test # or: vendor/bin/phpunit
The test suite (tests/) covers the parameter validator and runs entirely
offline — no API key required.
Related libraries
Official Newsdata.io clients across languages and runtimes:
- Python — newsdataapi/python-client (PyPI)
- Node.js — newsdataapi/newsdata-nodejs-client (npm)
- React (hooks) — newsdataapi/newsdata-reactjs-client (npm)
- Java — newsdataapi/newsdata-java-sdk (Maven Central)
- .NET — newsdataapi/newsdata-dotnet-sdk (NuGet)
- Go — newsdataapi/newsdata-go-client (pkg.go.dev)
- Dart / Flutter — newsdataapi/newsdata-flutter-client (pub.dev)
- MCP Server (AI assistants) — newsdataapi/newsdata.io-mcp (PyPI)
Also see free news datasets for ML / NLP work.
License
MIT.
newsdataio/newsdataapi 适用场景与选型建议
newsdataio/newsdataapi 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 3.06k 次下载、GitHub Stars 达 2, 最近一次更新时间为 2021 年 10 月 07 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「api」 「sdk」 「news」 「crypto」 「archive」 「market」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 newsdataio/newsdataapi 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 newsdataio/newsdataapi 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 newsdataio/newsdataapi 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
A PSR-7 compatible library for making CRUD API endpoints
Extend news to use them also as event
This TYPO3 distribution provides a sample website using bootstrap and the extensions pizpalue and container_elements. The distribution tailors Swiss market featuring German as default language and additional translations to French, English and Finnish.
PHP unofficial client to cryptopanic.com API
News feature for Clara.
Extend news by a sub headline
统计信息
- 总下载量: 3.06k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 2
- 点击次数: 17
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2021-10-07
