Ruby-on-rails 从 Rails 应用程序使用 REST API

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5386232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:44:12  来源:igfitidea点击:

Consuming REST API from Rails Application

ruby-on-railsapiweb-applicationsrest

提问by licorna

I'm building my first Rails App and I want it to consume everything from a REST API. What I want to do is to have Rails serve my web application as a frontend to my API. As far as I've read (I'm staring with Rails right now), Rails has a lot of potential with ORMs and direct access to database systems. My platform, on the other hand, is designed in such a way that every layer is accessed via a defined interface (in this case a REST API), so no databases are read from any client, but via their interfaces.

我正在构建我的第一个 Rails 应用程序,我希望它使用 REST API 中的所有内容。我想要做的是让 Rails 将我的 Web 应用程序作为 API 的前端提供服务。据我所知(我现在正在关注 Rails),Rails 在 ORM 和直接访问数据库系统方面有很大的潜力。另一方面,我的平台的设计方式是通过定义的接口(在本例中为 REST API)访问每一层,因此不会从任何客户端读取数据库,而是通过它们的接口。

For example, my API exposes the following resource:

例如,我的 API 公开了以下资源:

https://api.example.com/v1/users/feature-xxx [GET]

And I want my web app to have a page like:

我希望我的网络应用程序有一个页面,如:

https://example.com/feature

So the users will visit this URL and when logged in, the Rails app will request the data to generate this dynamic content from my API.

因此,用户将访问此 URL,并且在登录时,Rails 应用程序将请求数据以从我的 API 生成此动态内容。

The question is:

问题是:

  • What are the necessary steps for my Rails Application to consume its datafrom a HTTP/Rest Backend? and,
  • Is this a good design for a Rails app?
  • 我的 Rails 应用程序从 HTTP/Rest 后端使用其数据的必要步骤是什么?和,
  • 对于 Rails 应用程序来说,这是一个好的设计吗?

Thanks!

谢谢!

回答by Duke

ActiveResource is no longer being included in Rails 4.0. Word is that it is barely maintained these days, and is difficult to customize for REST API endpoints that are not formulated according to the "Rails way".

ActiveResource 不再包含在 Rails 4.0 中。话说现在它几乎没有维护,并且很难为不是根据“Rails 方式”制定的 REST API 端点进行自定义。

After some research, I am heavily favoring using Faraday. It includes support for utilizing different HTTP request adapters. It can use EventMachine directly, or libraries like Typhoeus for when you decide to get concurrent. It also supports Rack-like middleware for seamlessly including, say, authentication.

经过一些研究,我非常喜欢使用Faraday。它支持使用不同的 HTTP 请求适配器。当您决定并发时,它可以直接使用 EventMachine,也可以使用 Typhoeus 之类的库。它还支持类似机架的中间件,以无缝地包括身份验证。

For a REST ORM in Rails that is easily configurable, the relatively new (about a year old) Herlooks very promising, and utilizes Faraday.

对于 Rails 中易于配置的 REST ORM,相对较新(大约一年)的Her看起来非常有前途,并且使用了 Faraday。

Update

更新

I completely <3 RestClient. So simple. If you need ORM-style functionality, then you'll need a higher-level abstraction, but for simply consuming an API, you can't beat its simplicity. It just does exactly what it's supposed to do without fuss, has sensible defaults, and has the ability to set advanced options such as auth headers.

我完全 <3 RestClient。很简单。如果您需要 ORM 风格的功能,那么您将需要更高级别的抽象,但对于简单地使用 API,您无法击败它的简单性。它只是做它应该做的事情,没有大惊小怪,具有合理的默认值,并且能够设置高级选项,例如身份验证标头。

回答by Chirantan

I would highly recommend ActiveResourcefor your requirement. My experience with it has been really good. Provided that the API you intend to consume is reallyREST, I don't think there is any cleaner design for consuming data through REST API. From it's README,

我强烈推荐ActiveResource来满足您的要求。我对它的体验非常好。假设您打算使用的 API确实是REST,我认为没有任何更简洁的设计可以通过 REST API 使用数据。从它的自述文件,

Active Resource

Active Resource (ARes) connects business objects and Representational State Transfer (REST) web services. It implements object-relational mapping for REST web services to provide transparent proxying capabilities between a client (ActiveResource) and a RESTful service (which is provided by Simply RESTful routing in ActionController::Resources).

Philosophy

Active Resource attempts to provide a coherent wrapper object-relational mapping for REST web services. It follows the same philosophy as Active Record, in that one of its prime aims is to reduce the amount of code needed to map to these resources. This is made possible by relying on a number of code- and protocol-based conventions that make it easy for Active Resource to infer complex relations and structures. These conventions are outlined in detail in the documentation for ActiveResource::Base.

Overview

Model classes are mapped to remote REST resources by Active Resource much the same way Active Record maps model classes to database tables. When a request is made to a remote resource, a REST XML request is generated, transmitted, and the result received and serialized into a usable Ruby object.

Configuration and Usage

Putting Active Resource to use is very similar to Active Record. It's as simple as creating a model class that inherits from ActiveResource::Base and providing a site class variable to it:

class Person < ActiveResource::Base  
  self.site = "http://api.people.com:3000/" 
end 

Now the Person class is REST enabled and can invoke REST services very similarly to how Active Record invokes life cycle methods that operate against a persistent store.

# Find a person with id = 1 
ryan = Person.find(1) 
Person.exists?(1)  # => true 

As you can see, the methods are quite similar to Active Record's methods for dealing with database records. But rather than dealing directly with a database record, you're dealing with HTTP resources (which may or may not be database records).

活动资​​源

活动资​​源 (ARes) 连接业务对象和具象状态传输 (REST) Web 服务。它为 REST Web 服务实现对象关系映射,以在客户端 (ActiveResource) 和 RESTful 服务(由 ActionController::Resources 中的简单 RESTful 路由提供)之间提供透明代理功能。

哲学

Active Resource 尝试为 REST Web 服务提供一致的包装器对象关系映射。它遵循与 Active Record 相同的理念,其主要目标之一是减少映射到这些资源所需的代码量。这是通过依赖许多基于代码和协议的约定实现的,这些约定使 Active Resource 可以轻松推断复杂的关系和结构。ActiveResource::Base 的文档中详细概述了这些约定。

概述

模型类通过 Active Resource 映射到远程 REST 资源,与 Active Record 将模型类映射到数据库表的方式非常相似。当对远程资源发出请求时,会生成、传输 REST XML 请求,接收结果并将其序列化为可用的 Ruby 对象。

配置和使用

使用 Active Resource 与 Active Record 非常相似。它就像创建一个继承自 ActiveResource::Base 的模型类并为其提供站点类变量一样简单:

class Person < ActiveResource::Base  
  self.site = "http://api.people.com:3000/" 
end 

现在 Person 类已启用 REST,并且可以调用 REST 服务,这与 Active Record 调用针对持久存储操作的生命周期方法的方式非常相似。

# Find a person with id = 1 
ryan = Person.find(1) 
Person.exists?(1)  # => true 

如您所见,这些方法与 Active Record 处理数据库记录的方法非常相似。但不是直接处理数据库记录,而是处理 HTTP 资源(可能是也可能不是数据库记录)。

Read more here...

在这里阅读更多...

回答by Eric

If you decide to not use an HTTP client library like Farady or HTTParty, you can use open-uri to grab the data from the endpoint that you need and parse it with JSON.

如果你决定不使用像 Farady 或 HTTParty 这样的 HTTP 客户端库,你可以使用 open-uri 从你需要的端点获取数据并用 JSON 解析它。

Requirements: open-uri and json

要求:open-uri 和 json

In the controller:

在控制器中:

@people = JSON.parse(open("http://api.people.com:3000/people").read, symbolize_names: true)

In the view:

在视图中:

<% @people.each do |person| %>
    Name:<%= person[:name] %>
    Age:<%= person[:age] %>
<% end %>

回答by Alan Peabody

Yes it can be a good design.

是的,它可以是一个很好的设计。

My advice it to read "Service Oriented Design with Ruby And Rails: http://www.amazon.com/Service-Oriented-Design-Rails-Addison-Wesley-Professional/dp/0321659368

我的建议是阅读“使用 Ruby 和 Rails 进行面向服务的设计:http: //www.amazon.com/Service-Oriented-Design-Rails-Addison-Wesley-Professional/dp/0321659368

It focus on Restful Ruby apps just like your example with an emphasis on scaling and performance. It also investigates different frameworks (Rack, Sinatra, Rails) and the roles they fill well.

就像您的示例一样,它专注于 Restful Ruby 应用程序,并强调扩展性和性能。它还调查了不同的框架(Rack、Sinatra、Rails)以及它们很好地填充的角色。

Unfortunately I have not implemented this strategy my self (yet!) so I can not give you any first hand advice.

不幸的是,我自己还没有实施这个策略(还没有!)所以我不能给你任何第一手的建议。