ruby-on-railsrubyruby-on-rails-6ruby-grape

Grape API malformed parameters


I'm trying to make a post endpoint, with multiple nested parameters but the params are not as expected

I have the following parameters definitions for the endpoint:

params do
  requires :p2 do
    optional :p3
    requires :p4, as: :p4_new
    requires :p5, as: :p5_new do
      requires :p6, as: :p6_new
    end
  end
end

So I put a debugger in the first line of the endpoint and I am expecting the parameters to look like this:

{
  "p2": {
    "p3": 1,
    "p4_new": "Ceva nume",
    "p5_new": {
      "p6_new": 1,
    }
  }
}

But the actual parameters are malformed, it gives me both the newly named parameters and the old name for the parameters, in a chaotic order. It doesn't make any sense. Does anyone know what is going on here?


Solution

  • You're seeing the difference between params and declared(params). The documentation on renaming params specifies that if you want only the renamed parameters that you need to use declared(params):

    You can rename parameters using as, which can be useful when refactoring existing APIs:

    resource :users do
      params do
        requires :email_address, as: :email
        requires :password
      end
      post do
        User.create!(declared(params)) # User takes email and password
      end
    end
    

    The value passed to as will be the key when calling declared(params)

    I assume that you're calling params which is giving you both the original and the renamed parameters merged together. Switch to declared(params) to get just the renamed parameters.