Search code examples
ruby-on-railsgrape-api

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.


Solution

  • 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.