项目作者: dblock

项目描述 :
OpenWeather Ruby Client
高级语言: Ruby
项目地址: git://github.com/dblock/open-weather-ruby-client.git
创建时间: 2020-04-28T04:05:26Z
项目社区:https://github.com/dblock/open-weather-ruby-client

开源协议:MIT License

下载


OpenWeather Ruby Client

Gem Version
Tests Status

A Ruby client for the OpenWeather API v2.5 and v3.0.

Unlike other clients, including open-weather, provides a rich first class interface to OpenWeather models, structured timestamps, built-in metrics conversion for temperature and wind speed, offers more consistent error handling, and is implemented with thorough test coverage using actual OpenWeather data.

Table of Contents

Installation

Add to Gemfile.

  1. gem 'open-weather-ruby-client'

Run bundle install.

Usage

Use an access token obtained from API Keys on the OpenWeather website after registration.

  1. client = OpenWeather::Client.new(
  2. api_key: "1a2b3c4d5a6b7c8d9a8b7c6d5a4b3c2d1"
  3. )

Current Weather

Returns current weather.

  1. data = client.current_weather(city: 'London') # => OpenWeather::Models::City::Weather
  2. data.name # => 'London'
  3. data.dt # => Time
  4. data.main.feels_like # => 277.73
  5. data.main.humidity # => 81
  6. data.main.pressure # => 1005
  7. data.main.temp # => 282.57
  8. data.main.temp_max # => 283.15, degrees Kelvin
  9. data.main.temp_max_c # => 10, degrees Celcius
  10. data.main.temp_max_f # => 50.0, degrees Farenheit
  11. data.main.temp_min # => 281.48

Returns the current weather in metric units and Russian metadata.

  1. data = client.current_weather(city: 'Moscow', units: 'metric', lang: 'ru') # => OpenWeather::Models::City::Weather
  2. data.name # => 'Москва'
  3. data.main.temp # => 12

Returns weather by city, optional state (in the US) and optional ISO 3166 country code.
Names that cannot be resolved will cause the API call to raise a Faraday::ResourceNotFound error.

  1. client.current_city('Sydney')
  2. client.current_city('London, UK')
  3. client.current_city('London', 'UK')
  4. client.current_city('Albany')
  5. client.current_city('Albany, New York')
  6. client.current_city('Albany, New York', 'US')
  7. client.current_city('Albany, NY', 'US')
  8. client.current_city('Albany', 'New York', 'US')
  9. client.current_city('Albany', 'NY', 'US')
  10. client.current_city('Albany', 'NY') # 2-letter state abbreviation w/o country will raise Faraday::ResourceNotFound
  11. client.current_weather(city: 'Albany', state: 'NY', country: 'US')

Returns weather by city ID.

  1. client.current_city_id(2643743) # => weather in London
  2. client.current_weather(id: 2643743) # => weather in London

Returns weather by latitude and longitude.

  1. client.current_geo(51.51, -0.13) # => weather in London
  2. client.current_weather(lat: 51.51, lon: -0.13) # => weather in London

Returns weather by zip code with an optional country code (defaults to US).

  1. client.current_zip(10018, 'US') # => weather in New York, 10018
  2. client.current_weather(zip: 10018, country: 'US') # => weather in New York, 10018

See OpenWeather::Models::City::Weather and related OpenWeather::Models for all available properties.

Current Weather for Several Cities

Collection APIs return OpenWeather::Models::List, which includes multiple instances of OpenWeather::Models::City::Weather.

Cities Within a Rectangle Zone

  1. data = client.current_cities_geo_box(12, 32, 15, 37, 10) # => OpenWeather::Models::List
  2. data.first.name # 'Birkirkara'
  3. data.main.temp # => 16.23

You can optionally name parameters.

  1. client.current_cities_geo_box(lon_left: 12, lat_bottom: 32, lon_right: 15, lat_top: 37, zoom: 10) # => OpenWeather::Models::List

You can use server clustering of points with cluster: true.

  1. client.current_cities_geo_box(12, 32, 15, 37, 10, cluster: true) # => OpenWeather::Models::List

