🍏🌤 Apple WeatherKit API

Overview

Banner PHP 8.1 Coding style Tests Coverage License

⚠️ DISCLAIMER ⚠️

Apple's WeatherKit REST API is currently still in beta and the documentation is not fully up-to-date.

During development undocumented responses and values were encountered, but have been handled to the best of what information was available at the time.

📖 Table of contents

🚀 Features

  • Multiple forecast types
    • Current weather
    • Next hour (minute-by-minute) forecast 🔹
    • Hourly forecast
    • Daily forecast
  • Weather alerts 🔸
  • Built-in unit conversions
    • Length
    • Pressure
    • Speed
    • Temperature

🔹 = In countries where available. 🔸 = When a country code is provided.

📦 Installation

You can install the package via Composer, by using the following command:

composer require rugaard/weatherkit

Laravel provider

This package comes with a out-of-the-box Service Provider for the Laravel framework. If you're using a newer version of Laravel (>= 5.5) then the service provider will loaded automatically.

Are you using an older version, then you need to manually add the service provider to the config/app.php file:

'providers' => [
    Rugaard\WeatherKit\Providers\LaravelServiceProvider::class,
]

Configuration

The default package configuration are setup to use the following environment variables.

Variable name Default Description
RUGAARD_WEATHERKIT_AUTH_FILEPATH Path to the .p8 key file.
RUGAARD_WEATHERKIT_AUTH_KEY_ID Key ID matching the .p8 key file
RUGAARD_WEATHERKIT_AUTH_APP_PREFIX_ID App Prefix ID (aka. Team ID)
RUGAARD_WEATHERKIT_AUTH_BUNDLE_ID Bundle ID of your App ID.
RUGAARD_WEATHERKIT_LANGUAGE_CODE config('app.locale', 'en') Language code
RUGAARD_WEATHERKIT_TIMEZONE config('app.timezone', 'UTC') Set timezone of timestamps

Should you need to change the default configuration, you can publish the configuration file to your project.

php artisan vendor:publish --provider=\Rugaard\WeatherKit\Providers\LaravelServiceProvider

🔑 Authentication

After Apple bought DarkSky and turned into WeatherKit, the API now requires authentication. To be able to authenticate, you are required to be part of Apple's Developer Program.

Once you're enrolled with Apple Developer Program, you must register a new App ID and create a new Key.

Create new App ID

To create a new App ID, you must register your app on this form. Enter a short description and give your app a unique bundle ID (reverse url).

Example:

Description Bundle ID
Latest weather forecast com.forecast.weather

When you are done filling out the required fields, you need ☑️ WeatherKit under the Capabilities and App Services tabs.

Afterwards, click the blue Continue button and you're done.

Create new key

To create a new key, you must generate it from this form.

Give your key a name and make sure to enable ☑️ WeatherKit. When you're done, click the blue Continue button. You'll be redirected to a confirmation page, where you click the blue Register button.

Then, download your key as physical file to your machine. It's required for authenticating with the API.

And that's it. You're done.

⚙️ Usage

Before the client can be instantiated, it requires an access token. To generate an access token, Apple requires you to create an App ID and Key, which you to download as a physical file.

If you have not done these things yet, you can follow the guide in the 🔑 Authentication section of this README.

Generate access token

To generate an access token, you're going to need a few things:

<?php

use Rugaard\WeatherKit\Token;

// Details from "Create new App ID" section.
$appIdPrefix = 'O9876S4E2I';
$bundleId = 'com.forecast.weather';

// Details from "Create new key" section.
$pathToKey = 'credentials/AuthKey_I2E4S6789O.p8'
$keyId = 1234567890;

// Create Token instance.
$token = new Token($pathToKey, $keyId, $appIdPrefix, $bundleId);

When a Token instance has been created, you can retrieve the generated access token in two different ways.

// Method 1: getToken()
$accessToken = $token->getToken();

// Method 2: __toString()
$accessToken = (string) $token;

Standalone

Before we are able to make any requests to the API, we need to instantiate the HTTP client. A client can be instantiated with or without a default location.

<?php

use Rugaard\WeatherKit\Client;

// Instantiate client without default location.
$weatherKit = new Client($token->getToken(), null, null, null);

// Instantiate client with default location.
$weatherKit = new Client((string) $token, 55.6736841, 12.5681471, 'dk');

// Instantiate client with default location and local language/timezone.
$weatherKit = new Client((string) $token, 55.6736841, 12.5681471, 'dk', 'da', 'Europe/Copenhagen');

When a client has been instantiated, it's possible to change the location, language and timezone, if needed.

