我已閱讀了許多關於創建和使用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調用。檢查答案的最後部分,它包含一個可以幫助你的建議。 –