Git Product home page Git Product logo

open-weather-ruby-client's Introduction

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.

gem 'open-weather-ruby-client'

Run bundle install.

Usage

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

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

Current Weather

Returns current weather.

data = client.current_weather(city: 'London') # => OpenWeather::Models::City::Weather

data.name # => 'London'
data.dt # => Time
data.main.feels_like # => 277.73
data.main.humidity # => 81
data.main.pressure # => 1005
data.main.temp # => 282.57
data.main.temp_max # => 283.15, degrees Kelvin
data.main.temp_max_c # => 10, degrees Celcius
data.main.temp_max_f # => 50.0, degrees Farenheit
data.main.temp_min # => 281.48

Returns the current weather in metric units and Russian metadata.

data = client.current_weather(city: 'Moscow', units: 'metric', lang: 'ru') # => OpenWeather::Models::City::Weather

data.name # => 'Москва'
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.

client.current_city('Sydney')
client.current_city('London, UK')
client.current_city('London', 'UK')
client.current_city('Albany')
client.current_city('Albany, New York')
client.current_city('Albany, New York', 'US')
client.current_city('Albany, NY', 'US')
client.current_city('Albany', 'New York', 'US')
client.current_city('Albany', 'NY', 'US')
client.current_city('Albany', 'NY')  # 2-letter state abbreviation w/o country will raise Faraday::ResourceNotFound

client.current_weather(city: 'Albany', state: 'NY', country: 'US')

Returns weather by city ID.

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

Returns weather by latitude and longitude.

client.current_geo(51.51, -0.13) # => weather in London
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).

client.current_zip(10018, 'US') # => weather in New York, 10018
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

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

data.first.name # 'Birkirkara'
data.main.temp # => 16.23

You can optionally name parameters.

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.

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

Cities Within a Circle

data = client.current_cities_geo_circle(55.5, 37.5, 10) # => OpenWeather::Models::List

data.first.name # 'Shcherbinka'
data.main.temp # => 276.86

You can optionally name parameters.

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

Multiple Cities by Id

data = client.current_cities_id(524901, 703448, 2643743) # => OpenWeather::Models::List

data.first.name # 'Moscow'
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

data = client.one_call(lat: 33.441792, lon: -94.037689) # => OpenWeather::Models::OneCall::Weather
data.lat # => 33.44
data.lon # => -94.04
data.timezone # => 'America/Chicago'
data.current # => OpenWeather::Models::OneCall::CurrentWeather
data.minutely # => Array[OpenWeather::Models::OneCall::MinutelyWeather]
data.hourly # => Array[OpenWeather::Models::OneCall::HourlyWeather]
data.daily # => Array[OpenWeather::Models::OneCall::DailyWeather]
data.alerts # => Array[OpenWeather::Models::OneCall::Alert]

Exclude minutely and hourly data.

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

Historical Weather

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

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:

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

Alternatively, call register! on an instance of Station:

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

List Stations

To list all stations, call the client method:

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

Get Station

To get a station, call the client method:

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

Update Station

To update a station, call the client method:

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

Alternatively, call update! on an instance of Station:

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

Delete Station

To delete a station, call the client method:

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

Create Measurements

To create measurements, call the client method:

client.create_measurements([
  {
    "station_id": -1,
    "dt": 1479817340,
    "temperature": 18.7,
    "wind_speed": 1.2,
    "wind_gust": 3.4,
    "pressure": 1021,
    "humidity": 87,
    "rain_1h": 2,
    "clouds": [
      {
        "condition": 'NSC'
      }
    ]
  }
]) # => nil

Get Measurements

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

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

Configuration

You can configure client options, globally.

OpenWeather::Client.configure do |config|
  config.api_key = '1a2b3c4d5a6b7c8d9a8b7c6d5a4b3c2d1'
  config.user_agent = 'OpenWeather Ruby Client/1.0'
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.

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

