Download the PHP package pastclimate/pastclimate-php without Composer
On this page you can find all versions of the php package pastclimate/pastclimate-php. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download pastclimate/pastclimate-php
More information about pastclimate/pastclimate-php
Files in pastclimate/pastclimate-php
Package pastclimate-php
Short Description Official PHP client for the PastClimate historical weather API.
License MIT
Homepage https://developer.pastclimate.com/api/
Informations about the package pastclimate-php
pastclimate/pastclimate-php
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
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.
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:
- 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.
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.
nearestLocation(float $lat, float $lon, string $country)
The place nearest a point, inside one country. data is a NearestLocation.
getLocation(Place|string $id)
One location by id. data is a LocationDetail, including coverage (first_year, last_date).
getDaily($location, $start, $end, $units = null, $format = Format::Json)
Daily values from $start to $end, both included. data is a list of DailyRow.
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.
getMonthly($location, $units = null)
Every month on file. data is a list of MonthlyRow.
getYearly($location, $units = null)
Every year on file. data is a list of YearlyRow.
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.
getRecords($location, $units = null)
The hottest, coldest, wettest and windiest day on file. data is a list of RecordItem.
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.
getMe()
Your plan, credit balance and limits. data is a MeData. Use it instead of hard-coding limits.
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.
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:
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:
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.
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:
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
The tests use a fake transport and a mocked PSR-18 client; they never call the real API.
License
MIT. See LICENSE.
All versions of pastclimate-php with dependencies
ext-json Version *