Rails应用调用OpenWeatherMap API返回401错误的求助
Hey there, let's tackle that 401 error you're hitting—it's a straightforward fix once we break down what's going on! That {"cod"=>401, "message"=>"Invalid API key"} response leaves no doubt: your API key is either invalid, not activated yet, or being passed incorrectly to the gem. Here's how to fix this step by step:
1. Grab a Valid, Activated API Key
First off, replace that placeholder "blahblahblah" with your real OpenWeatherMap API key from your account dashboard. A quick heads-up: newly generated keys can take 10-15 minutes to activate on their end, so don't stress if it doesn't work instantly after generating it.
2. Stop Hardcoding Your API Key (Security Best Practice)
Never hardcode secrets like API keys directly in your code—this is a huge security risk, especially if you're pushing code to version control. Use environment variables instead:
- Add
gem 'dotenv-rails'to your Gemfile, then runbundle install. - Create a
.envfile in your project root (make sure to add this file to.gitignore!) and add your key:OPENWEATHER_API_KEY=your_real_api_key_here
3. Fix Your Service Class
Update your OpenWeatherApi class to use the environment variable, and double-check the gem's parameter formatting (some versions expect lowercase appid instead of uppercase APPID):
# services/open_weather_api.rb class OpenWeatherApi require 'open_weather' def initialize(city, units = "metric") @options = { city: city, units: units, appid: ENV['OPENWEATHER_API_KEY'] # Lowercase 'appid' matches most recent gem versions } end # Quick note: If you want CURRENT weather (not a 5-day forecast), use OpenWeather::Current.city def current_forecast OpenWeather::Current.city(@options) end # Keep this if you specifically need the 5-day forecast def five_day_forecast OpenWeather::Forecast.city(@options) end end
I added a note here because your code uses OpenWeather::Forecast.city (which returns a 5-day forecast) but you mentioned wanting the current weather—this is a common mix-up with the gem!
4. Update Controller and View for Better Readability
Tweak your controller to use the updated service methods, and make your view handle success/error states more cleanly:
# forecasts_controller.rb class ForecastsController < ApplicationController def berlin_weather weather_service = OpenWeatherApi.new("Berlin") @forecast = weather_service.current_forecast end end
# berlin_weather.html.erb <p>Berlin Current Forecast:</p> <% if @forecast.is_a?(Hash) && @forecast['cod'] == 200 %> <ul> <li>Temperature: <%= @forecast['main']['temp'] %> °C</li> <li>Condition: <%= @forecast['weather'].first['description'].capitalize %></li> <li>Humidity: <%= @forecast['main']['humidity'] %>%</li> </ul> <% else %> <p>Error fetching forecast: <%= @forecast['message'] if @forecast.is_a?(Hash) %></p> <% end %>
5. Double-Check the Gem Docs
If you still run into issues, confirm you're using the latest version of the open_weather gem and cross-reference its documentation to ensure method signatures and parameter keys match—gem updates can occasionally change these details!
Once you swap in your real, activated API key (and wait a few minutes if it's new), this should resolve the 401 error and return the weather data you're expecting.
内容的提问来源于stack exchange,提问作者Steve

