News API API in PHP
News API API in PHP
This guide shows you how to integrate the News API into your PHP application. Headlines and articles from 80,000+ worldwide news sources.
Prerequisites
- PHP installed on your system
- An News API API key (sign up at https://newsapi.org)
- Basic familiarity with HTTP APIs
Installation
composer require guzzlehttp/guzzle
Basic Usage
<?php
$apiKey = getenv('API_KEY') ?: 'YOUR_API_KEY';
$baseUrl = 'https://api.newsapi.org';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $baseUrl . '/v1/resources');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $apiKey,
'Content-Type: application/json',
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo "Status: $httpCode\n";
echo $response . "\n";
?>
Error Handling
<?php
$apiKey = getenv('API_KEY') ?: 'YOUR_API_KEY';
$baseUrl = 'https://api.newsapi.org';
function callApiWithRetry($url, $headers, $maxRetries = 3) {
$ch = curl_init();
for ($attempt = 0; $attempt <= $maxRetries; $attempt++) {
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpCode === 429) {
sleep(60);
continue;
}
if ($httpCode < 500) {
break;
}
sleep(pow(2, $attempt));
}
curl_close($ch);
return [$httpCode, $response];
}
$url = $baseUrl . '/v1/resources';
$headers = ['Authorization: Bearer ' . $apiKey, 'Content-Type: application/json'];
list($code, $resp) = callApiWithRetry($url, $headers);
echo "Status: $code\n";
echo $resp . "\n";
?>
Advanced Usage
<?php
class NewsapiClient {
private $apiKey;
private $baseUrl;
public function __construct($apiKey, $baseUrl = 'https://api.newsapi.org') {
$this->apiKey = $apiKey;
$this->baseUrl = rtrim($baseUrl, '/');
}
public function request($method, $path, $data = null) {
$ch = curl_init();
$url = $this->baseUrl . '/v1' . $path;
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->apiKey,
'Content-Type: application/json',
]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
if ($data !== null) {
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
}
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpCode >= 400) {
throw new Exception("API Error: HTTP $httpCode");
}
return json_decode($response, true);
}
public function listResources($params = []) {
$query = http_build_query($params);
$path = '/resources' . ($query ? '?' . $query : '');
return $this->request('GET', $path);
}
public function createResource($data) {
return $this->request('POST', '/resources', $data);
}
}
$client = new NewsapiClient(getenv('API_KEY') ?: 'YOUR_API_KEY');
$resources = $client->listResources(['limit' => 50]);
echo "Found " . count($resources['data'] ?? []) . " resources\n";
?>
Best Practices
- Store your API key in an environment variable, never in source code
- Implement retry logic with exponential backoff for 429 and 5xx errors
- Set reasonable timeouts (10-30 seconds) for all API calls
- Log request IDs from response headers for debugging
- Cache responses where appropriate to reduce API calls