Cities Within a Circle

  1. data = client.current_cities_geo_circle(55.5, 37.5, 10) # => OpenWeather::Models::List
  2. data.first.name # 'Shcherbinka'
  3. data.main.temp # => 276.86

You can optionally name parameters.

  1. client.current_cities_geo_circle(lat: 55.5, lon: 37.5, cnt: 7) # => OpenWeather::Models::List

Multiple Cities by Id

  1. data = client.current_cities_id(524901, 703448, 2643743) # => OpenWeather::Models::List
  2. data.first.name # 'Moscow'
  3. data.main.temp # => 285.15

One Call

One Call API provides current weather, minute forecast for 1 hour, hourly forecast for 48 hours, daily forecast for 7 days, historical weather data for 5 previous days for any geographical coordinate, and national weather alerts.

See OpenWeather::Models::OneCall for all available models and properties.

Current and Forecast Weather

  1. data = client.one_call(lat: 33.441792, lon: -94.037689) # => OpenWeather::Models::OneCall::Weather
  2. data.lat # => 33.44
  3. data.lon # => -94.04
  4. data.timezone # => 'America/Chicago'
  5. data.current # => OpenWeather::Models::OneCall::CurrentWeather
  6. data.data # => Array]OpenWeather::Models::OneCall::CurrentWeather] (on base plan)
  7. data.minutely # => Array[OpenWeather::Models::OneCall::MinutelyWeather]
  8. data.hourly # => Array[OpenWeather::Models::OneCall::HourlyWeather]
  9. data.daily # => Array[OpenWeather::Models::OneCall::DailyWeather]
  10. data.alerts # => Array[OpenWeather::Models::OneCall::Alert]

Exclude minutely and hourly data.

  1. client.one_call(lat: 33.441792, lon: -94.037689, exclude: ['minutely', 'hourly'])

Historical Weather

  1. data = client.one_call(lat: 33.441792, lon: -94.037689, dt: Time.now - 24 * 60 * 60) # => OpenWeather::Models::OneCall::Weather
  2. data.lat # => 33.44
  3. data.lon # => -94.04
  4. data.timezone # => 'America/Chicago'
  5. data.current # => OpenWeather::Models::OneCall::CurrentWeather
  6. data.hourly # => Array[OpenWeather::Models::OneCall::HourlyWeather]

Hourly Forecast (Pro)

The Hourly Forecast API provides hourly weather forecast for 4 days. Note: This API requires a paid api-key from OpenWeather.org.

  1. data = client.client.hourly(lat: 33.5312, lon: -111.9426, appid: "<your api key>") # => OpenWeather::Models::Forecast::Hourly
  2. data.cnt # => 96 (number of entries)
  3. data.city # => OpenWeather::Models::Forecast::City
  4. data.list.first # => OpenWeather::Models::Forecast::Forecast
  5. data.list.first.dt # => Time
  6. data.list.first.main # => OpenWeather::Models::Forecast::Main
  7. data.list.first.weather # => Array[OpenWeather::Models::Forecast::Weather]
  8. data.list.first.clouds # => OpenWeather::Models::Forecast::Clouds or nil
  9. data.list.first.wind # => OpenWeather::Models::Forecast::Wind or nil
  10. data.list.first.visibility # => 10000
  11. data.list.first.pop # => 0.1 (probability of precipitation from 0.0 to 1.0 (0% to 100%))
  12. data.list.first.rain # => OpenWeather::Models::Forecast::Rain or nil
  13. data.list.first.snow # => OpenWeather::Models::Forecast::Snow or nil
  14. data.list.first.sys # => OpenWeather::Models::Forecast::Sys or nil
  15. data.list.first.dt_txt # => String (Time of data forecasted, ISO, UTC)

30 Day Forecast (Pro)

