pastclimate / pastclimate-php
Official PHP client for the PastClimate historical weather API.
Requires
- php: >=8.1
- ext-json: *
Requires (Dev)
- nyholm/psr7: ^1.8
- phpunit/phpunit: ^10.5
- psr/http-client: ^1.0
- psr/http-factory: ^1.0
Suggests
- ext-curl: Needed by the default transport (CurlTransport).
- psr/http-client: Needed only to use Psr18Transport with a PSR-18 client such as Guzzle.
- psr/http-factory: Needed only to use Psr18Transport (a PSR-17 request factory).
Provides
None
Conflicts
None
Replaces
None
README
The official PHP client for the PastClimate API: historical daily, hourly, monthly and yearly weather, climate normals and records.
- PHP 8.1 or newer,
declare(strict_types=1)throughout. - Zero dependencies: the default transport uses the cURL extension. Or plug in any PSR-18 client.
- One method per API operation, with typed response models.
- One exception class per kind of failure.
- Automatic retries where retrying is safe.
- Credit and rate-limit numbers on every response.
Install
composer require pastclimate/pastclimate-php
Quickstart
Get a key on your API page and put it in an environment variable. Never put a key in source code or in a URL.
export PASTCLIMATE_API_KEY=your_key_here
<?php require 'vendor/autoload.php'; use PastClimate\Client; $client = new Client(); // reads PASTCLIMATE_API_KEY $response = $client->getDaily('gb/london', '2024-01-01', '2024-01-31'); foreach ($response->data as $day) { echo "{$day->date}: {$day->daily_min_temp} to {$day->daily_max_temp}\n"; } echo "Used {$response->creditsUsed()} credits, {$response->creditsRemaining()} left\n";
A runnable version is in examples/quickstart.php. It makes real calls, so it
only runs when PASTCLIMATE_API_KEY is set.
Configuration
Arguments are named, so pass only what you need:
$client = new Client( apiKey: '...', // default: the PASTCLIMATE_API_KEY environment variable baseUrl: 'https://api.pastclimate.com', // default: PASTCLIMATE_BASE_URL, then this value timeout: 30.0, // seconds per attempt maxRetries: 2, // retries after the first try maxRetryDelay: 60.0, // longest wait the client will sleep between tries );
- With no key, the constructor throws
PastClimate\Exception\ConfigurationException. baseUrlmust behttps. Plainhttpis accepted only forlocalhostand127.0.0.1.- The key is sent as
Authorization: Bearer <key>, never in the URL.var_dump($client)hides it, and a client cannot be serialized. - Redirects are not followed, so the key cannot be sent to another host.
- The
User-Agentispastclimate-php/<version>.
Places
Every weather method takes a place as its first argument. Give it in one of two ways.
use PastClimate\Place; // 1. A location id: country code, slash, place slug. A plain string works. $client->getMonthly('gb/london'); $client->getMonthly(Place::id('gb/london')); // 2. A latitude and longitude, with the two-letter country they are in. $client->getMonthly(Place::point(51.5, -0.12, 'gb'));
Find ids with searchLocations. A point is snapped to the nearest place in that country; the
response's location->requested shows the point you sent and how far away the chosen place is.
Methods
Every method returns a PastClimate\Response\ApiResponse with data, location, meta, rateLimit,
status, headers, and the methods creditsUsed() and creditsRemaining(). The type of data is
given below. Model properties mirror the API's field names (daily_max_temp). Properties the server
leaves out are null; fields this version does not know about are ignored.
Dates (YYYY-MM-DD) are strings and timestamps are DateTimeImmutable in UTC. You may pass dates as
strings or any DateTimeInterface.
searchLocations(string $q, ?string $country = null)
Search places by the start of their name. data is a list of LocationSearchResult.
$found = $client->searchLocations('lon', country: 'gb'); foreach ($found->data as $place) { echo "{$place->id} {$place->name}\n"; }
nearestLocation(float $lat, float $lon, string $country)
The place nearest a point, inside one country. data is a NearestLocation.
$nearest = $client->nearestLocation(51.5, -0.12, 'gb'); echo "{$nearest->data->id}, {$nearest->data->requested->distance_km} km away\n";
getLocation(Place|string $id)
One location by id. data is a LocationDetail, including coverage (first_year, last_date).
$london = $client->getLocation('gb/london'); echo $london->data->timezone, ' ', $london->data->coverage->last_date, "\n";
getDaily($location, $start, $end, $units = null, $format = Format::Json)
Daily values from $start to $end, both included. data is a list of DailyRow.
use PastClimate\Units; $daily = $client->getDaily('gb/london', '2024-01-01', '2024-01-31', Units::Imperial); foreach ($daily->data as $d) { echo "{$d->date} {$d->daily_avg_temp} {$daily->meta->units->temperature}\n"; }
getHourly($location, $date, ?int $days = null, $units = null, $format = Format::Json)
Hourly values for $days consecutive local days starting at $date. data is a list of
HourlyRow. Leave $days out for the server default.
$hourly = $client->getHourly('gb/london', '2024-01-15', days: 1); foreach ($hourly->data as $h) { echo $h->timestamp_utc->format('c'), " {$h->temperature}\n"; }
getMonthly($location, $units = null)
Every month on file. data is a list of MonthlyRow.
$monthly = $client->getMonthly('gb/london'); $latest = $monthly->data[count($monthly->data) - 1]; echo $latest->monthly_total_rain, "\n";
getYearly($location, $units = null)
Every year on file. data is a list of YearlyRow.
foreach ($client->getYearly('gb/london')->data as $y) { echo "{$y->year} {$y->yearly_avg_temp}\n"; }
getNormals($location, ?int $month = null, $units = null)
Climate normals. data is a NormalsData with monthly and day_of_year lists. $month (1 to 12)
narrows both to one month.
$normals = $client->getNormals('gb/london', month: 7); echo $normals->data->monthly[0]->avg_temp, ' ', $normals->data->day_of_year[0]->rain_prob, "\n";
getRecords($location, $units = null)
The hottest, coldest, wettest and windiest day on file. data is a list of RecordItem.
foreach ($client->getRecords('gb/london')->data as $record) { echo "{$record->metric}: {$record->value} {$record->unit} on {$record->occurred_on}\n"; }
getCoverage(?string $country = null)
The countries the archive serves, and the first year and last day of published data for each.
data is a CoverageData. Check it before asking for dates near the end of the archive.
foreach ($client->getCoverage(country: 'gb')->data->countries as $c) { echo "{$c->country}: {$c->first_year} to {$c->last_date}\n"; }
getMe()
Your plan, credit balance and limits. data is a MeData. Use it instead of hard-coding limits.
$me = $client->getMe()->data; echo $me->plan->name, ' ', $me->credits->used_this_month, ' ', $me->rate_limit->per_minute, "\n";
Units
$units is Units::Metric (the server default) or Units::Imperial; the strings 'metric' and
'imperial' work too. Field names are the same in both; the unit of each value is in
$response->meta->units (system, temperature, precipitation, wind_speed, pressure). Anything
else throws InvalidArgumentException before a request is sent.
$response = $client->getRecords('gb/london', Units::Imperial); echo $response->meta->units->temperature; // F
CSV
getDaily and getHourly can return CSV. Pass Format::Csv (or 'csv'), or use the shorthands
getDailyCsv and getHourlyCsv. You get a PastClimate\Response\CsvResponse:
$csv = $client->getDailyCsv('gb/london', '2023-01-01', '2023-12-31'); file_put_contents('london-2023.csv', $csv->csv); echo $csv->creditsUsed();
A CSV body has no meta, so creditsUsed(), creditsRemaining() and rateLimit come from the response
headers. If the request fails you still get a typed exception, never an error saved as CSV.
Credits and rate limits
Every response, JSON or CSV, tells you what the call cost and what is left:
$response = $client->getMonthly('gb/london'); $response->creditsUsed(); // credits this call used $response->creditsRemaining(); // credits you can still spend (may be null) $response->meta->methodology_version; $limit = $response->rateLimit; // the per-minute request limit $limit->limit; // requests allowed per minute $limit->remaining; // requests left in this minute $limit->reset; // seconds until the oldest request leaves the minute window
The SDK does not know what a call costs and does not check your balance. Read the numbers from the
response, or call getMe(). Rate-limit values are null when the server did not send the header.
Errors
Everything the package throws extends PastClimate\Exception\PastClimateException.
| Class | Thrown for (error code) |
|---|---|
AuthenticationException |
missing_key, invalid_key, key_revoked, email_not_verified, account_suspended |
InvalidRequestException |
invalid_request, range_too_large, key_in_query, cors_not_supported, method_not_allowed |
NotFoundException |
location_not_found, not_published, not_found, location_blocked |
PlanRequiredException |
plan_required |
RateLimitedException |
rate_limited, daily_request_cap_reached |
QuotaExceededException |
quota_exceeded |
ServerException |
internal_error, api_disabled, metering_unavailable (and invalid_response, when a success body cannot be read) |
ConnectionException |
no HTTP answer: DNS, TLS, reset or timeout ($e->timedOut) |
ConfigurationException |
the client was set up wrongly |
The first seven rows (AuthenticationException to ServerException) extend ApiException and carry:
$e->status: the HTTP status (alsogetCode())$e->errorCode: the API's stable error code (PHP keepsgetCode()for an integer, so it iserrorCode)$e->getMessage(): the message$e->docsUrl: the docs page for the code$e->headers,$e->rateLimit,$e->retryAfter(seconds, ornull),$e->upgradeUrl,$e->body
An unknown future code still maps to a class by its HTTP status. If a proxy answers without the API's
error body, errorCode is "http_<status>" and docsUrl is null.
use PastClimate\Exception\{ApiException, ConnectionException, NotFoundException, QuotaExceededException, RateLimitedException}; try { $client->getDaily('gb/london', '1900-01-01', '1900-01-31'); } catch (NotFoundException $e) { echo "No data: {$e->errorCode} - {$e->getMessage()}\n"; // e.g. not_published; see getCoverage() } catch (QuotaExceededException $e) { echo "Out of credits. Upgrade: {$e->upgradeUrl}\n"; } catch (RateLimitedException $e) { echo "Slow down. Wait {$e->retryAfter} seconds.\n"; } catch (ApiException $e) { echo "{$e->status} {$e->errorCode}: {$e->getMessage()} ({$e->docsUrl})\n"; } catch (ConnectionException $e) { echo "Network problem: {$e->getMessage()}\n"; }
Branch on the class or errorCode, not on the message. Failed calls are not charged.
Retries
The client retries a call automatically, up to maxRetries times (default 2):
| Failure | What happens |
|---|---|
429 with Retry-After |
waits that many seconds, then retries |
429 without Retry-After |
thrown at once (on a plan with one-time credits this means they are used up, and waiting does not help) |
500, 502, 503, any 5xx |
retries with exponential backoff and jitter |
| network error or timeout | retries with the same backoff |
any other 4xx |
thrown at once; fix the request |
A 429 whose Retry-After is longer than maxRetryDelay (default 60 seconds), for example "wait until
midnight UTC", is thrown instead of slept on; retryAfter tells you how long. Set maxRetries: 0 to turn
retrying off. Retries repeat the same GET, so they cannot double-send anything. Refused calls still count
toward your daily request limit, so do not wrap the client in an unbounded retry loop of your own.
Transports and PSR-18
The default CurlTransport needs only ext-curl. To use Guzzle, Symfony HttpClient or any other PSR-18
client, install psr/http-client, a PSR-17 factory and your client, and wrap it:
use PastClimate\Client; use PastClimate\Http\Psr18Transport; $client = new Client( apiKey: getenv('PASTCLIMATE_API_KEY') ?: null, transport: new Psr18Transport($psr18Client, $psr17RequestFactory), );
With a PSR-18 client, set the timeout on that client (the timeout argument applies to the cURL transport)
and configure it not to follow redirects. To write your own transport, implement
PastClimate\Http\TransportInterface (get(string $url, array $headers, float $timeout): TransportResponse,
throwing ConnectionException when no HTTP answer arrives).
Development
composer install
composer test
The tests use a fake transport and a mocked PSR-18 client; they never call the real API.
License
MIT. See LICENSE.