Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to filter the params for a request to a Grape API?

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.

like image 311
Mike Hall Avatar asked Dec 05 '25 16:12

Mike Hall


2 Answers

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

like image 122
Erem Avatar answered Dec 07 '25 04:12

Erem


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.

like image 23
RantriX Avatar answered Dec 07 '25 06:12

RantriX