为什么我的API请求使用HTTParty返回400响应?

时间:2019-06-06 12:01:00

标签: ruby-on-rails ruby httparty openweathermap

我正在创建一个简单的Rails应用程序,该应用程序将从Open Weather Map API中获取数据,并返回在表单字段中搜索的城市的当前天气数据。我希望API调用看起来像这样:

http://api.openweathermap.org/data/2.5/weather?q=berlin&APPID=111111

我已经使用API​​密钥在Postman中对其进行了测试,但是效果很好,但是对于我的代码,它返回了"cod":"400","message":"Nothing to geocode"

有人可以看到我要去哪里了吗?这是我的代码。

services / open_weather_api.rb

class OpenWeatherApi
  include HTTParty
  base_uri "http://api.openweathermap.org"

  def initialize(city = "Berlin,DE", appid = "111111")
    @options = { query: { q: city, APPID: appid } }
  end

  def my_location_forecast
    self.class.get("/data/2.5/weather", @options)
  end
end

forecasts_controller.rb

class ForecastsController < ApplicationController
  def current_weather
    @forecast = OpenWeatherApi.new(@options).my_location_forecast
  end
end

current_weather.html.erb

<%= form_tag(current_weather_forecasts_path, method: :get) do %>
  <%= text_field_tag(:q) %>
  <%= submit_tag("Search") %>
<% end %><br>

<%= @forecast %>

routes.rb

Rails.application.routes.draw do
  root 'forecasts#current_weather'
  resources :forecasts do
    collection do
      get :current_weather
    end
  end
end

1 个答案:

答案 0 :(得分:1)

错误描述了自己:

"cod":"400","message":"Nothing to geocode"

这意味着您没有在查询中提供城市。导致此错误的一种可能原因是,您在initialize方法中用以下行中的控制器的@options变量覆盖了默认值:

class ForecastsController < ApplicationController
  def current_weather
    @forecast = OpenWeatherApi.new(@options).my_location_forecast
  end
end

根据您提供的信息,您尚未在控制器中定义@options变量,或者它是nil。因此,这将覆盖initializeOpenWeatherApi方法的默认值。 由于您的情况下的appid不会更改,因此只有城市名称会更改,因此您可以从控制器发送它。

def current_weather
  @city = params[:city] // the city you want to send to API. Change it with your value
  @forecast = OpenWeatherApi.new(@city).my_location_forecast
end