edytajordan/openweather

Laravel 对 OpenWeather API 的 Guzzle HTTP 包装器

1.1.6 2020-08-31 03:09 UTC

This package is auto-updated.

Last update: 2024-09-29 05:55:50 UTC


README

这是一个 OpenWeather API 的 Laravel 风格包装器。有关请求和响应格式的更多信息,请访问:https://openweathermap.org/

安装

使用以下命令通过 composer 安装此包

$ composer require edytajordan/openweather

更新 composer 后,将服务提供者添加到 config/app.php 文件中的 providers 数组中

/*
* Package Service Providers...
*/
EdytaJordan\OpenWeather\OpenWeatherServiceProvider::class,

要注册一个外观访问器,将以下内容添加到 config/app.php 文件中的 aliases 数组中

 "OpenWeather" => EdytaJordan\OpenWeather\Facades\OpenWeather::class,

配置

将以下行添加到 .env 文件中

OPEN_WEATHER_KEY=<your_open_weather_api_key>

用法

有关响应格式的完整详细信息,请访问:https://openweathermap.org/api

示例案例:仅针对给定的邮政编码获取 'wind' 信息。根据 OpenWeather API 的最终 URL,应传递以下内容
$url = api.openweathermap.org/data/2.5/weather?zip={zip code},{country code}&appid={your api key}
参数

传递一个包含所需响应的参数数组的参数。以下示例将仅从请求的邮政编码的天气信息中返回 WIND。OpenWeather 类的 URL 构建器将根据提供的参数构建 URL。它还将仅包含请求的项目或从响应中排除项目。

可选地,您可以直接传递 'custom_url'(最终 URL),构建器将跳过构建 URL,而是仅验证并获取响应。

//example wih options to build URL
public function wind(Request $request, $zipcode)
    {
        //passing all the options as an example only, please refer to documentation
        $options = [
            'custom_url'        => null,        //if not provided, url will be built from other options
            'pro'               => false,       //if not provided, false is default
            'type'              => 'weather',   //weather, forecast, box, group or onecall (please refer to API documentation)
            'lat'               => null,
            'lon'               => null,
            'location'          => 'zip',       //zip, city name, city id
            'location_value'    => $zipcode,
            'country_code'      => '',          //if not provided, default is 'us'
            'includeOnly'       => ['wind'],    //RESPONSE WILL RETURN INCLUDED ITEMS ONLY (please refer to API documentation for examples of response params (fields) )
            'excludeOnly'       => [],          //RESPONSE WILL RETURN EXCLUDED ITEMS ONLY please refer to API documentation for examples of response params (fields)
        ];

       return json_encode(OpenWeather::getWeather($options));
    }
//example wih passing custom URL
public function wind(Request $request, $zipcode)
    {
        //passing all the options as an example only, please refer to documentation
        $options = [
            'custom_url'        => 'api.openweathermap.org/data/2.5/weather?zip='.$zipcode.'&appid={your api key}',       
            'includeOnly'       => ['wind'],    //RESPONSE WILL RETURN INCLUDED ITEMS ONLY (please refer to API documentation for examples of response params (fields) )
        ];

       return json_encode(OpenWeather::getWeather($options));
    }

JSON 响应

{
  "wind": {
    "speed": 2.1,
    "deg": 0
  }
}

许可证

MIT 许可证(MIT)。有关更多信息,请参阅 许可证文件