The 30 Day Forecast API provides daily weather forecast for 30 days. Note: This API requires a paid api-key from OpenWeather.org.

  1. data = client.client.forecast(lat: 33.5312, lon: -111.9426, appid: "<your api key>") # => OpenWeather::Models::Forecast::ThirtyDay::ThirtyDay
  2. data.cnt # => 30 (number of entries - sometimes this is 29)
  3. data.city # => OpenWeather::Models::Forecast::City
  4. data.list.first # => OpenWeather::Models::Forecast::ThirtyDay::Forecast
  5. data.list.first.dt # => Time - time of data forcasted, UTC
  6. data.list.first.sunrise # => Time - Sunrise time, UTC
  7. data.list.first.sunset # => Time - Sunset time, UTC
  8. data.list.first.temp # => OpenWeather::Models::Forecast::ThirtyDay::Temp
  9. data.list.first.feels_like # => OpenWeather::Models::OneCall::FeelsLike
  10. data.list.first.pressure # => int - Atmospheric pressure on the sea level, hPa
  11. data.list.first.humidity # => int - Humidity, % (e.g. integer 24 means 24% cloudiness)
  12. data.list.first.weather # => Array[OpenWeather::Models::Weather]
  13. data.list.first.speed # => double - Wind speed. Unit Default: meter/sec, Metric: meter/sec, Imperial: miles/hour
  14. data.list.first.deg # => int - Wind direction, degrees (meteorological)
  15. data.list.first.clouds # => int - Cloudiness, % (e.g. integer 78 means 78% cloudiness)
  16. data.list.first.rain # => double or nil - Precipitation volume, mm. Please note that only mm as units of measurement are available for this parameter
  17. data.list.first.snow # => double or nil - Snow volume, mm. Please note that only mm as units of measurement are available for this parameter

5 Day Forecast

The 5 Day Forecast API provides weather forecast for 5 days with data every 3 hours by geographic coordinates.

  1. data = client.client.five_day_forecast(lat: 33.5312, lon: -111.9426, appid: "<your api key>") # => OpenWeather::Models::Forecast::FiveDay
  2. data.cnt # => 40 (number of entries)
  3. data.list.first # => OpenWeather::Models::Forecast::FiveDay::Forecast
  4. data.list.first.dt # => Time
  5. data.list.first.main # => OpenWeather::Models::Main
  6. data.list.first.weather # => Array[OpenWeather::Models::Weather]
  7. data.list.first.clouds # => OpenWeather::Models::Clouds or nil
  8. data.list.first.wind # => OpenWeather::Models::Wind or nil
  9. data.list.first.visibility # => 10000
  10. data.list.first.pop # => 0.1 (probability of precipitation from 0.0 to 1.0 (0% to 100%))
  11. data.list.first.rain # => OpenWeather::Models::Rain or nil
  12. data.list.first.snow # => OpenWeather::Models::Snow or nil
  13. data.list.first.sys # => OpenWeather::Models::Sys or nil
  14. data.list.first.dt_txt # => String (Time of data forecasted, ISO, UTC)

Stations

The Stations API lets your manage personal weather stations and measurements.

Register a Station

To register a station, you can call the client method:

  1. data = client.register_station(external_id: 'SF_TEST001', ...) # => OpenWeather::Models::Station
  2. data.id # => '5ed2118acca8ce0001f1aeg1'
  3. data.external_id # => 'SF_TEST001'

Alternatively, call register! on an instance of Station:

  1. model = OpenWeather::Models::Station.new(external_id: 'SF_TEST001', ...)
  2. model.register!
  3. model.id # => '5ed2118acca8ce0001f1aeg1'

List Stations

To list all stations, call the client method:

  1. client.list_stations # => Array[OpenWeather::Models::Station]

Get Station

To get a station, call the client method:

  1. client.get_station('5ed2118acca8ce0001f1aeg1') # => OpenWeather::Models::Station

Update Station

To update a station, call the client method:

  1. client.update_station('5ed2118acca8ce0001f1aeg1', external_id: 'SF_TEST002') # => OpenWeather::Models::Station

Alternatively, call update! on an instance of Station:

  1. model = OpenWeather::Models::Station.new(external_id: 'SF_TEST001', ...)
  2. model.register!
  3. model.update!(external_id: 'SF_TEST002')
  4. model.external_id # => 'SF_TEST002'

