【问题标题】:Why am I getting a 401 when trying to connect to an external API in my Rails app?为什么在我的 Rails 应用程序中尝试连接到外部 API 时会收到 401?
【发布时间】:2019-10-06 01:30:22
【问题描述】:

我正在尝试使用同名的gem 调用开放天气地图 API。我正在尝试获取一个城市的当前预测。我查看了他们的常见问题解答,但无法解决。当我尝试加载 http://localhost:3000/forecasts/berlin_weather 时返回:Berlin forecast: {"cod"=>401, "message"=>"Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."} 这表明它正在连接,但不确定为什么我没有得到预期的响应。这是我的代码。

服务/open_weather_api.rb

class OpenWeatherApi
  require 'open_weather'

  def initialize(city, appid = "blahblahblah", units = "metric")
    @options = { city: city, units: units, APPID: appid }
  end

  def berlin_forecast
    OpenWeather::Forecast.city(@options)
  end
end

forecasts_controller.rb

class ForecastsController < ApplicationController

  def berlin_weather
    @forecast = OpenWeatherApi.new("Berlin").berlin_forecast
  end
end

berlin_weather.html.erb

<p>Berlin forecast: <%= @forecast %></p>

【问题讨论】:

  • 是否正在设置 API 密钥,就像错误消息所暗示的那样?
  • @bo-oz 是的,API 密钥已在我的服务类中设置。一旦我开始工作,就会将它添加到加密的凭据中。
  • 我会向 gem 作者打开一个问题,可能 API 中发生了一些变化。查看 Open Weathers API 文档并将其与 gem 的功能进行比较。

标签: ruby-on-rails openweathermap


【解决方案1】:

在向 API 发出请求之前,您应该注册并从他们那里获取 API KEY! 请按照此处的说明进行操作! https://openweathermap.org/appid

然后当他们为您提供密钥时,您可以在请求中使用此密钥!

def initialize(city, appid = "API KEY WHAT THEY WILL GIVE YOU", units="metric")
    @options = { city: city, units: units, APPID: appid }      
end

【讨论】:

  • 是的,我已经这样做了。它不在我的示例代码中,因为我不希望每个人都知道我的密钥,所以我将其替换为“blahblahblah”
【解决方案2】:
require 'open_weather'

# get current weather by city name
OpenWeather::Current.city("Cochin, IN", options)

您还需要提供国家/地区代码。 取自 open_weather ruby​​ 包装器 github 页面的代码示例。

编辑

https://openweathermap.org/data/2.5/forecast/daily/?appid=b6907d289e10d714blah&id=1298824&units=metric

我认为注册时发送到您邮箱的 api 密钥是错误的。您必须检查 openweathermap.org 中的网络调用才能获取真正的 api 密钥

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 1970-01-01
    • 2015-11-21
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多