http - 用于 API 调用问题的 rails faraday

我在调用 API 时收到未定义的方法“body”错误;

网址 - https://api.company.com/api/v1/dept/person/query/empid/22435678

我还需要传递用户名和密码。这是我正在尝试的。我究竟做错了什么?

require 'faraday'
  require 'faraday/net_http'
  Faraday.default_adapter = :net_http


  def show

    @response = Faraday.new('https://api.company.com/api/v1/dept/person/query/empid/22435678') do |conn|
      conn.request :authorization, :basic, 'testuser', '77hfhncqjwnd'
    end

  end

回答1

您只设置了 Faraday 对象,并没有使用它发送实际请求。

# NOTE: configure faraday
api = Faraday.new('https://api.company.com/api/v1/dept/person/query/empid/22435678') do |conn|
  conn.request :authorization, :basic, 'testuser', '77hfhncqjwnd'
end

# NOTE: send requests to api `get`, `post` etc.
@response = api.get.body

这是首选设置:

api = Faraday.new('https://api.company.com/') do |conn|
  conn.request :authorization, :basic, 'testuser', '77hfhncqjwnd'
  # conn.response :json # automatically parse responses as json, if needed
end

@response = api.get("api/v1/dept/person/query/empid/22435678").body

https://lostisland.github.io/faraday/usage/

相似文章

最新文章