だから、あなたは標準的な経路とアクションを活用する必要があります/メッセージ/ APIにmain_urlに送信されています。お使いのコントローラが今api/v1
内にネストされ
Rails.application.routes.draw do
resources :messages
namespace :api, defaults: {format: 'json'} do
namespace :v1 do
resources :messages
end
end
end
注:routes.rb
では、あなたのような何かをするかもしれません。これにより、パスをapiとして識別し、時間の経過とともにバージョンを維持することができます。その固体の練習。また、あなたのWebアプリケーション用の標準messages
リソースがあることにも注意してください。このコントローラは、Api::V1::BaseController
から継承することを
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関連のクライアント認証(キー/トークンのチェックなど)を行うように設定したコントローラになります。おそらく、何かのように、:
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レスポンスを得るにはOr:
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
は、以前の質問から受け入れられたコードであることに注意しましょう。
コントローラのどこかで 'respond_to do | format |'を使っていますか? – jvillian
いいえ、私のルートに指定されたばかりです(投稿に追加しました) –
あなたは間違っていると思います。私はちょっと答えを投稿します。 – jvillian