You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails应用调用OpenWeatherMap API返回401错误的求助

Fixing the OpenWeatherMap 401 Invalid API Key Error

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 run bundle install.
  • Create a .env file 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:36:29