我已阅读了许多关于创建和使用REST API的文章,但我还没有找到任何有关如何在单个应用程序中执行此操作的文档。Rails REST API和在相同的应用程序中使用
我曾经有一个完整的MVC应用程序on Rails的工作,但我们决定改变它使用REST API为其他发展提供数据,但我们真的不知道该怎么做。我们所做的是使用API控制器创建一个api/v1 /文件夹结构。
我们有一个非常简单的控制器进行测试:
class Api::V1::ProductsController < ApplicationController
def list
@products = Product.limit(100)
render json: @products, status: 200
end
end
在我的路线文件我有以下几点:
namespace :api do
namespace :v1 do
scope '/products' do
get '/list' => 'products#list'
end
end
end
当我启动服务器和访问http://localhost:3000/api/v1/products/list它按预期工作。
但现在,我想从同一个应用程序使用它,所以我有以下代码中的另一个的ProductsController:
class ProductsController < ApplicationController
include HTTParty
base_uri "http://1ocalhost:3000/api/v1/products"
format :json
def index
@products = self.class.get("/list?category_id=22"))
end
end
当我试图让这条路线,它显示在下面服务器控制台:
Started GET "/" for 127.0.0.1 at 2017-05-08 11:58:30 -0400
Processing by ProductsController#index as HTML
Started GET "/api/v1/products/list?category_id=22" for 127.0.0.1 at 2017-05-08 11:58:31 -0400
Completed 500 Internal Server Error in 120213ms (ActiveRecord: 2.9ms)
Net::ReadTimeout (Net::ReadTimeout):
但是在抛出错误后,请求在后台正确完成。
我首先想知道,如果这是正确的做法;其次,为什么我得到那个超时,如果我在同一个服务器,并已测试了获得API的工作。
非常感谢你提前。
感谢您的回答,但是您只是回答为什么我会收到该错误。我仍然需要知道如何在不执行http请求的情况下调用该函数(我仍然需要REST API) – Kunstmann
@Kunstmann:什么函数?休息api端点?只能通过http调用。检查答案的最后部分,它包含一个可以帮助你的建议。 –