data = client.weather(id: 2643743)
data.name # => 'London'
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.

data = client.current_weather(city: 'Moscow', units: 'metric') # => OpenWeather::Models::City::Weather

data.main.temp_max # => 12, degrees Celcius, metric as requested
data.main.temp_max_c # => 12, degrees Celcius
data.main.temp_max_k # => 285.15, degrees Kelvin
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.

data.wind.speed # => 3, in meters per second, metric as requested
data.main.speed_mph # => 6.71, miles per hour
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.

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

data = client.weather(id: 2643743)
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 and License

Copyright (c) 2020, Daniel Doubrovkine

This project is licensed under the MIT License.

open-weather-ruby-client's People

Contributors

dblock avatar dgarwood avatar mattlindsey avatar petergoldstein avatar sunny avatar troya2 avatar wasabigeek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

open-weather-ruby-client's Issues

One Call API 2.5 to be closed

Got this email.

We would like to inform you about our plans to complete the migration from One Call 2.5 to One Call 3.0 that started 2 years ago. In line with this, access to One Call 2.5 will be finally closed in June 2024.

One Call 3.0 provides you with significantly advanced business-demanded features such as a minute forecast for 1 hour, 4 days forecast for any timestamp, a daily forecast for 8 days, including a human-readable summary, historical data (45-year archive) for timestamps, and with daily aggregation, 1.5-year long-term forecast with daily aggregation, and others.

https://openweathermap.org/one-call-transfer

There are quite a few 2.5 references

OpenSSL::SSL::SSLError on Heroku

When using Heroku’s default stack, using this gem generates an SSL error.

This is due to Ruby not being able to find the certification authority certificates (CA Certs) used to verify the authenticity of the request.

Problem xith the {:id} of [GET] /stations/{:id} - [PUT] /stations/{:id} and [DELETE] /stations/{:id} in OpenWeather 3.0

Hello Daniel,

I am writing programming in python to send my weather data to the OpenWeather site.
Unfortunately the documentation (https://openweathermap.org/stations) is not very detailed...

I create the stations, transmit the data, retrieve it without problem.
However, I cannot change and delete the stations linked to my openweather account.

The documentation says [GET] /stations/{:id} - [PUT] /stations/{:id} and [DELETE] /stations/{:id} but I can't find how "{:id}" must be formulated! :-(

I saw that you had written the same thing in ruby but couldn't find any inspiration! :-(

Would you be kind enough to email me a simple example showing how these [GET] [PUT] and [DELETE] requests should be formulated with the {:id} field?

Thanking you - Very kind regards

Change endpoint to not include version

As is, the README for stations API will not work because you need to use the api.openweathermap.org/data/3.0 endpoint.

I propose to add api_root (e.g. https://api.openweathermap.org), api_path, e.g. data, and api_version, then combine these into endpoint.

Then document that this now supports 2.5 and 3.0 endpoints.

Support location names in other than ISO 3166

Not a huge deal, but data = client.current_weather(city: city, units: units) seems to blow up with Faraday::ResourceNotFoundError error when given given Atlanta, GA, imperial, but works fine with Atlanta, Georgia, imperial. Data issue?

Missing 'summary' in OpenWeather::Models::OneCall::DailyWeather

Looks like some properties are missing, like summary of a forecast. I might be able to help by adding them.

Also, I assume you don't want to support geocoding a name (city "New York City", for example) in order to return Forecast data? The user of this gem should do that?

Also, Is there a reason you don't include state or country in your examples? Aren't both supported?

data = client.current_weather(city: 'London') # => OpenWeather::Models::City::Weather
data = client.current_weather(city: 'London, UK') # => OpenWeather::Models::City::Weather

Specialize 429 errors

Rate limit returns a 429

{
"cod": 429,
"message": "Your account is temporary blocked due to exceeding of requests limitation of your subscription type. 
Please choose the proper subscription http://openweathermap.org/price"
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.