首页 > 解决方案 > 为什么我的 API 请求使用 HTTParty 返回 400 响应?

问题描述

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

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

我已经在 Postman 中使用我的 API 密钥对其进行了测试,它工作正常,但使用我的代码返回"cod":"400","message":"Nothing to geocode"

谁能看到我哪里出错了?这是我的代码。

服务/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

预测控制器.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 %>

路线.rb

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

标签: ruby-on-railsrubyhttpartyopenweathermap

解决方案


该错误描述了自身:

"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. 所以这是覆盖initialize方法的默认值OpenWeatherApi。由于您案例中的 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

推荐阅读