首页 > 解决方案 > Rails - 为多个 API 构建适配器

问题描述

关于在 Rails 中为多个 API 构建适配器的想法,我需要帮助。我先解释一下:

我希望我的客户能够向我的应用程序添加第三方扩展。我有一个模型Extension和另一个CustomExtension

我自己创建扩展,然后出现在“可用扩展”部分。当用户点击“添加扩展”时,它会转到“我的扩展”部分(由 表示CustomExtension)。

我创建了一个名为的扩展程序API Connector,我希望它按如下方式工作:当用户单击“添加扩展程序”时,他会选择一个类别(我自己定义)API 是其中的一部分(如“客户评论”)。然后,用户将输入一些字段,例如 anapi_key或 an api_endpoint。然后,我希望能够连接到这个 api 并显示一些与 api 相关的其他字段(比如它来自哪里的名称,例如:对于客户评论,如果用户为它连接了 Google API,我想将扩展名从 API 连接器重命名为 Google 客户评论)。

简而言之,我希望能够使用相同的接口连接多个不同的 API,并让用户在我的项目中不实现 API 的情况下进行操作。

编辑——更多信息:

API 可能没有相同的身份验证过程或相同的属性。它们可以彼此非常不同。

技术要求是 RESTful API 和基于 JSON 的。

标签: ruby-on-railsrubyapi

解决方案


据我了解,您想根据用户定义的参数为用户创建一种连接到运行时未知的 API 的方法?如果是这样,有一个 Ruby 库(现在从 Rails 中删除)是为了轻松连接到 REST API 而构建的,也许这对这里有帮助?

https://github.com/rails/activeresource

所以,假设我想从 Cat API 中提取品种信息。这是一些示例代码,可以让我在运行时定义它:

require "active_resource"
require "ostruct"

##
# This is just a data-store. It could be an ActiveRecord object or some other set 
# of values that you need for the API. You'll have to establish your own criteria
# for types of API configuration you can support
@config = OpenStruct.new(
  # We need to set a custom header and value
  header_name: 'x-api-key',
  # get your own key here: https://docs.thecatapi.com
  header_value: '96120fe6-0846-41c6-9a1d-8a70e691dd47',
  base_url: "https://api.thecatapi.com/v1/",
  # What's the path where this resource can be found
  resource_name: "breeds",
  # don't add ".json" to the URLs
  use_json_extension: false,
)

##
# Create an anonymous class at runtime that inherits from ActiveResource::Base
@custom_extension = Class.new(ActiveResource::Base)

##
# Config our class based on the user-provided values.
@custom_extension.class_eval do
  self.include_format_in_path = @config.use_json_extension
  self.site = @config.base_url
  self.headers[@config.header_name] = @config.header_value
  self.element_name = @config.resource_name
  # Log errors here
  self.logger = Logger.new("./output.log")
end

puts @custom_extension.all.to_s

运气好的话,应该会为您下载猫品种列表。这应该足以证明这个概念。ActiveResource 的文档可以在这里找到:https ://rubydoc.info/gems/activeresource

请注意不要从用户提供的来源导入危险内容!

希望这就是你要找的东西?


推荐阅读