Ruby on Rails是一种基于Ruby编程语言的开发框架,它提供了一套简单而强大的工具和约定,用于快速构建Web应用程序。在Ruby on Rails中调用外部API并显示结果可以通过以下步骤实现:
require 'net/http'
def call_external_api
url = URI.parse('https://api.example.com/endpoint')
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true if url.scheme == 'https'
request = Net::HTTP::Get.new(url.request_uri)
response = http.request(request)
if response.code == '200'
@result = JSON.parse(response.body)
else
@error = "API request failed with code #{response.code}"
end
end
在上述示例中,我们使用了Net::HTTP库来发起GET请求,并将响应解析为JSON格式。
<% if @result %>
<% @result.each do |item| %>
<p><%= item['name'] %></p>
<% end %>
<% elsif @error %>
<p><%= @error %></p>
<% end %>
上述代码将遍历API调用返回的结果,并显示每个项目的名称。如果API调用失败,将显示错误消息。
get '/call_external_api', to: 'your_controller#call_external_api'
上述代码将将GET请求映射到名为call_external_api的动作,该动作位于your_controller控制器中。
这样,当访问/call_external_api路径时,Rails应用程序将调用外部API并显示结果。
对于Ruby on Rails调用外部API并显示结果的示例,你可以参考以下腾讯云产品和文档:
请注意,以上链接仅作为示例,你可以根据实际需求选择适合的腾讯云产品。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云