// Change location to London.
$weatherKit->setLocation(51.5286416, -0.1015987);

// Country code is optional
// but required to retrieve weather alerts.
$weatherKit->setLocation(51.5286416, -0.1015987, 'gb');

// Change language to German.
$weatherKit->setLanguage('de');

// Change timezone to Paris.
$weatherKit->setTimezone('Europe/Paris');

You can either retrieve all forecasts at once or individually.

// Get all forecasts at once.
/* @var $forecasts \Illuminate\Support\Collection */
$forecasts = $weatherKit->weather();

// Get current forecast.
/* @var $forecast \Rugaard\WeatherKit\DTO\DataSets\Currently */
$forecast = $weatherKit->currently();

// Get next hour (minute-by-minute) forecast.
/* @var $forecast \Rugaard\WeatherKit\DTO\DataSets\NextHour */
$forecast = $weatherKit->nextHour();

// Get hourly forecast.
/* @var $forecast \Rugaard\WeatherKit\DTO\DataSets\Hourly */
$forecast = $weatherKit->hourly();

// Get daily forecast.
/* @var $forecast \Rugaard\WeatherKit\DTO\DataSets\Daily */
$forecast = $weatherKit->daily();

When a country code has been set with the client, you are able to retrieve weather alerts, should there be any associated with the location.

// Get weather alerts.
/* @var $alerts \Rugaard\WeatherKit\DTO\DataSets\Alerts */
$alerts = $weatherKit->alerts();

// Get detailed information about a specific alert.
/* @var $alertDetails \Rugaard\WeatherKit\DTO\Forecasts\AlertDetails */
$alertDetails = $weatherKit->alert($alerts->getData()->first()->getId());

With Laravel

When using this package with Laravel, the client will automatically be instantiated and added to the service container.

By default the settings are set via environment variables, described in the 📦 Installation section. Should you want to use something else than environment variables, you can change it in the config file at config/weatherkit.php.

<?php

namespace App\Http\Controllers;

use Illuminate\Routing\Controller;
use Rugaard\WeatherKit\Client as WeatherKit;

class WeatherController extends Controller
{
    /**
     * Get all forecasts at once.
     *
     * @param \Rugaard\WeatherKit\Client $weatherKit
     */
    public function forecast(WeatherKit $weatherKit)
    {
        $forecasts = $weatherKit->setLocation(55.6736841, 12.5681471, 'dk')->weather();
    }
    
    /**
     * Get current weather measurements.
     *
     * @param \Rugaard\WeatherKit\Client $weatherKit
     */
    public function currently(WeatherKit $weatherKit)
    {
        $forecasts = $weatherKit->setLocation(55.6736841, 12.5681471, 'dk')->currently();
    }
    
    /**
     * Get next hour (minute-by-minute) forecast.
     *
     * @param \Rugaard\WeatherKit\Client $weatherKit
     */
    public function nextHour(WeatherKit $weatherKit)
    {
        $forecasts = $weatherKit->setLocation(55.6736841, 12.5681471, 'dk')->nextHour();
    }
    
    /**
     * Get hourly forecast.
     *
     * @param \Rugaard\WeatherKit\Client $weatherKit
     */
    public function hourly(WeatherKit $weatherKit)
    {
        $forecasts = $weatherKit->setLocation(55.6736841, 12.5681471, 'dk')->hourly();
    }
    
    /**
     * Get daily forecast.
     *
     * @param \Rugaard\WeatherKit\Client $weatherKit
     */
    public function daily(WeatherKit $weatherKit)
    {
        $forecasts = $weatherKit->setLocation(55.6736841, 12.5681471, 'dk')->daily();
    }
}

It's possible to set/change default settings on the Client by setting them in the boot() method of the AppServiceProvider. This way, you can avoid setting location/language/timezone on each request.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Rugaard\WeatherKit\Client as WeatherKit;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot(WeatherKit $weatherKit)
    {
        // Change location to London.
        $weatherKit->setLocation(51.5286416, -0.1015987);
        
        // Country code is optional
        // but required to retrieve weather alerts.
        $weatherKit->setLocation(51.5286416, -0.1015987, 'gb');
        
        // Change language to German.
        $weatherKit->setLanguage('de');
        
        // Change timezone to Paris.
        $weatherKit->setTimezone('Europe/Paris');
    }
}

📚 Documentation

For more in-depth documentation about forecast types, measurements and more, please refer to the Wiki.

🚓 License

This package is licensed under MIT.