Delete Station

To delete a station, call the client method:

  1. data = client.delete_station('5ed2118acca8ce0001f1aeg1') # => nil

Create Measurements

To create measurements, call the client method:

  1. client.create_measurements([
  2. {
  3. "station_id": -1,
  4. "dt": 1479817340,
  5. "temperature": 18.7,
  6. "wind_speed": 1.2,
  7. "wind_gust": 3.4,
  8. "pressure": 1021,
  9. "humidity": 87,
  10. "rain_1h": 2,
  11. "clouds": [
  12. {
  13. "condition": 'NSC'
  14. }
  15. ]
  16. }
  17. ]) # => nil

Get Measurements

To get measurements, call the client method with the required parameters:

  1. client.get_measurements(
  2. station_id: '5ed21a12cca8ce0001f1aef1',
  3. type: 'd',
  4. limit: 100,
  5. from: 1469817340,
  6. to: 1591620047
  7. ) # => Array[OpenWeather::Models::Stations::Measurement]

Configuration

You can configure client options, globally.

  1. OpenWeather::Client.configure do |config|
  2. config.api_key = '1a2b3c4d5a6b7c8d9a8b7c6d5a4b3c2d1'
  3. config.user_agent = 'OpenWeather Ruby Client/1.0'
  4. end

The following settings are supported.

setting description
api_key Required API key.
lang Default language in API responses.
units Default units in API responses.
endpoint Defaults to https://api.openweathermap.org/data.
user_agent User-agent, defaults to OpenWeather Ruby Client/version.
proxy Optional HTTP proxy.
ca_path Optional SSL certificates path.
ca_file Optional SSL certificates file.
logger Optional Logger instance that logs HTTP requests.
timeout Optional open/read timeout in seconds.
open_timeout Optional connection open timeout in seconds.

Units

The OpenWeather API returns responses in standard, metric, and imperial units. You can pass units into API requests or configure the desired units globally.

  1. data = client.weather(id: 2643743, units: 'metric')
  2. data.name # => 'London'
  3. data.main.temp # => 12, degrees Celcius
  1. OpenWeather.configure do |config|
  2. config.units = 'metric'
  3. end
  4. data = client.weather(id: 2643743)
  5. data.name # => 'London'
  6. data.main.temp # => 12, degrees Celcius

Converting Temperature

APIs that return temperature support conversion between default, metric and imperial units, regardless of what units were requested. The following example requests current weather in metric units in Moscow. Use _k for Kelvin, _c for Celcius and _f for Farenheit.

  1. data = client.current_weather(city: 'Moscow', units: 'metric') # => OpenWeather::Models::City::Weather
  2. data.main.temp_max # => 12, degrees Celcius, metric as requested
  3. data.main.temp_max_c # => 12, degrees Celcius
  4. data.main.temp_max_k # => 285.15, degrees Kelvin
  5. data.main.temp_max_f # => 53.6, degrees Farenheit

Converting Wind Speed

Use _mps for wind speed in meters-per-second, and _mph for miles-per-second.

  1. data.wind.speed # => 3, in meters per second, metric as requested
  2. data.main.speed_mph # => 6.71, miles per hour
  3. data.main.speed_mps # 3, meters per second

Language

The OpenWeather API returns responses in English and supports many other languages. You can pass lang into API requests or configure the desired language globally.

  1. data = client.weather(id: 2643743, lang: 'ru')
  2. data.name # => 'Лондон'
  1. OpenWeather.configure do |config|
  2. config.lang = 'ru'
  3. end
  4. data = client.weather(id: 2643743)
  5. data.name # => 'Лондон'

Errors

All errors that return HTTP codes 400-600 result in either Faraday::ResourceNotFound, Faraday::ConnectionFailed or OpenWeather::Errors::Fault exceptions.

Resources

Contributing

See CONTRIBUTING.

Copyright (c) 2020, Daniel Doubrovkine

This project is licensed under the MIT License.