Domanda

If I set up param validation on a Grape API request is it possible to get a hash of just the validated params?

desc "My Grape API request handler"
params do
  requires :name
  optional :description
end
post do
   puts params.inspect # has all the params passed to request, 
                       # even params not defined in validation block
end

Is there another way to just get the params limited to the ones listed in the param validation block? Kind of like how Rails strong_parameters works.

È stato utile?

Soluzione 2

Assuming you're using rails...

You can create a strong param helper in the base class of your api so your mounted endpoints can also have this helper:

module StrongParamHelpers
  def strong_params
    ActionController::Parameters.new(params)
  end
end

Include this in the base class of your api:

helpers StrongParamHelpers

Then in each api endpoint class, you create another helper method kind of similar to how rails does it:

helpers do
  def user_params
    strong_params.require(:user).permit(:username, :email) # etc...
  end
end

Then just call user_params in your routes:

desc "My Grape API request handler"
params do
  requires :user do
    optional :username
    optional :email
    # etc
  end
end
post do
   User.create user_params
end

Hope that helps.

Altri suggerimenti

It might be late but for anybody passing by, you can use declared_params. https://github.com/ruby-grape/grape#declared

It might be easier to start with Rack::Utils.parse_nested_query

For example:

params = Rack::Utils.parse_nested_query(env['QUERY_STRING'])
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top