因此,您应该利用标准路线和操作。在routes.rb 中,您可能会执行以下操作:
Rails.application.routes.draw do
resources :messages
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :messages
end
end
end
请注意,您的控制器现在嵌套在 api/v1 中。这使您可以将路径标识为 api 并随着时间的推移维护版本。那固体的做法。另请注意,您的 Web 应用程序有一个标准的 messages 资源。
然后,您的控制器将如下所示:
class Api::V1::MessagesController < Api::V1::BaseController
def create
@message = Message.new(message_params)
respond_to do |format|
if @message.save
@message.update(url: "http://link.com/#{@message.id}")
format.json { render json: create_hsh, status: :ok }
format.xml { render xml: create_hsh, staus: :ok }
else
format.json { render json: @message.errors, status: :unprocessable_entity }
format.xml { render xml: @message.errors, status: :unprocessable_entity }
end
end
end
def show
respond_to do |format|
if @message = Message.find_by(id: params[:id])
format.json { render json: show_hsh, status: :ok }
format.xml { render xml: show_hsh, status: :ok }
else
format.json { render json: {errors: :not_found}, status: :not_found }
format.xml { render xml: {errors: :not_found}, status: :not_found }
end
end
end
private
def create_hsh
@message.attributes.with_indifferent_access.slice(:url)
end
def show_hsh
attr = @message.attributes.with_indifferent_access
attr.slice(:foo, :bar).merge!(message: attr[:text])
end
def message_params
params.require(:message).permit(:text)
end
end
请注意,此控制器继承自 Api::V1::BaseController。那将是您设置的控制器以执行与 api 相关的客户端身份验证(密钥/令牌检查等)。可能是这样的:
class Api::V1::BaseController < ActionController::API
before_action :authorize
def authorize
# do your checks in a way that results in a variable @authorized?
render(json: {errors: :unauthorized}, status: :unauthorized) unless @authorized?
end
end
所以,现在您使用单个控制器操作来响应所有格式类型(您选择提供)。然后,您的客户会发布如下内容:
http://your.api.com/messages.json
获取 json 响应。或者:
http://your.api.com/messages.xml
获取 xml 响应。您可能会注意到上面写着:namespace :api, defaults: {format: 'json'} do。这意味着您的客户可以致电:
http://your.api.com/messages
它将默认为json 格式。
现在您没有一堆随机端点(例如mssg_as_json),只有您的客户期望的常规 RESTful 端点。您的 API 客户会因此而爱上您。
您会注意到 show_hsh 是您之前问题中接受的代码。