Since this package uses an Apple service, you need follow the guidelines and requirements for attributing Apple weather data. For more details, view the attribution requirements on Apple's website.

You might also like...
Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics (functional) API that doesn't cause vendor lock-in.

Metrics Simple library that abstracts different metrics collectors. I find this necessary to have a consistent and simple metrics API that doesn't cau

Currency is a simple PHP library for current and historical currency exchange rates & crypto exchange rates. based on the free API exchangerate.host

Currency Currency is a simple PHP library for current and historical currency exchange rates & crypto exchange rates. based on the free API exchangera

A set of utilities for working with vk api!

vk-utils Документация на русском языке Installation composer require labile/vk-utils How to use it? Simple example use Astaroth\VkUtils\Client; $api

A simple API with Guzzle wrapper, providing easy access to wppconnect's endpoints.

WPPConnect Team Wppconnect Laravel Client A simple API with Guzzle wrapper, providing easy access to wppconnect's endpoints. Requirements PHP 7.4 or n

Uma solucão simples para integrar sua aplicação Laravel a API PIX do Banco Central do Brasil
Uma solucão simples para integrar sua aplicação Laravel a API PIX do Banco Central do Brasil

Uma solução simples para integrar a sua aplicação Laravel com a API PIX do Banco Central do Brasil Instalação Publicando os assets Publicando o arquiv

Complete Pipedrive API client for PHP

Complete Pipedrive API client for PHP Contribute by referral code / link This won't take much time. You could use my referral code or link to get up t

The swiss army knife for Magento developers, sysadmins and devops. The tool provides a huge set of well tested command line commands which save hours of work time. All commands are extendable by a module API.

netz98 magerun CLI tools for Magento 2 The n98 magerun cli tools provides some handy tools to work with Magento from command line. Build Status Latest

Simple game server with php without socket programming. Uses the Api request post(json).

QMA server Simple game server with php without socket programming. Uses the Api request post(json). What does this code do? Register the user as a gue

Releases(0.1.0)
Owner
Morten Rugaard
Web geek, gadget lover and sports enthusiast.
Morten Rugaard
A Laravel Wrapper for the Binance API. Now easily connect and consume the Binance Public & Private API in your Laravel apps without any hassle.

This package provides a Laravel Wrapper for the Binance API and allows you to easily communicate with it. Important Note This package is in early deve

Moinuddin S. Khaja 7 Dec 7, 2022
Google Search Results PHP API via Serp Api

Google Search Results in PHP This Php API is meant to scrape and parse Google, Bing or Baidu results using SerpApi. The full documentation is availabl

SerpApi 42 Nov 14, 2022
The fastest way to make a powerful JSON:API compatible Rest API with Laravel.

The first fully customizable Laravel JSON:API builder. "CRUD" and protect your resources with 0 (zero) extra line of code. Installation You can instal

BinarCode 394 Dec 23, 2022
Code to accompany the YouTube video "Full PHP cURL API tutorial - how to use a REST API from PHP using cURL"

PHP cURL CRUD Example Example code to accompany this YouTube video. Note that the init_curl.php file contains a placeholder for an API key. DO NOT che

Dave Hollingworth 14 Dec 24, 2022
Api.video-wordpress-plugin - The official api.video plugin for WordPress

api.video WordPress Plugin api.video is the video infrastructure for product builders. Lightning fast video APIs for integrating, scaling, and managin

api.video 5 Oct 19, 2022
Projet réalisé dans le cadre de l'apprentissage des API et d'API Platform

Bilemo BileMo est une entreprise offrant toute une sélection de téléphones mobiles haut de gamme. Vous êtes en charge du développement de la vitrine d

Abdelatif H. 1 Jan 13, 2022
Bastion API is a simple API made to get query informations

Bastion API is a simple API made to get query informations

Adler 1 Jul 16, 2022
A PHP API extension the 'An API of Ice and Fire'

This documentation is meant to enable you to consume our API and get you started right away using your favourite programming language. All endpoints and HTTP methods to be used have been detailed with a sample example for e

David Syengo 1 Mar 26, 2022
Simple Symfony API-Platform Template which you can use to start to develop with symfony and api-platform

symfony-api-platform-skeleton Simple Template for Symfony API You can fork it and change the git remote to your Repo git remote set-url <your-git-remo

null 1 Jan 23, 2022
PDF API. JSON to PDF. PDF Template Management, Visual HTML Template Editor and API to render PDFS by json data

PDF Template Management, Visual HTML Template Editor and API to render PDFS by json data PDF ENGINE VERSION: development: This is a prerelease version

Ajous Solutions 2 Dec 30, 2022