我有一个带有一些标准路由的rails应用程序,我想在其中添加一些API端点。
我想我只需要添加一些路由(可能在scope '/api'
下),创建一些扩展ActionController::API
的新控制器,然后做一些事情让rails神奇地知道如何呈现JSON数据
有没有关于如何做到这一点的指南?我能找到的所有内容都只涉及创建API和#39;应用程序,但没有讨论向现有Web应用程序添加一些API端点。
编辑:我特意寻找rails 5解决方案
答案 0 :(得分:6)
"经典"或仅API应用程序非常小。仅API应用程序可以缩小API中不需要的一些中间件和组件。
否则,构建实际API组件的步骤几乎完全相同。
您将首先为API控制器选择不同的超类。您的API控制器不需要ApplicationController上的所有垃圾,您将以不同的方式处理许多方面,例如身份验证。
Rails 5有ActionController::API
,在之前的版本中,您将使用ActionController::Metal
并包含所需的模块。
# app/controllers/api_controller.rb
class ApiController < ActionController::API
# Do whatever you would do in ApplicationController
end
然后设置路线:
namespace :api, defaults: { format: :json }
resources :things
end
和控制器:
module API
class ThingsController < ApiController
before_action :set_thing, except: [:create, :index]
def show
render json: @thing
end
def index
render json: @things = Thing.all
end
def create
@thing = Thing.create(thing_params)
if @thing.save
head :created, location: [:api, @thing]
else
render json: @thing.errors, status: :bad_entity
end
end
# ...
end
end
构建API有很多方面,例如版本控制和JSON序列化策略,你会发现很多关于这个主题的教程 - 只是不要挂在API上。< / p>
答案 1 :(得分:2)
v1
)在config/routes.rb
添加以下路线
在名为v1
在v1
目录中创建一个控制器,如下面的那个
#goes in routes
namespace 'v1', defaults: {format: 'json'} do
resources :products, only: [:create]
end
#controller
module V1
class ProductsController < ActionController::API
def create
#some code
end
end
end
随机智慧
在这里寻求一些建议:
https://www.codementor.io/ruby-on-rails/tutorial/creating-simple-api-with-rails
https://www.airpair.com/ruby-on-rails/posts/building-a-restful-api-in-a-rails-application
答案 2 :(得分:0)
使用类似
的内容 namespace :api, defaults: {format: 'json'} do
默认你的api控制器只渲染json。
您所描述的其余部分是一个不错的实现,正是我们今天在生产中使用的。一些端点仍然是纯粹的轨道,但大多数是api json只有客户端MVC做重负荷。这是从默认rails应用程序迁移到客户端MVC时的常见用例。
另一个好的问题是你创建的基础api控制器的api控制器,它是从应用程序控制器继承的。