Michael Glenn
Michael Glenn

Reputation: 1882

Why are the requires directives in a Grape API param block not being observed?

I have a Grape API class Customer subclassing Grape::API. The parameters designated requires are not being validated. If a request is made without these parameters the code continues without throwing an exception. How can I enabled requires validation?

module API
  module V1
    # API interface for users
    class Customers < Grape::API
      include API::V1::Defaults

      helpers do
        def customer_options(params)
          {
            user_id: params.user_id,
            phone: params.phone,
            date_of_birth: params.date_of_birth
          }
        end
      end

      resource :customers do
        desc "Create a customer"
        post do
          params do
            requires :user_id, type: Integer, desc: "ID of associated user record", allow_blank: false
            requires :phone, type: String, desc: "Applicant's phone number", allow_blank: false
            requires :date_of_birth, type: String, desc: "Applicant's date of birth", allow_blank: false
          end

          options = customer_options(permitted_params)

          customer = nil
          Customer.transaction do
            customer = Customer.create!(options)
          end
          result = {
            id: customer.id,
            phone: customer.phone,
            user_id: customer.user_id
          }
          result["date_of_birth"] = customer.date_of_birth if
            customer.date_of_birth.present?
          result
        end
      end
    end
  end
end

Upvotes: 0

Views: 31

Answers (1)

Michael Glenn
Michael Glenn

Reputation: 1882

After carefully comparing to other examples I realized I had put the params definition inside the post block which won't work. Splitting them enabled the validations to properly be identified and run.

resource :customers do
        desc "Create a customer"
        params do
          requires :user_id, type: Integer, desc: "ID of associated user record", allow_blank: false
          requires :phone, type: String, desc: "Applicant's phone number", allow_blank: false
          requires :date_of_birth, type: String, desc: "Applicant's date of birth", allow_blank: false
        end
        post do
          options = customer_options(permitted_params)

Upvotes: 0

Related Questions